强制类加载
C# 或 .net IL 中是否有一种方法可以强制具有类型初始值设定项(静态构造函数)的类加载自身,而不访问其任何参数?
假设我已经上课了,
public static class LogInitialization {
static LogInitialization() {
System.Console.WriteLine("Initialized");
}
}
有没有办法打印这一行?
请注意,该类是静态的,因此我无法实例化它以强制初始化,并且它没有公共成员,因此我无法访问它们来启动它。
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?
Assuming I've got the class
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
翻遍 CLI 规范,我发现了对方法
RuntimeHelpers.RunClassConstructor
Rummaging in the CLI spec, I found a reference to the method
RuntimeHelpers.RunClassConstructor
我通常在具有静态构造函数的类上创建一个虚拟(空)Init 方法,以强制执行静态构造函数。 IE。
也就是说,您始终可以使用反射来获取 Type.TypeInitializer ... http://msdn.microsoft.com/en-us/library/system.type.typeinitializer.aspx
编辑:我过去做过的另一件事是创建一个名为 RequiresInitializationAttribute 的属性,然后在 AssemblyLoad 上扫描程序集以查找具有此类属性的类型,并使用 type.TypeInitializer 强制在加载包含程序集时执行静态构造函数。
我想,像往常一样,真正的问题是……你想实现什么目标?
I usually create a dummy (empty) Init method on classes with static constructors to force the static constructor execution. ie.
That said, you can always go for the Type.TypeInitializer with reflection... http://msdn.microsoft.com/en-us/library/system.type.typeinitializer.aspx
EDIT: One other thing I've done in the past, is to create an attribute called RequiresInitializationAttribute then on AssemblyLoad scan the assembly for types with such an attribute and using the type.TypeInitializer to force the static constructor to execute when the containing assembly is loaded.
I guess the real question, as usual, is...what are you trying to accomplish?