如何命名元组属性?

问题描述 投票:10回答:8

如何和“可能”组织从返回元组类型的方法返回与参数的名称,作为一个exapmle

private static Tuple<string, string> methodTuple()
{
    return new {Name = "Nick", Age = "Twenty"}; /*exception because need to new Tuple<string, string>(){Item1 = "Nick", Item2 = "Twenty"}o*/
}

并调用像methodTuple.Name这样的参数不像methodTuple.Item1....N

这可能吗?

UPD:我想用没有新命名类型的命名参数创建对象。

c# tuples
8个回答
13
投票

您需要声明一个帮助程序类来执行此操作。

public class MyResult
{
    public string Nick { get; set; }
    public string Age { get; set; }
}

你想要返回的是匿名类型。顾名思义你不知道它的名字是什么,所以你不能声明你的方法来返回它。

Anonymous Types (C# Programming Guide)

您不能将方法的字段,属性,事件或返回类型声明为具有匿名类型。同样,您不能将方法,属性,构造函数或索引器的形式参数声明为具有匿名类型。要传递匿名类型或包含匿名类型的集合作为方法的参数,可以将参数声明为类型对象。但是,这样做会破坏强类型的目的。如果必须存储查询结果或将它们传递到方法边界之外,请考虑使用普通的命名结构或类而不是匿名类型。

更新

C#7引入了语言内置的Tuple支持,它带有命名元组

(string name, int age) methodTuple()
{
    (...)
}

阅读docs.microsoft.com上的更多信息:https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#tuples


10
投票

在C#7.0(Visual Studio 2017)中有一个新选项:

(string first, string middle, string last) LookupName(long id)

6
投票

这与Tuple不可能,不。您需要创建自己的新命名类型才能执行此操作。


4
投票

现在可以从C#v7.0开始,将以前用于默认名称的元组属性命名为Item1Item2等。

命名元组文字的属性:

var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");

控制台上的输出:

名字-RBT_yo,raise-22,passon-dosa

从方法返回元组(具有命名属性):

static void Main(string[] args)
{
    var empInfo = GetEmpInfo();
    Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}

static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
    //This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
    return ("Rasik", "Bihari", "Rasik-PC", 1000);
}

控制台上的输出:

员工详细信息:Rasik,Bihari,Rasik-PC,1000

创建具有命名属性的元组列表

var tupleList = new List<(int Index, string Name)>
{
    (1, "cow"),
    (5, "chickens"),
    (1, "airplane")
};

foreach (var tuple in tupleList)
    Console.WriteLine($"{tuple.Index} - {tuple.Name}");

控制台输出:

1 - 牛5 - 鸡1 - 飞机

我希望我已经涵盖了一切。如果有什么我错过了,请在评论中给我一个反馈。

注意:我的代码片段使用C#v6的字符串插值功能作为详细的here


1
投票

我通常创建一个派生自Tuple的新类型,并映射您的显式属性以返回基类的ItemX属性。例如:

public class Person : Tuple<string, string>
{
    public Key(string name, string age) : base(name, age) { }

    public string Name => Item1;
    public string Age => Item2;
}

0
投票

不幸的是,使用“Tuple”类型是不可能的,因为它在MSDN中被定义为“Item1 ... N”。所以这个例外是有效的。

此方法可以通过3种方式进行编译:1。)将返回类型更改为对象 - 这将创建一个“匿名”类型,稍后您可以使用该类型。如果您想在以后访问“名称”或“年龄”属性而不需要一些额外的工作,这不是特别有用。 2.)将返回类型更改为动态 - 这将允许您访问“名称”和“年龄”属性,但会使整个程序(只是这个方法所在的DLL)稍慢,因为使用动态需要抛出打出一些强烈的打字。 3.)创建一个类并将其用作返回类型。

示例代码:

private static object ObjectTuple()
        {
            return new { Name = "Nick", Age = "Twenty" };
        }

        private static dynamic DynamicTuple()
        {
            return new { Name = "Nick", Age = "Twenty" };
        }

        private static Temp TempTuple()
        {
            return new Temp{ Name = "Nick", Age = "Twenty" };
        }

        class Temp
        {
            public string Name { get; set; }
            public string Age { get; set; }
        }

0
投票

按照我的说法,当你想从单个方法中返回或获取很多东西时,最好将其返回类型设置为CLASS,但如果你打算使用Tuple本身就是Class,那么为了更好地命名,这个新类应该从Tuple继承。例如如以下所说的。

 public CustomReturn ExecuteTask( int a, string b, bool c, object d )
        {
        // Calling constructor of CustomReturn Class to set and get values
          return new CustomReturn(a,b,c,d);
        }

        internal class CustomReturn 
        // for tuple inherit from Tuple<int,string,bool,object,double>
        { 
          //for tuple public int A{ get {this.Item1} private set;}

          public int A{get;private set;}
          public string B{get;private set;}
          public bool C{get;private set;}
          public object D{get;private set;}

          public CustomReturn (int a, string b, bool c, object d )
              // use this line for tuple ": base( obj, boolean )"
            {
              this.A = a;
              this.B = b;
              this.C = c;
              this.D = d;
            }

        }

    Main(args)
    {
      var result = ExecuteTask( 10, "s", true, "object" );
      // now if u have inherited Tuple for CustomReturn class then 

      // on doing result. you will get your custom name as A,B,C,D for //Item1,Item2,Item3,Item4 respectively also these Item1,Item2,Item3,Item4 will also be there.
    }

-4
投票

您可以尝试动态:

    private static dynamic methodTuple()
    {
        return new { Name = "Nick", Age = "Twenty" }; 
    }

...但是如已经提到的那样返回定义的类型或结构是最好的。

© www.soinside.com 2019 - 2024. All rights reserved.