저는 인스턴스 생성자가 정적 필드에 액세스하는 이유는 무엇입니까? 정적 생성자를 통해 정적 필드를 초기화하고 실수로 인스턴스 생성자를 통해 초기화하면 두 번째 초기화가 첫 번째를 덮어 씁니다. 인스턴스 생성자를 통해 액세스 가능하게 만드는 배경은 무엇입니까? 정적 필드에 대한 인스턴스의 카운터가 포함 된 경우 생성자는 정적 멤버에 액세스 할 수있는 사용 사례의 예를 들어어떤 논리로 인스턴스 생성자가 정적 필드에 액세스해야합니까
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