只是让Dictionary<TKey,TValue>
的自定义祖先引入约束。就像这样:
public class CustomControlDictionary<TKey, TValue> : Dictionary<TKey, TValue>
where TValue : UserControl, IEspecialOptions
{
// possible constructors and custom methods, properties, etc.
}
然后你就可以在你的代码中使用它像你想:如果从你的榜样类型参数T
从外部提供
// this compiles:
CustomControlDictionary<int, MyClass1> dict1 = new CustomControlDictionary<int, MyClass1>();
CustomControlDictionary<int, MyClass2> dict2 = new CustomControlDictionary<int, MyClass2>();
// this fails to compile:
CustomControlDictionary<int, string> dict3 = ...;
,你必须这样做,很自然地,在周围的班级引入类型约束。
public class MyCustomControlContainer<T> where T : UserControl, IEspecialOptions
{
// this compiles:
private CustomControlDictionary<int, T>;
}
注:如果你想在同一字典都MyClass1
和MyClass2
情况下混合,你就必须引入一个共同的祖先对他们来说,从UserControl
继承和实施IEspecialOptions
。在这种情况下,抽象类将是正确的方法。