c# - 字段顺序在匿名类型自动初始化中很重要吗?

标签 c# anonymous-types

我得到了一个从匿名类型创建匿名列表的场景,我使用

实现了这一点
    public static List<T> MakeList<T>(T itemOftype)
    {
        List<T> newList = new List<T>(); 
        return newList; 
    } 

    static void Main(string[] args)
    {
       //anonymos type
       var xx = new
       {                             
          offsetname = x.offName,
          RO = y.RO1
       };

       //anonymos list
       var customlist = MakeList(xx);

       //It throws an error because i have given the wrong order
       customlist.Add(new { RO = y.RO2, offsetname = x.offName });
       customlist.Add(new { RO = y.RO3, offsetname = x.offName });

       //but this works
       customlist.Add(new { offsetname = x.offName, RO = y.RO2 });
       customlist.Add(new { offsetname = x.offName, RO = y.RO3 });
    }

这些是错误信息

System.Collections.Generic.List.Add(AnonymousType#1)' has some invalid arguments

Argument '1': cannot convert from 'AnonymousType#2' to 'AnonymousType#1'

这背后的原因是什么??

最佳答案

是的,这很重要。

如果属性名称和类型相同且顺序相同,则两个匿名类型初始化程序使用相同的自动生成类型。

散列时顺序变得相关;本来可以使用一致的顺序生成类型来计算哈希值,但将属性顺序作为使类型唯一的一部分包含在内似乎更简单。

有关详细信息,请参阅 C# 3 规范的第 7.5.10.6 节。特别是:

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.

关于c# - 字段顺序在匿名类型自动初始化中很重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2154414/

相关文章:

c# - 匿名类型 - 是否有任何显着特征?

c# - WPF richTextBox问题

c# - 如何订购匿名类型的 IEnumerable<T>?

c# - 将一个分层列表投影到另一个具有匿名类型(或动态)的分层列表?

c# - 将上下文菜单从 App.xaml 附加到 Setter 值

c# - 在运行时解析参数名称

c# - always 编译器是否在匿名类型的名称中包含文本 "AnonymousType"?

c# - 为标签添加右边框

c# - 在 .net c# 中使用 ssl Stream 从 Tcp.Client.Socket 发送数据

c# - 组合属性 setter "init and private"(C#9)