Anonymous type and tuple

谁都会走 提交于 2019-12-03 05:36:43

问题


What is the difference between anonymous type and tuple?


回答1:


Anonymous types have property names which carry more information, for tuples you don't have this. You can't use anonymous types as return values and parameters though and you can with tuples.

An example of when a tuple is nice is when you want to return multiple values. @Petar Minchev mentions this link which gives a good example.

You may want a Find() method that returns both an index and the value. Another example would be the position in a 2d or 3d plane.




回答2:


Just a little update to this answer since C# 7 is out in the wild. Tuples have super powers now and can sometimes replace anonymous types and classes. Take for example this method that accepts and returns tuples with named properties.

void Main()
{
    var result = Whatever((123, true));
    Debug.Assert(result.Something == 123);
    Debug.Assert(result.Another == "True");
}

(int Something, string Another) Whatever((int Neat, bool Cool) data)
{
    return (data.Neat, data.Cool.ToString());
}

That's cool.




回答3:


A tuple is not an anonymous type, it's a named type. You can use it as a return type or method argument. This code is valid:

Tuple<int, string> GetTuple()
{
    return Tuple.Create(1, "Bob");
}

You can't do this with an anonymous type, you would have to return System.Object instead. Typically, you end up having to use Reflection on these objects (or dynamic in .NET 4) in order to obtain the values of individual properties.

Also, as Brian mentions, the property names on a Tuple are fixed - they're always Item1, Item2, Item3 and so on, whereas with an anonymous type you get to choose the names. If you write:

var x = new { ID = 1, Name = "Bob" }

Then the anonymous type actually has ID and Name properties. But if you write:

Tuple.Create(1, "Bob")

Then the resulting tuple just has properties Item1 and Item2.




回答4:


Another point in favor of anonymous types would be that you can easily have more than 8 properties. While this is doable using tuples, it's not so pretty.

var tuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9)); //and so on

or write your own tuple classes.


An interesting similarity to note is that both tuples and anonymous types give you immutability and equality comparability (both overrides Equals and GetHashCode) based on the properties by default.



来源:https://stackoverflow.com/questions/2613829/anonymous-type-and-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!