我想知道为什么实例构造函数可以访问静态字段?如果我通过静态构造函数初始化静态字段,并通过错误再次通过实例构造函数初始化静态字段,则第二次初始化会覆盖第一个。通过实例构造函数使它们可访问的背后是什么? (请看看简单的程序下面来了解我的观点)通过什么逻辑,实例构造函数可以访问静态字段
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