2011-01-31 86 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。在這種情況下,抽象類將是正確的方法。