静态类c#中的公共成员

时间:2015-03-29 10:59:15

标签: c# c#-4.0

我试图理解c#中的静态类。我想做的是我想创建一个静态配置类。我将在其中定义多个公共成员,可以从外部访问,如ConnectionString和其他与应用程序相关的配置。怎么做?

public static class config {
    public static string con {get; set;}
    public static bool IsProduction {get; set;}
    public static string FileLogPath {get; set;}
}

这就是我现在正在做的事情我是否需要在构造函数中定义所有变量的值?

1 个答案:

答案 0 :(得分:3)

这通常可以通过单例模式更好地处理。静态构造函数中的异常是噩梦+当您使用单例模式时,您的对象始终处于一致状态,并且在第一次调用Config.Instance时根据需要执行初始化。

public class Config {
  private static Config s_Config;

  public static Config Instance {
    get {
      if (s_Config == null)
      {
        // fetch members
        string con = "";
        bool isProduction = false;
        string fileLogPath = "";
        s_Config = new Config(con, isProduction, fileLogPath);
      }
      return s_Config;
    }
  }

  private Config(string con, bool isProduction, string fileLogPath)
  {
    Con = con; 
    IsProduction = isProduction;
    FileLogPath = fileLogPath;
  }

  public string Con { get; private set; }
  public bool IsProduction { get; private set; }
  public string FileLogPath { get; private set; }
}

如@khlr所述 - 这是一个简单的例子,单例的初始化部分不是线程安全的。如果线程安全是个问题,请参阅https://msdn.microsoft.com/en-us/library/ff650316.aspx