假设我想实现一个过期的缓存,我想在底层存储容器上使它成为通用的.所以我将允许用户告诉我的班级要使用哪种容器类型.但由于我将填充私有类型,我需要它们告诉我一个通用类型.所以我想尝试做这样的事情:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以Container需要是泛型类型,因为我想将它专门化为私有类型.我想像这样使用它:
var cache = new MyCache<String, String, Dictionary>();
Run Code Online (Sandbox Code Playgroud)
哪会导致实现使用Dictionary.
这可能吗?它的语法是什么?如果不可能,那么在容器上获得类型安全性和这种可组合性的最佳选择是什么?
这不起作用,因为调用者无法创建Dictionary <K,MyValue> - MyValue private.
但是如果你制作MyValue就可以做到public:
public class MyValue<V>
{
public readonly V Value;
public readonly DateTime InsertionTime;
}
Run Code Online (Sandbox Code Playgroud)
您希望Container为IDictionary <K,MyValue <V >>并希望能够创建新的Container实例.因此,您需要在Container类型参数中使用以下约束:
class MyCache<K, V, Container> : IDictionary<K, V>
where Container : IDictionary<K, MyValue<V>>, new()
{
private IDictionary<K, MyValue<V>> m_dict = new Container();
}
Run Code Online (Sandbox Code Playgroud)
请注意,IDictionary <K,V>接口不提供TryGetValue方法.
用法示例:
var cache = new MyCache<string, int, Dictionary<string, MyValue<int>>>();
Run Code Online (Sandbox Code Playgroud)