强制类加载 [英] Forcing class load
问题描述
有没有办法在C#或.net IL强制具有类型初始化一个类(静态构造函数)来加载自身,而无需访问它的任何参数?
Is there a way in C# or .net IL to force a class that has a type initializer (static constructor) to load itself, without accessing any of its parameters?
假设我有类
public static class LogInitialization {
static LogInitialization() {
System.Console.WriteLine("Initialized");
}
}
有没有办法让这条线来打印?
Is there a way to get this line to print?
请注意这个类是静态的,所以我不能将它实例强制初始化,并且它没有公开的成员,所以我不能访问他们开始吧。
Note that the class is static so I can't instantiate it to force initialization, and it has no public members so I can't access them to start it.
推荐答案
在翻找的CLI规范,我发现了一个参考方法<一href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.runclassconstructor.aspx"><$c$c>RuntimeHelpers.RunClassConstructor$c$c>
Rummaging in the CLI spec, I found a reference to the method 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:
- 定义隐藏静态字段和code中的每个类的构造函数触及的隐藏静态字段的 基类和/或接口它实现,或
- 通过显式调用
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor
(请参阅分区IV)。
- 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).
这篇关于强制类加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!