其他分享
首页 > 其他分享> > 快速搭建上位机的可视化系统配置层

快速搭建上位机的可视化系统配置层

作者:互联网

  1. 系统配置文件名称是SystemConfig.json
  2. 系统配置存储在exe目录
  3. 若配置文件不存在,不会报错,而是使用默认配置启动程序
  4. 默认配置取决于类的字段的默认值
  5. 配置比较多时,可以用多个类划分归类
  6. 使用序列化实现当前配置的拷贝
public class SystemConfig : ICloneable
{
    #region Singleton

    private static SystemConfig _instance;
    private const string _fileName = "SystemConfig.json";
    private static string _path;
    private static object _loadLocker;
    private static object _saveLocker;

    static SystemConfig()
    {
        _path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _fileName);
        _loadLocker = new object();
        _saveLocker = new object();
    }

    private SystemConfig()
    {
    }

    public static SystemConfig Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_loadLocker)
                {
                    if (_instance == null)
                    {
                        if (!File.Exists(_path))
                        {
                            _instance = new SystemConfig();
                        }
                        else
                        {
                            _instance = JsonConvert.DeserializeObject<SystemConfig>(_path);
                        }
                    }
                }
            }

            return _instance;
        }
    }

    #endregion Singleton

    public BaseConfig BaseConfig { get; set; } = new BaseConfig();
    public OtherConfig OtherConfig { get; set; } = new OtherConfig();

    public void Save()
        {
            lock (_saveLocker)
            {
                File.WriteAllText(_path, JsonConvert.SerializeObject(_instance, Formatting.Indented));
            }
        }

    public void Save(string path)
    {
        lock (_saveLocker)
        {
            File.WriteAllText(path, JsonConvert.SerializeObject(_instance, Formatting.Indented));
        }
    }

    public object Clone()
    {
            return JsonConvert.DeserializeObject<SystemConfig>(JsonConvert.SerializeObject(this));
    }
}

public class BaseConfig
{
    /// <summary>
    /// 当不存在配置文件时,会使用此默认值
    /// </summary>
    public string ServerIP { get; set; } = "127.0.0.1";
}

public class OtherConfig
{
}

标签:instance,SystemConfig,private,上位,static,可视化,path,public,系统配置
来源: https://www.cnblogs.com/LiuwayLi/p/15559335.html