- 系统配置文件名称是
SystemConfig.json
- 系统配置存储在exe目录
- 若配置文件不存在,不会报错,而是使用默认配置启动程序
- 默认配置取决于类的字段的默认值
- 配置比较多时,可以用多个类划分归类
- 使用序列化实现当前配置的拷贝
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
{
}