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

2021/11/16 6:09:51

本文主要是介绍快速搭建上位机的可视化系统配置层,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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


这篇关于快速搭建上位机的可视化系统配置层的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程