[英]C#: static object variable in class
If I have a static variable in a class: 如果我在类中有一个静态变量:
public class MyClass {
private static MyObject = new MyObject();
public void MyMethod() {
// do some stuff
}
}
Can the variable be instantiated when it is declared, as in the above? 变量在声明时是否可以实例化,如上所述?
Your code is legal and works. 您的代码合法且有效。
One thing to be aware of is that static constructors and initalizers don't run when your module is loaded, but only when needed. 需要注意的一点是静态构造函数和初始化程序在模块加载时不会运行,但仅在需要时运行。
MyObject will only be instantiated when you either create an instance of MyClass or access a static field of it. 只有在创建MyClass实例或访问其静态字段时,才会实例化MyObject。
10.5.5.1 Static field initialization 10.5.5.1静态字段初始化
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. 类的静态字段变量初始值设定项对应于以它们出现在类声明中的文本顺序执行的赋值序列。 If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. 如果类中存在静态构造函数(第10.12节),则在执行该静态构造函数之前立即执行静态字段初始值设定项。 Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. 否则,静态字段初始化器在第一次使用该类的静态字段之前的实现相关时间执行。The static constructor for a closed class type executes at most once in a given application domain. 封闭类类型的静态构造函数在给定的应用程序域中最多执行一次。 The execution of a static constructor is triggered by the first of the following events to occur within an application domain: 静态构造函数的执行由应用程序域中发生的以下第一个事件触发:
· An instance of the class type is created. ·创建类类型的实例。
· Any of the static members of the class type are referenced. ·引用类类型的任何静态成员。
So as I understand it: 据我所知:
Yes. 是。 Two particular things to note: 需要注意的两件事:
Section 10.5.5.1 of the C# spec goes into more detail in you are interested. C#规范的第10.5.5.1节详细介绍了您感兴趣的内容。
If you are asking if this is legal C#, then yes it is. 如果你问这是否合法C#,那么是的。 And it will do what you think it will. 它会做你认为会做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.