Is RunClassConstructor guaranteed to run a type

2020-08-27 01:00发布

问题:

I'm calling the static ctor of a class using this code:

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

Can this cause the cctor to be run twice?

回答1:

RunClassConstructor runs the static constructor only once, even if you call it twice. Just try ;)

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");
    }
}

This code prints :

Foo
Bar