Anonymous type and tuple

后端 未结 4 1423
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 12:09

What is the difference between anonymous type and tuple?

4条回答
  •  春和景丽
    2020-12-25 12:55

    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 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.

提交回复
热议问题