简体   繁体   English

C#:类中的静态对象变量

[英]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: 据我所知:

  • If there is no static constructor the calling of a static method may trigger the initializers but isn't required to do so if the static method uses no static field. 如果没有静态构造函数,则调用静态方法可能会触发初始化程序,但如果静态方法不使用静态字段,则不需要这样做。
  • If there is a static constructor it must run when a static member is referenced, so calling of a static method triggers first the static field initializers and then the the static constructor. 如果有静态构造函数,它必须在引用静态成员时运行,因此调用静态方法首先触发静态字段初始化器,然后触发静态构造函数。

Yes. 是。 Two particular things to note: 需要注意的两件事:

  1. The static variables will be initialized in the order they appear in the class. 静态变量将按它们在类中出现的顺序进行初始化。
  2. They are guaranteed to be initialized before any static constructor is called. 保证在调用任何静态构造函数之前初始化它们。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM