C# 为封装创建属性
当Perperty创建一个私有字段时,它是强制的吗 什么时候不创建C# 为封装创建属性,c#,properties,encapsulation,C#,Properties,Encapsulation,当Perperty创建一个私有字段时,它是强制的吗 什么时候不创建 enter code here namespace ApplicationStartSample { public class Configuration { private Configuration() { } private static Configuration _Current; public static Configuration 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
{
}
}
}
}
如果您询问是否可以删除
当前
属性的私有字段,您可以这样做(尽管它不再懒洋洋地初始化配置
):
注意:这是一个需要C#3.0的版本
您也可以改用公共字段(不过,如果您需要将其更改为属性,则需要重新编译调用它的任何内容):
你是说什么时候创建一个属性而不是仅仅使用一个字段?
public class Configuration
{
static Configuration()
{
Current = new Configuration();
}
public static Configuration Current { get; private set; }
}
public class Configuration
{
public static Configuration Current = new Configuration();
}