C# 泛型集合实例中的多类型约束

C# 泛型集合实例中的多类型约束,c#,collections,generics,C#,Collections,Generics,我想实例化一个泛型集合(在本例中是一个字典),但在泛型类型声明中,我想将参数类型约束为多于1个类 下面是示例代码: 我有很多类都有这样的声明: public class MyClass1 : UserControl, IEspecialOptions public class MyClass2 : UserControl, IEspecialOptions, IOtherInterface 等等 这就是我想要的: Dictionary<int, T> where T:UserCon

我想实例化一个泛型集合(在本例中是一个字典),但在泛型类型声明中,我想将参数类型约束为多于1个类

下面是示例代码:

我有很多类都有这样的声明:

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

这就是我想要的:

Dictionary<int, T> where T:UserControl, IEspecialOptions myDicc = new Dictionary<int, T>();
字典,其中T:UserControl,IEspecialOptions myDicc=new Dictionary();
这看起来很好,但不需要编译

你知道如何将第二个参数限制在两个类/接口中吗

我仅限于.NET2.0


提前感谢

您需要在方法或类级别指定引入T的约束,而不是在声明变量时

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

您需要在方法或类级别指定引入T的约束,而不是在声明变量时

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

您不能。但是您可以创建一个抽象类,既继承
UserControl
又实现
iescpecialpoptions
,然后将泛型参数约束为抽象类型。

您不能。但是您可以创建一个抽象类,该类继承
UserControl
并实现
iescpecialpoptions
,然后将泛型参数约束为抽象类型。

只需创建一个
字典的自定义祖先来引入约束即可。像这样:

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

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

只需创建一个自定义的
字典的祖先来引入约束。像这样:

public class CustomControlDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    where TValue : UserControl, IEspecialOptions
{
    // possible constructors and custom methods, properties, etc.
}
注意:如果您想在同一个字典中混合使用
MyClass1
MyClass2
实例,您必须为它们引入一个共同的祖先,继承自
UserControl
并实现
IEspecialOptions
。在这种情况下,抽象类是正确的方法