CLR 是在每次方法调用之前就在堆上创建 Type 对象,还是只使用已经创建的 Type 对象?

Does the CLR create Type object on the heap right before each method invocation or does it just use already created Type object?

我的问题是 CLR 是在每次方法调用之前就在堆上创建 Type 对象,还是只使用已经创建的 Type 对象? 例如,假设我们有 Person class 和两个使用此 Person 类型的方法。

class Program
{
    static void Main(string[] args)
    {
        Method1();
        Method2();
    }

    static void Method1()
    {
        Person p = new Person();
    }

    static void Method2()
    {
        Person p = new Person();
    }
}

class Person
{
    public string Name { get; set; }
}

正如我们所知,CLR 在执行之前扫描方法体,为该方法使用的类型创建 Type 对象。那么,在那种情况下会创建多少个 Person 类型的对象呢? CLR 会创建两个类型对象还是会使用已创建的类型对象?

回答你的最后一个问题:

Will CLR create two type object or will it use already created Type object?

它将使用已经创建的一个

在这里,通过 C# 史诗书直接取自 Jeffery Ritcher CLR:

Just before the Main method executes, the CLR detects all of the types that are referenced by Main’s code. This causes the CLR to allocate an internal data structure that is used to manage access to the referenced types. In Figure 1-4, the Main method refers to a single type, Console, causing the CLR to allocate a single internal structure. This internal data structure contains an entry for each method defined by the Console type. Each entry holds the address where the method’s implementation can be found. When initializing this structure, the CLR sets each entry to an internal, undocumented function contained inside the CLR itself. I call this function JITCompiler.

所以这最终意味着运行时将在执行执行方法之前第一次看到类型时创建类型,如果该类型存在于不同的程序集中,它将首先尝试加载该程序集(当然使用程序集清单中的程序集引用元数据文件)