gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:14:28 24 4
gpt4 key购买 nike

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

实现了这一点
    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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com