2011-01-31 36 views
1

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

下面是示例代码:

我有很多个教学班,这个声明:

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提前

回答

3

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

3

2.0

谢谢,你需要指定,介绍T,声明你的变量不是在方法或类级别该限制。

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

只是让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>; 
} 

注:如果你想在同一字典都MyClass1MyClass2情况下混合,你就必须引入一个共同的祖先对他们来说,从UserControl继承和实施IEspecialOptions。在这种情况下,抽象类将是正确的方法。