Files
BitGet_API/BitgetApi/Utils/BaseSingleton.cs

72 lines
1.7 KiB
C#
Raw Normal View History

2024-05-22 16:56:51 +09:00
using Newtonsoft.Json;
using System;
using System.IO;
namespace BitgetAPI.Utils
{
public class BaseSettings<T> where T : class, new()
{
private static readonly object lockObject = new object();
private static readonly object fileLockObject = new object();
private static T _instance;
public static T Instance
{
get
{
lock (lockObject)
{
//var path = GetSettingFilePath();
if (null == _instance)
_instance = CreateInstance();
}
return _instance;
}
}
protected static T CreateInstance()
{
try
{
Type type = typeof(T);
var saveFilePath = getFilePath();
if (File.Exists(saveFilePath))
{
//File.ReadAllText(saveFilePath);
return JsonConvert.DeserializeObject<T>(File.ReadAllText(saveFilePath)) ?? new T();
}
}
catch { }
return new T();
}
private static string getFilePath()
{
return typeof(T).Name + ".json";
}
~BaseSettings()
{
SaveConfig();
}
public void SaveConfig()
{
lock (fileLockObject)
{
try
{
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
File.WriteAllText(getFilePath(), json);
}
catch
{
}
}
}
}
}