我知道匿名类型没有自己的预定义类型。类型由编译器在编译类型中分配给它,并且在编译时分配的类型的详细信息在代码级别无法获知;这些细节是 CLR 本身已知的。我听说 CLR 中的这些匿名类型仅被视为引用类型。所以我的问题是,是否在编译时创建了一个新类型,如类或结构,对应于匿名类型中定义的只读属性?
最佳答案
I understand that anonymous types have no pre-defined type of its own.
正确。除了匿名类型共有的对象外,没有其他基类型。
Type is assigned to it by the compiler at the compile type and details of type assigned at compile time can't be known at code level
没错。
these details are known to CLR itself.
我不知道你说的“细节”是什么,也不知道“CLR 已知”是什么意思。
I've heard that these anonymous types at CLR are treated as if it's a reference type only.
你没有听错。
So my question is that whether at compile time a new Type like a class or a struct is created corresponding to read-only properties defined in the anonymous type?
是的。创建了一个新类。
请注意,在程序集中如果有两个匿名类型具有相同的属性名称、相同的属性类型、相同的顺序,则只会创建一个类型。这是由语言规范保证的。
练习:
// Code in Assembly B:
public class B { protected class P {} }
// Code in Assembly D (references assembly B)
class D1 : B {
public static object M() { return new { X = new B.P() }; }
}
class D2 : B {
public static object M() { return new { X = new B.P() }; }
}
您需要在程序集 D 中生成一个 单个 类声明,该类声明具有 B.P 类型的属性 X,使得 D1.M().GetType()
等于到 D2.M().GetType()
。描述如何做到这一点。
关于c# - 匿名类型 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41250314/