2011-02-26 4 views
0

Perperty가 개인 필드를 만들 때 compulsor입니까?캡슐화를위한 속성 생성

언제 만들어지지 않습니까? 당신이 당신의 Current 속성의 개인 필드를 제거 할 수 있다면, 당신이 할 수있는 당신이 요청하는 경우

enter code here 

namespace ApplicationStartSample 
{ 
public class Configuration 
{ 
    private Configuration() 
    { 
    } 

    private static Configuration _Current; 
    public static Configuration Current 
    { 
     get 
     { 
      if (_Current == null) 
       _Current = new Configuration(); 

      return _Current; 
     } 
    } 

    private const string Path = "Software\\MFT\\Registry Sample"; 

    public bool EnableWelcomeMessage 
    { 
     get 
     { 
      return bool.Parse(Read("EnableWelcomeMessage", "false")); 
     } 
     set 
     { 
      Write("EnableWelcomeMessage", value.ToString()); 
     } 
    } 

    public string Company      //why do not create private field? 
    { 
     get 
     { 
      return Read("Company", "MFT"); 
     } 
     set 
     { 
      Write("Company", value); 
     } 
    } 

    public string WelcomeMessage 
    { 
     get 
     { 
      return Read("WelcomeMessage", string.Empty); 
     } 
     set 
     { 
      Write("WelcomeMessage", value); 
     } 
    } 

    public string Server 
    { 
     get 
     { 
      return Read("Server", ".\\Sqldeveloper"); 
     } 
     set 
     { 
      Write("Server", value); 
     } 
    } 

    public string Database 
    { 
     get 
     { 
      return Read("Database", "Shop2"); 
     } 
     set 
     { 
      Write("Database", value); 
     } 
    } 

    private static string Read(string name, string @default) 
    { 
    RegistryKey key = Registry.CurrentUser.OpenSubKey(Path, false); 

    if (key == null) 
    return @default; 

try 
{ 
    string result = key.GetValue(name).ToString(); 
    key.Close(); 

    return result; 
} 
catch 
{ 
    return @default; 
} 
} 

    private static void Write(string name, string value) 
{ 
try 
{ 
    RegistryKey key = Registry.CurrentUser.OpenSubKey(Path, true); 

    if (key == null) 
     key = Registry.CurrentUser.CreateSubKey(Path); 

    key.SetValue(name, value); 
    key.Close(); 
} 
catch 
{ 
} 
} 
} 
} 
+0

당신은 의미 단지 필드를 사용하는 것의? –

답변

0

(더 이상 게으르게 Configuration를 초기화하지 않을 것이다하지만) :

public class Configuration 
{ 
    static Configuration() 
    { 
     Current = new Configuration(); 
    } 

    public static Configuration Current { get; private set; } 
} 

참고 :이 Auto-Implemented Property이며 C# 3.0이 필요합니다.

(적 속성으로 변경해야하는 경우, 당신이 그것을 부르고 아무것도 다시 컴파일해야하지만) 당신은 대신 공공 필드를 사용할 수 있습니다 속성을 대신 만들 때

public class Configuration 
{ 
    public static Configuration Current = new Configuration(); 
} 
관련 문제