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

大憨熊 提交于 2019-12-07 00:18:10

问题


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



来源:https://stackoverflow.com/questions/2658561/is-runclassconstructor-guaranteed-to-run-a-types-static-constructor-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!