通用集合实例中的多类型约束

时间:2011-01-31 14:51:51

标签: c# collections generics

我想实例化一个泛型集合(在这种情况下是一个Dictionary)但是在泛型类型声明中我希望将参数类型约束为多于1个类。

以下是示例代码:

我有很多关于这个声明的课程:

public class MyClass1 : UserControl, IEspecialOptions
public class MyClass2 : UserControl, IEspecialOptions, IOtherInterface

这就是我想要的:

Dictionary<int, T> where T:UserControl, IEspecialOptions myDicc = new Dictionary<int, T>();

这看起来很不错但不编译。

你知道如何禁止第二个参数来加密2个类/接口吗?

我只限于.net 2.0

提前致谢

3 个答案:

答案 0 :(得分:3)

你需要在产生T的方法或类级别指定约束,而不是在声明变量时。

class myDictClass<T> : where T:UserControl,IEspecialOPtions
{
  Dictionary<int,T> myDicc;
}

答案 1 :(得分:3)

你做不到。但是您可以创建一个抽象类,它继承UserControl并实现IEscpecialOptions,然后将泛型参数约束为抽象类型。

答案 2 :(得分:1)

只需创建Dictionary<TKey,TValue>的自定义祖先即可引入约束。像这样:

public class CustomControlDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    where TValue : UserControl, IEspecialOptions
{
    // possible constructors and custom methods, properties, etc.
}

然后您就可以在代码中使用它了:

// 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 = ...;

如果您的示例中的类型参数T是从外部提供的,您必须非常自然地在周围的类级别引入类型约束。

public class MyCustomControlContainer<T> where T : UserControl, IEspecialOptions
{
    // this compiles:
    private CustomControlDictionary<int, T>;
}

注意:如果您想要在同一个字典中同时混合MyClass1MyClass2个实例,则必须为它们引入一个共同的祖先,继承自UserControl并实施IEspecialOptions。在这种情况下,抽象类是正确的方法。