我正在使用以下代码调用一个类的静态 ctor:
Type type;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
这会导致 cctor 运行两次吗?
我正在使用以下代码调用一个类的静态 ctor:
Type type;
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
这会导致 cctor 运行两次吗?
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");
}
}
此代码打印:
富
吧