c# - 匿名类型 C#

标签 c# anonymous-types

我知道匿名类型没有自己的预定义类型。类型由编译器在编译类型中分配给它,并且在编译时分配的类型的详细信息在代码级别无法获知;这些细节是 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/

相关文章:

c# - 从辅助 webconfig 读取 AppSettings

c# - WinForms 中的计时器

entity-framework - 加入 Entity Framework 和 F#

c# - 将匿名类型附加到对象;如何找回它?

C++ 在循环中创建和收集结构

c# - 给定的规则集不包含任何类型为 System.Object、mscorlib、

c# - Key Input Bindings 与 CommandParameter 用法伯顿绑定(bind)

c# - 用默认值填充 List<int>?

c# - 使用相同的属性名称和类型多次分配匿名类型

c# - 跨程序集边界返回/使用动态匿名类型