2017-04-20 3 views
-3

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

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; 
    } 
} 
+1

은 쓰기를 허용하는'const'를 사용합니다. –

+0

다니엘 그건 내 질문의 핵심이 아니야. 정적 필드를 쓸 수 없도록 만들 수있는 다른 방법이 있습니다. 내 관심사는 왜이 기능이 제공 되는가입니다. ?? 어떤 예 에서처럼 인스턴스 생성자가 정적 필드를 사용해야합니까 ?? – TotalGadha

답변

0

(아래 나의 점을 이해하기 위해 간단한 프로그램에서 볼 수있다) 수업. 클래스 멤버가 정적이 아닌 필드를 가져 와서 유지하고이 카운터를 정적으로 증가 시키길 원할 수 있습니다. 앞으로 인스턴스에는 고유 한 고유 식별자가 있습니다.

예 :

public class Employee { 
     static int NextEmployeeId; // a counter across all employees 

     public int EmployeeId; // this instance's employee id 
     public string Name;  // this instance's name. 

     static Employee() { 
      Employee.NextEmployeeId = 1; // first employee gets 1. 
     } 

     public Employee(string Name) { 
      this.Name = Name; 
      this.EmployeeId = Employee.NextEmployeeId++; // take an id and increment for the next employee 
     } 

} 
+0

선생님, 답을 예제로 설명해 주실 수 있습니까? 단지 당신이 설명하려고하는 것과 똑같은 것을 이해했는지 확신하기 위해서 : P – TotalGadha

0

정적 필드도 생성자에서, 또는 메인/다른 클래스에서, 모든 곳에서 액세스 할 수 있습니다. 그 목적은 전체 앱에 대해 하나의 정적 속성/필드 싱글 톤을 갖게된다는 것입니다.

public class AClass() 
{ 
    public static float staticField; 
    public float field; 
    public AClass() 
    { 
     staticField = 5; 
     field = 6; 
    } 
    static AClass() 
    { 
     staticField = 7; 
    } 
} 

public int Main() 
{ 
    float initially = AClass.staticField; // initially this staticField is 7. 
    AClass aclass = new AClass(); // instantiating AClass 
    float localfield = aclass.field; // this field does not affect anyone. It is 6 
    float newStaticField = AClass.staticField; // Due to previous instantiation, the value is now 5. 

} 

그리고 나는 당신이보기에 나쁘다는 것에 동의합니다. 왜? 왜냐하면 Pi의 값을 변경하는 이유는 이미 결정되고 고정되어 있기 때문에 생성자에서 Pi의 값을 변경할 이유가 없기 때문입니다.

클래스를 디자인하고 왜 정적 필드를 원하게되는지 알아야합니다. 다음은 정적 필드 (예 : 일종의 ... 키가 숨겨져 있어야하기 때문에)를 올바르게 가지고있는 클래스의 예입니다. 이것은 정적 필드가 유용하고 괜찮은 방법을 보여주기위한 것입니다. :

public class NewEncryptionClass() 
{ 
     public static string Key; 
     public NewEncryptionClass() 
     { 

     } 
     public NewEncryptionClass(string newKey) 
     { 
      Key = newKey; // store the key and keep it forever 
     } 
     static NewEncryptionClass() 
     { 
      Key = "key1"; // initially key is "key1" 
     } 
     public string Encrypt(string str) 
     { 
      string result = string.Empty; 
      result = "adlasdjalskd" + Key + "ajlajfalkjfa" + str; // do the Encryption, I just made up 
      return result 
     } 
} 

여기서 NewEncryptionClass를 인스턴스화하면 다음에 암호화를 수행 할 때마다 항상 최신 키를 사용할 수 있도록 NewEncryptionClass를 저장하는 것이 좋습니다. 예를 들어 : 내가하지,이 클래스의 디자인이 잘못되면, 영원히 최신 키를 유지하려는 당신이 당신의 목적을 다시 작성해야하는 경우

public int Main() 
{ 
    string initialkey = NewEncryptionClass.Key; 
    string result1 = new EncryptionClass().Encrypt("encryptThis"); // using key1 

    // let's change the key 
    string result2 = new EncryptionClass("key2").Encrypt("encryptThat"); // using key2 
    string result3 = new EncryptionClass().Encrypt("encryptOther"); // still using key2 


} 

이 물론이다.