RunClassConstructor是否只能运行一次类型的静态构造函数?
我正在使用以下代码调用类的静态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"); } }
此代码打印:
富
酒吧