我得到了一个从匿名类型创建匿名列表的场景,我使用
实现了这一点 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/