创建封装的属性

时间:2011-02-26 10:27:15

标签: c# properties encapsulation

当属性创建私有字段时,这是强制性的吗?

什么时候不创建?

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
{
}
}
}
}

1 个答案:

答案 0 :(得分: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();
}