我目前有一个 6 或 7 个单例的集合,所有这些都做几乎相同的事情(参见For
下面示例中的方法)但使用不同的内部数据库查询并返回不同对象的集合(因此解析数据库结果是不同的在每个单身人士中)。
因此,使用这个问题作为我的基础,我一直在尝试在 C# 中为这些单例构建一个抽象的通用基类。
关于 SO也有类似的问题Lazy
,但没有实施,我希望这样做。
到目前为止我有这个
public abstract class SingletonBase<T> where T : class, new()
{
private static Lazy<SingletonBase<T>> _lazy;
private static readonly object _lock = new object();
public static SingletonBase<T> Instance
{
get
{
if (_lazy != null && _lazy.IsValueCreated)
{
return _lazy.Value;
}
lock (_lock)
{
if (_lazy != null && _lazy.IsValueCreated)
{
return _lazy.Value;
}
***** this is the problem line *****
_lazy = new Lazy<SingletonBase<T>>(new T());
}
return _lazy.Value;
}
}
public abstract IEnumerable<T> For(string systemLangCode);
}
但是,上线出现问题
_lazy = new Lazy<SingletonBase<T>>(new T());
Visual Studio 告诉我“无法解析构造函数 'Lazy<T>'。”
我不确定应该将什么传递给构造函数Lazy<SingletonBase<T>>
,还是我走错了方向?