<>j__AnonymousTypeTypeParameter1和<>j__AnonymousTypeTypeParameter2这两个Generic Type代表我在 {} 中制定ID和Name的类型。通过这个结构,我们发现其定义和一般的Generic Type并没有什么区别。
为了进一步了解生成什么样的Anonymous Type,我们使用IL DASM在IL级别看看生成的Anonymous Type的大体结构:
为了做一个对比,下面是我们最开始定义的Named Employee Type在IL DASM中的结构:
如果想更清楚了解Anonymous Type的本质,建议读者亲自使用IL DASM看看的每个成员具体的IL。
三、Anonymous Type is Bound to Assembly
在上面一个部分中我们说了对于CLR来说,Anonymous Type和一般的Named Type并没有本质的区别。但是话不能太绝对,他们之间还是有一点小小的差异。到底是什么样差异,我在这里先卖一个关子。在具体介绍这个差异的时候,我们先来看看一个Sample:
在这个Sample中,我定义了两个Project:
Console Application:Artech.NewFeatureInCSharp.ConsoleApp
Class Libray:Artech.NewFeatureInCSharp.Library
Artech.NewFeatureInCSharp.Library中定一个Employee Type:
| using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Artech.NewFeatureInCSharp.Library { public class Employee { private Guid _id; private string _name; public Guid ID { get { return _id; } set { _id = value; } } public string Name { get { return _name; } set { _name = value; } } } } |
和一个Static的Utility Class:
| using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Artech.NewFeatureInCSharp.Library { public static class Utility { public static object Anonymous_GetEmployee(Guid id, string name) { return new { ID = id, Name = name }; } public static Employee GetEmployee(Guid id, string name) { return new Employee { ID = id, Name = name }; } } } |

