如何运行一个静态构造函数? [英] How can I run a static constructor?
本文介绍了如何运行一个静态构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想执行一个类的静态构造函数(即我想加载之类的),而无需创建一个实例。我该怎么办呢?
I'd like to execute the static constructor of a class (i.e. I want to "load" the class) without creating an instance. How do I do that?
奖金的问题:是否有.NET 4和旧版本之间的差异
Bonus question: Are there any differences between .NET 4 and older versions?
编辑:
- 类也不是一成不变的。
- 我要创建实例,因为它需要一段时间来运行之前运行它,我想避免这种延迟的第一次访问。
- 在静态构造函数初始化
私有静态只读
字段因此不能在一个方法,而不是运行。
- The class is not static.
- I want to run it before creating instances because it takes a while to run, and I'd like to avoid this delay at first access.
- The static ctor initializes
private static readonly
fields thus cannot be run in a method instead.
推荐答案
只是参考静态的领域之一。这将迫使你的静态初始化code运行。例如:
Just reference one of your static fields. This will force your static initialization code to run. For example:
public class MyClass {
private static readonly someStaticField;
static MyClass() { someStaticField = ... }
// any no-op method call accepting your object will do fine
public static void TouchMe() { Equals(someStaticField, null); }
}
用法:
// initialize statics
MyClass.TouchMe();
这篇关于如何运行一个静态构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文