43 lines
861 B
C#
43 lines
861 B
C#
using System;
|
|
using System.Reflection;
|
|
|
|
namespace WxOrder.Framework;
|
|
|
|
/// <summary>
|
|
/// 单例,需要在当前类中定义
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class SingleInstance<T> 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<T>();
|
|
}
|
|
|
|
return mySelf;
|
|
}
|
|
}
|
|
}
|
|
|
|
public static class InstanceCreator
|
|
{
|
|
public static T CreateInstance<T>()
|
|
{
|
|
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)");
|
|
}
|
|
}
|
|
}
|