被RunClassConstructor保证运行一个类型的静态构造函数只有一次? [英] Is RunClassConstructor guaranteed to run a type's static constructor only once?

查看:221
本文介绍了被RunClassConstructor保证运行一个类型的静态构造函数只有一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话使用此代码类的构造函数静态:

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

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

这可能会导致cctor被运行两次?

Can this cause the cctor to be run twice?

推荐答案

没有,它运行静态构造函数只有一次,即使你叫 RunClassConstructor 的两倍。刚刚尝试;)

No, it runs the static constructor only once, even if you call RunClassConstructor 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");
    }
}

此代码打印:

美孚结果

这篇关于被RunClassConstructor保证运行一个类型的静态构造函数只有一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆