音频内容
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace AibisDream.Kit
|
||||
{
|
||||
public class SingletonProp<T> where T : class, ISingleton
|
||||
{
|
||||
/// <summary>
|
||||
/// 静态实例
|
||||
/// </summary>
|
||||
private static T _instance;
|
||||
|
||||
/// <summary>
|
||||
/// 标签锁
|
||||
/// </summary>
|
||||
private static readonly object _lock = new();
|
||||
|
||||
public static T Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
// 先获取所有非public的构造方法
|
||||
var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
// 从ctors中获取无参的构造方法
|
||||
var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
|
||||
if (ctor == null)
|
||||
throw new Exception("Non-public ctor() not found!");
|
||||
// 调用构造方法
|
||||
_instance = ctor.Invoke(null) as T;
|
||||
_instance?.OnSingletonInit();
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 资源释放
|
||||
/// </summary>
|
||||
public static void Dispose()
|
||||
{
|
||||
_instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user