using System;
using System.Reflection;
namespace MAX.Core.Infrastructure;
///
/// 单例,需要在当前类中定义
///
///
public class SingleInstance where T : class
{
private static readonly object lockObj = new();
private static T mySelf;//= default(T);
public static T Instance
{
get
{
lock (lockObj)
{
mySelf ??= InstanceCreator.CreateInstance();
}
return mySelf;
}
}
}
public static class InstanceCreator
{
public static T CreateInstance()
{
Type type = typeof(T);
try
{
return (T)type.Assembly.CreateInstance(type.FullName, true, BindingFlags.NonPublic | BindingFlags.Instance, null, null, null, null);
}
catch (MissingMethodException ex)
{
throw new Exception($"{ex.Message}\n(单例模式下,构造函数必须为 private)");
}
}
}