编程语言
首页 > 编程语言> > 对于C#二进制文件,匿名类的类型信息存储在哪里?

对于C#二进制文件,匿名类的类型信息存储在哪里?

作者:互联网

我用C#进行了实验,首先创建了一个名为“ ClassLibrary1”的类库,其代码如下:

public class ClassLibrary1
{
    public static void f()
    {
        var m = new { m_s = "abc", m_l = 2L };
        Console.WriteLine(m.GetType());
    }
}

注意,我删除了IDE生成的名称空间信息.
然后我用下面的代码创建了控制台应用程序:(还删除了名称空间)
在引用ClassLibrary1时:

class Program
{
    static void Main()
    {
        var m = new {m_s = "xyz", m_l = 5L};
        Console.WriteLine(m.GetType());
        ClassLibrary1.f();
    }
}

我运行程序,它打印:

<>f__AnonymousType0`2[System.String,System.Int64]
<>f__AnonymousType0`2[System.String,System.Int64]
Press any key to continue . . .

输出表明在类库和控制台应用程序中定义的2个匿名类具有相同的类类型.

我的问题是:C#二进制如何为它包含的所有类存储其类型信息?如果将其存储在全局位置,则使用dll引用构建exe时,将存在2个相同的匿名类型信息,因此

(1) Is name duplication an error that should be avoid?
(2) If not an error like I tested, how could C# binary store duplicate type information?
(3) And in runtime, what's the rule to look up type information to create real objects? 

在我的示例中似乎有些混乱.
谢谢.

解决方法:

I removed namespace information

不相关.程序集的匿名类型在相同的名称空间(即空名称空间)中生成.

此外,请参见C#规范7.6.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.

令人困惑的是,“程序”在这里是指“汇编”.所以:

how does C# binary store its type information for all the classes it contains? If it’s stored in a global place, when the exe is built with dll reference, 2 same anonymous type information is there

是的,但是每个程序集的类型都是唯一的.它们可以具有相同的类型名称,因为它们在不同的程序集中.您可以通过打印m.GetType().AssemblyQualifiedName来看到,其中将包括程序集名称.

标签:anonymous,types,binary,c
来源: https://codeday.me/bug/20191028/1950643.html