是字段的顺序匿名类型自动初始化重要? [英] is order of field important in anonymous types automatic initialization?

查看:98
本文介绍了是字段的顺序匿名类型自动初始化重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,创建从匿名类型匿名列表,我实现了使用

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

    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 });
    }



这些都是错误讯息

these are the error messages

System.Collections.Generic.List.Add(AnonymousType#1)'
有一些无效参数

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

参数
'1':无法从
转换'AnonymousType#2到AnonymousType#1

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

什么背后的原因?

推荐答案

是的,这是非常重要的。

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.

查看C#3规范的详细信息部分7.5.10.6。特别是:

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.

这篇关于是字段的顺序匿名类型自动初始化重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆