gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:14:59 24 4
gpt4 key购买 nike

为什么 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();
}
}

最佳答案

不要把它看成初始化,把它看成设置。

如果您只想通过静态构造函数或在声明时对其进行初始化,请添加 readonly 关键字。

例如

public readonly static customer cust;

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

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

关于c# - 为什么 C# 允许在非静态构造函数中初始化静态类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17976581/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com