开发者

Is RunClassConstructor guaranteed to run a type's static constructor only once?

开发者 https://www.devze.com 2022-12-27 10:56 出处:网络
I\'m calling the static cto开发者_StackOverflow中文版r of a class using this code: Type type; System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);

I'm calling the static cto开发者_StackOverflow中文版r of a class using this code:

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

Can this cause the cctor to be run twice?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号