有没有办法在C#或.net IL强制一个类有一个类型initializer(静态构造函数)加载自身,而不访问其任何参数?
假设我已经上课了
public static class LogInitialization { static LogInitialization() { System.Console.WriteLine("Initialized"); } }
有没有办法得到这行打印?
请注意,该类是静态的,所以我无法实例化它强制初始化,它没有公共成员,所以我无法访问它们启动它.
解决方法
在CLI规范中进行翻阅,我发现对方法
RuntimeHelpers.RunClassConstructor
的引用
If a language wishes to provide more rigid behavior — e.g.,type initialization automatically triggers execution
of base class’s initializers,in a top-to-bottom order — then it can do so by either:
- defining hidden static fields and code in each class constructor that touches the hidden static field of its
base class and/or interfaces it implements,or- by making explicit calls to
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor
(see Partition IV).