假设我想实现一个到期的缓存,并且我想在底层存储容器上进行通用化。所以我会让用户告诉我的班级使用哪种容器类型。但是因为我会填充一个私有类型,所以我需要他们告诉我一个通用类型。所以,我试图做这样的事情:如何声明泛型的泛型类型参数?
class MyCache<K, V, Container> : IDictionary<K, V>
where Container : // what goes here?
{
private class MyValue
{
public readonly V Value;
public readonly DateTime InsertionTime;
}
private IDictionary<K, MyValue> m_dict = new Container<K, MyValue>(); // a specialization of the generic container
// implement IDictionary<K, V>, checking for value expiration
public bool TryGetValue(K key, out V val)
{
MyValue myval;
if (m_dict.TryGetValue(key, out myval))
{
if (Expired(myval.InsertionTime))
{
m_dict.Remove(key);
}
else
{
val = myval.Value;
return true;
}
}
// not there or expired
val = default(V);
return false;
}
}
所以容器需要是一个泛型类型,因为我想专注它在一个私有类型。我想像这样使用它:
var cache = new MyCache<String, String, Dictionary>();
这将导致实施使用词典。
这可能吗?它的语法是什么?如果不可能,在容器上获得类型安全性和这种可组合性的等级是什么最佳选择?
@MBabcock:无论如何,这篇文章已经消失了 - 我误解了这个问题。基本上OP所要求的在C#中是不可行的。 – 2012-03-12 17:27:15
同意。它看起来有点奇怪。这不正确吗? – 2012-03-12 17:27:55
@ M.Babcock:可能 - 它现在消失了,我不记得了。我所得到的甚至在某种程度上是陌生的,尽管它应该可行...... – 2012-03-12 17:31:36