첫 등록
This commit is contained in:
72
BitgetApi/Utils/BaseSingleton.cs
Normal file
72
BitgetApi/Utils/BaseSingleton.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
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
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user