2011-02-26 76 views
0

當Perperty創建一個私有字段時,它是否是compulsor?爲封裝創建屬性

什麼時候不創建?

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

你的意思是當創建一個屬性,而不是隻使用一個字段? – 2011-02-26 10:36:54

回答

0

如果你問,如果你能消除私有字段爲您Current屬性,你可以這樣做(儘管它不再初始化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(); 
}