我有一个小类,它实现了一个字典,该字典从接口的类型映射到从基类扩展的接口的实现。可惜抽象基类并没有实现接口,所以一旦在字典中,似乎没有办法将两者联系起来。这个类中还有另一种方法,它依赖于将对象存储为 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?
}
是否有任何聪明的约束可以用来删除 (base is T) 检查、强制转换为对象或两者兼而有之?
这是课程设置,供参考:
class BaseClass { }
interface IThing { }
class MyClass : BaseClass, IThing { }
dict.Add<IThing>(new MyClass());
IThing myClass = dict.Get<IThing>();