本文源码来自 凉鞋大大的 QFramework
首先我们需要一个对象构造器
SingletonCreator
using System;
using System.Reflection;
public static class SingletonCreator
{
public static T CreateSingleton<T>() where T : class, ISingleton
{
// 获取私有构造函数
var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
// 获取无参构造函数
var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
if (ctor == null)
{
throw new Exception("Non-Public Constructor() not found! in " + typeof(T));
}
// 通过构造函数,创建实例
var retInstance = ctor.Invoke(null) as T;
retInstance.OnSingletonInit();
return retInstance;
}
}
1)GetConstructors() : 返回为当前Type 定义的所有公共构造函数
返回值为 System.Reflection.ConstructorInfo[] GetConstructors();
2)ConstructorInfo 对象的数组,表示当前 Type 定义的所有公共实例构造函数,但不包括类型初始值设定项(静态构造函数)。 如果没有为当前 Type 定义公共实例构造函数,或者当前