Unity项目中使用反射机制实现的泛型单例类

  • Post author:
  • Post category:其他


本文提供一个方便简单的单例类,有需要的地方继承就可以实现单例了,当前此处是没有继承MonoBehaviour的,废话不多说,上代码:

using UnityEngine;
using System;
using System.Collections.Generic;
// using System.Text;
using System.Reflection;

public class Singleton<T> where T : class
{
    private static object ms_SyncRoot = new object();
    private static T ms_Instance;
    public static readonly Type[] ms_EmptyTypes = new Type[0];
    public static T Instance
    {
        get
        {
            if (ms_Instance == null)
            {
                lock (ms_SyncRoot)
                {
                    if (ms_Instance == null)
                    {
                        ConstructorInfo ci = typeof(T).GetConstructor(
                            BindingFlags.NonPublic | BindingFlags.Instance, null, ms_EmptyTypes, null);

                        if (ci == null)
                        {
                            throw new InvalidOperationException("class must contain a private constructor");
                        }

                        ms_Instance = (T)ci.Invoke(null);
                        //instance = Activator.CreateInstance(typeof(T)) as T;
                    }
                }
            }

            return ms_Instance;
        }
    }
}

所以咋使用?举个例子:

public class XXX : Singleton<XXX>
{
    /// <summary>
    /// 空构造函数
    /// </summary>
    private XXX()
    {
    }
}



版权声明:本文为arbut原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。