我有一个小类,它实现了一个从接口类型映射到从基类扩展的接口实现的字典。不幸的是,抽象基类没有实现接口,所以一旦在字典中,似乎没有办法将两者联系起来。在这个类中还有另一种方法,它依赖于将对象存储为BaseClass(实际上,我的大部分类都依赖于这个方法 - 入字典中的getter有点方便)。允许从接口转换为实现的通用约束
private readonly Dictionary<Type, BaseClass> dictionary;
public void Add<T>(BaseClass base)
{
if (!(base is T)) // How to get rid of this check?
{
throw new ArgumentException("base does not implement " + typeof(T).Name);
}
this.dictionary.Add(typeof(T), base);
}
public T Get<T>()
{
BaseClass base;
this.dictionary.TryGetValue(typeof(T), out base);
return (T)(object)base; // How to get rid of (object) cast?
}
是否有任何聪明约束我可以使用以除去(碱T)检查,铸造到对象,或两者兼而有之?
这里是类设置,以供参考:
class BaseClass { }
interface IThing { }
class MyClass : BaseClass, IThing { }
dict.Add<IThing>(new MyClass());
IThing myClass = dict.Get<IThing>();
我现在通过使用描述[这里](http://stackoverflow.com/questions/2893698/partial-generic-type-inference-possible-in-c),现在大约一半的路径,我得到使用类型推断消除Add()中的检查。在Get()中放弃演员阵容可能比值得付出更多的努力,因为我知道演员由于通过Add()控制访问是安全的。 – lukegravitt