我想知道爲什麼實例構造函數可以訪問靜態字段?如果我通過靜態構造函數初始化靜態字段,並通過錯誤再次通過實例構造函數初始化靜態字段,則第二次初始化會覆蓋第一個。通過實例構造函數使它們可訪問的背後是什麼? (請看看簡單的程序下面來了解我的觀點)通過什麼邏輯,實例構造函數可以訪問靜態字段
using System;
class Program
{
static void Main()
{
Circle C1 = new Circle(5);
Console.WriteLine("The area of the first circle is {0}", C1.CalculateArea());
}
}
class Circle
{
public static float _Pi; // Since the value of pi will not change according to circles, we have to make it static
int _Radius; // This is an instance field, whose value is different for different instances of the class
static Circle() // A static constructor initializes the static fields
{
Console.WriteLine("Static constructor executed");
Circle._Pi = 3.14F;
}
public Circle(int Radius) // An instance constructor initializes the instance fields
{
Console.WriteLine("Instance constructor executed");
this._Radius = Radius;
Circle._Pi = 2.12F; // This again initializes the value of the pi to a different value as given by the static constructor
}
public float CalculateArea()
{
return this._Radius*this._Radius*Circle._Pi;
}
}
使用'const'使其不可寫。 –
丹尼爾,這不是我的問題的重點。還有其他一些方法可以使我的靜態字段不可寫入。我關心的是爲什麼提供這個功能.. ??就像在哪個例子中,一個實例構造函數需要使用靜態字段? – TotalGadha