C#单例
单例的类
/// <summary>
/// 单例的类
/// </summary>
public abstract class QYSingleton<T> where T : class, new()
{
/// <summary>
/// 单例类
/// </summary>
private static class Single
{
/// <summary>
/// 静态构造函数,仅在Single第一次被使用时调用,多线程安全,按需创建
/// </summary>
static Single()
{
Inst = new T();
IsNew = true;
}
}
/// <summary>
/// T的单例
/// </summary>
public static T Inst;
/// <summary>
/// 是否被创建过
/// </summary>
public static bool IsNew = false;
public QYSingleton()
{
if (IsNew)
throw new Exception($"{typeof(T)} 是单例,无法被New");
}
}
使用案例
Test类
public class Test : QYSingleton<Test>
{
public Test()
{
Debug.Log("自动创建");
}
public void Func()
{
Debug.Log("方法测试");
}
}
正确使用Test类
public class QYEntry : MonoBehaviour
{
void Start()
{
Test.Inst.Func();
}
}
错误使用Test类
public class QYEntry : MonoBehaviour
{
void Start()
{
Test test = new Test("手动创建");
test.Func();
}
}