is order of field important in anonymous types automatic initialization?

前端 未结 3 1567
庸人自扰
庸人自扰 2020-12-10 06:17

I got a scenario to create the anonymous list from the anonymous types, and i achieved that using

    public static List MakeList(T itemOf         


        
相关标签:
3条回答
  • 2020-12-10 06:42

    whats the reason behind that??

    Suppose that order did not matter. Suppose you were on the compiler team. Describe for me the exact behaviour of an implementation of "ToString" on such an anonymous type, such that the implementation meets all user expectations.

    I personally cannot come up with one, but perhaps you can.

    0 讨论(0)
  • 2020-12-10 06:44

    Yes, the order of fields is significant. Same fields, different order will yield different types.

    From the language specification:

    "Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type. "

    0 讨论(0)
  • 2020-12-10 07:03

    Yes, it's important.

    Two anonymous type initializers use the same auto-generated type if the property names and types are the same, in the same order.

    The order becomes relevant when hashing; it would have been possible for the type to be generated with a consistent order for calculating a hash value, but it seems simpler to just include the property order as part of what makes a type unique.

    See section 7.5.10.6 of the C# 3 spec for details. In particular:

    Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.

    0 讨论(0)
提交回复
热议问题