为什么C#允许在非静态构造函数中初始化静态类变量?

nav*_*eed 3 c# variables static constructor initialization

为什么C#允许在非静态构造函数中初始化静态类变量?只应允许在静态构造函数上初始化静态变量.有任何想法吗?

 public class customer
{
    public string Name;

    public customer()
    {
        Name = "C1";
        Console.WriteLine("creating customer " + Name);
    }

}

class Program
{
    public static customer cust;

    public Program()
    {
        cust = new customer(); //Why is this allowed i.e. initialize a static variable in non-static constructor?
    }

    static void Main(string[] args)
    {
        Program program = new Program();
        program = new Program();

        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kha*_*han 10

不要将其视为初始化,将其视为设置.

如果您只希望通过静态构造函数或声明来初始化它,请添加readonly关键字.

例如

public readonly static customer cust;

//Allowed
static Program()
{
    cust = new customer(); 
}

//Not Allowed
public Program()
{
    cust = new customer();
}
Run Code Online (Sandbox Code Playgroud)

  • @naveed c#不是c ++. (6认同)