爲什麼C#允許在非靜態構造器中初始化靜態類變量?靜態變量應該只允許在靜態構造函數上初始化。有任何想法嗎?爲什麼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();
}
}
爲什麼它不應該允許這個?如果你想在第一次實例化類時初始化一個靜態變量呢?或者,也許每次增加一個對象時都會增加一個計數。 –
你可以從* any *方法更新它,沒有什麼特別的構造函數。你忘記宣佈它*只讀*? –