【发布时间】:2013-02-21 13:05:12
【问题描述】:
我有一个看起来像这样的通用单例:
public class Cache<T>
{
private Dictionary<Guid, T> cachedBlocks;
// Constructors and stuff, to mention this is a singleton
public T GetCache(Guid id)
{
if (!cachedBlocks.ContainsKey(id))
cachedBlocks.Add(id, LoadFromSharePoint(id))
return cachedBlocks[id];
}
public T LoadFromSharePoint(Guid id)
{
return new T(id) // Here is the problem.
}
}
错误信息是:
无法创建类型 T 的实例,因为它没有 new() 约束。
我必须提到我必须传递id 参数,并且没有其他方法可以这样做。任何有关如何解决此问题的想法都将受到高度赞赏。
【问题讨论】:
标签: c# constructor initialization generics