C#---继承单例的实现
c#可继承单例模板的实现,网上很多都是以另一种方式实现的,在使用时去控制,而不是生成的时候控制。
也是从别人那里捞过来的,但是具体的出处忘记在哪了,感谢那位无名的大哥!
using System;
using System.Linq;
using System.Reflection;
//利用Reflection与Lazy实现单例模式的泛型实现
public abstract class SPDataBase_Singleton<T> where T : class
{
private static readonly Lazy<T> _instance
= new Lazy<T>(() =>
{
var ctors = typeof(T).GetConstructors(
BindingFlags.Instance
| BindingFlags.NonPublic
| BindingFlags.Public);
if (ctors.Count() != 1)
throw new InvalidOperationException(String.Format("Type {0} must have exactly one constructor.", typeof(T)));
var ctor = ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate);
if (ctor == null)
throw new InvalidOperationException(String.Format("The constructor for {0} must be private and take no parameters.", typeof(T)));
return (T)ctor.Invoke(null);
}, true);
public string DataName { get; set; }
public static T Instance
{
get{
return _instance.Value;
}
}
public bool CheckMsgFunc(string name,SpObject msg)
{
Type t = this.GetType();
//Debug.Log("Checking type .. " + t);
MethodInfo method = t.GetMethod(name);
if(method != null)
{
//Debug.Log("Find " + name + " in " + t + " " + Instance.GetHashCode());
method.Invoke(Instance, new SpObject[] {msg });
return true;
}
else
{
//Debug.Log("Can't find " + name + " in " + t);
return false;
}
}
}
浙公网安备 33010602011771号