8

我正在使用以下代码调用一个类的静态 ctor:

Type type;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);

这会导致 cctor 运行两次吗?

4

1 回答 1

9

RunClassConstructor静态构造函数只运行一次,即使你调用了两次。试试看嘛 ;)

using System.Runtime.CompilerServices;
...

void Main()
{
    RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
    RuntimeHelpers.RunClassConstructor(typeof(Foo).TypeHandle);
    Foo.Bar();
}

class Foo
{
    static Foo()
    {
        Console.WriteLine("Foo");
    }

    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

此代码打印:


于 2010-04-17T14:07:46.940 回答