5 c# generics dictionary .net-4.0
我有一个名为泛型的类Manager<T>,我想创建一个字典,将类型映射到此类型的Manager类的实例.我想过创建一个派生自的Dictionary类Dictionary,但是覆盖它的所有方法似乎有些过分.想法?谢谢.
假设您的字典需要保存具有混合类型参数的管理器,您可以IManager在 中实现一个接口Manager<T>,创建一个Dictionary<Type,IManager>,并添加一个通用包装器以将实例强制转换回Maanger<T>,如下所示:
interface IManager {
// Properties and methods common to all Maanger<T>, regardless of T
}
class Manager<T> : IManager {
}
class Main {
private readonly IDictionary<Type,IManager> managers =
new Dictionary<Type,IManager>();
bool TryGetManager<T>(Type key, out Manager<T> manager) {
IManager res;
return managers.TryGetValue(key, out res) ? ((Manager<T>)res) : null;
}
}
Run Code Online (Sandbox Code Playgroud)