201709301555->unity中使用单例

来源:互联网 发布:剑桥少儿英语软件 编辑:程序博客网 时间:2024/05/29 04:07

声明基类singleton<T>

限制t为class

然后static T instance

给予属性Instance判断instance是否为空,为空则新建,不空则返回instance

如:

public class Singleton<T> where T : class,new()

{

    private static T instance = null;

    private static readonly object Lock = new object();

    public static T Instance

    {

        get

        {

            lock (Lock)
            {
                if (instance == null)
                {
                    instance = new T();
                }
                return instance;
            }
        }
    }
    public virtual void OnInitialized()
    {
    }
}