我有一个通用的单例模板和一个派生类。当从外部访问单个实例时,它返回null。我在代码中没有发现任何错误。实际上,在调试过程中,静态构造函数会分配_Instance字段。但是,当涉及到Instance属性时,该值为null!
消费者使用:
var value = Consumer.Instance.SomeProperty;单例模板和使用者:
namespace SingletonExample
{
using System;
using System.Linq;
using System.Reflection;
public sealed class Consumer:
Singleton<Consumer>
{
private Consumer ()
{
}
public bool SomeProperty { get { return (true); } }
}
public abstract class Singleton<T>
where T: Singleton<T>
{
protected Singleton ()
{
Singleton<T>.ThrowOnInCompatibleImplementation();
}
private static readonly T _Instance = null;
static Singleton ()
{
Singleton<T>.ThrowOnInCompatibleImplementation();
Singleton<T> _Instance = (T) Activator.CreateInstance(type : typeof(T), nonPublic : true);
}
public static T Instance { get { return (Singleton<T>._Instance); } }
private static void ThrowOnInCompatibleImplementation ()
{
if (!typeof(T).IsSealed)
{
// Force derived classes to be sealed.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must be sealed."));
}
if (typeof(T).GetConstructors(BindingFlags.Static | BindingFlags.NonPublic).Any())
{
// Disallow derived classes to implement static constructors.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must not have static constructors."));
}
if (typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public).Any())
{
// Disallow derived classes to implement instance public constructors.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must not have public constructors."));
}
if (typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Any(ctor => !ctor.IsPrivate))
{
// Disallow derived classes to implement instance protected constructors.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must not have protected constructors."));
}
if (!typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Any())
{
// Force derived classes to implement a private parameterless constructor.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must have a private parameterless constructor."));
}
if (typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Any(ctor => ctor.GetParameters().Length != 0))
{
// Force derived classes to implement a private parameterless constructor.
throw (new InvalidOperationException("Classes derived from [Singleton<T>] must have a private parameterless constructor."));
}
}
}
}虽然我对改进实现的建议持开放态度,但是在这些模板、线程安全和好/坏的实践方面已经有很多问题。会很感激你对这里出了什么问题的任何暗示。
发布于 2014-07-24 05:22:19
Singleton<T> _Instance = (T) Activator.CreateInstance(type : typeof(T), nonPublic : true);应该是
_Instance = (T) Activator.CreateInstance(type : typeof(T), nonPublic : true);https://stackoverflow.com/questions/24925538
复制相似问题