简体   繁体   English

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

[英]Multiple type constraint in Generic Collection instance

I want to instantiate a generic collection (a Dictionary in this case) but in the generic type declaration I want constraint the parameter type to more then 1 class. 我想实例化一个泛型集合(在这种情况下为Dictionary),但是在泛型类型声明中,我想将参数类型限制为1个以上的类。

Here is the example code: 这是示例代码:

I have many classes with this declaration: 我有很多这样的声明类:

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

etc. 等等

This is what I want: 这就是我要的:

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

This looks very nice but don't compile. 这看起来很不错,但是不能编译。

Do you know how to contraint the second parameter to inherate from 2 classes/interfaces? 您知道如何约束第二个参数以从2个类/接口继承吗?

I'm limited to .net 2.0 我仅限于.net 2.0

Thanks in advance 提前致谢

YOu need to specify the contraint at the method or class level that introduces T, not when declaring your variable. 您需要在引入T的方法或类级别上指定约束,而不是在声明变量时指定约束。

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

You cannot. 你不能。 But you can create an abstract class that both inherits UserControl and implements IEscpecialOptions and then constraint the generic parameter to be of the abstract type. 但是您可以创建一个既继承UserControl又实现IEscpecialOptions的抽象类,然后将通用参数约束为抽象类型。

Just make a custom ancestor of Dictionary<TKey,TValue> to introduce the constraint. 只需创建一个Dictionary<TKey,TValue>的自定义祖先来引入约束。 Like this: 像这样:

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

Then you will be able to use it in your code like you want: 然后,您将可以根据需要在代码中使用它:

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

In case the type parameter T from your example is provided from outside, you have to, quite naturally, introduce the type constraint at the surrounding class level. 如果您的示例中的类型参数T是从外部提供的,则必须自然而然地在周围的类级别引入类型约束。

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

Note: In case you'd want to mix both MyClass1 and MyClass2 instances in the same dictionary, you'd have to introduce a common ancestor for them, inheriting from UserControl and implementing IEspecialOptions . 注意:如果要在同一字典中混合使用MyClass1MyClass2实例,则必须为它们引入一个共同的祖先,继承自UserControl并实现IEspecialOptions An abstract class would be the right way in that case. 在这种情况下,抽象类将是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM