通用集合实例中的多类型约束
我想实例化一个泛型集合(在本例中为字典),但在泛型类型声明中,我希望将参数类型限制为超过 1 个类。
这是示例代码:
我有很多带有此声明的类:
public class MyClass1 : UserControl, IEspecialOptions
public class MyClass2 : UserControl, IEspecialOptions, IOtherInterface
等等。
这就是我想要的:
Dictionary<int, T> where T:UserControl, IEspecialOptions myDicc = new Dictionary<int, T>();
这看起来非常好,但无法编译。
你知道如何限制第二个参数继承两个类/接口吗?
我仅限于 .net 2.0
提前致谢
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.
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?
I'm limited to .net 2.0
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能。但是您可以创建一个继承
UserControl
并实现IEscpecialOptions
的抽象类,然后将泛型参数限制为抽象类型。You cannot. But you can create an abstract class that both inherits
UserControl
and implementsIEscpecialOptions
and then constraint the generic parameter to be of the abstract type.您需要在引入 T 的方法或类级别指定约束,而不是在声明变量时指定。
YOu need to specify the contraint at the method or class level that introduces T, not when declaring your variable.
只需创建一个
Dictionary
的自定义祖先即可引入约束。像这样:然后您将能够按照您想要的方式在代码中使用它:
如果示例中的类型参数
T
是从外部提供的,您必须很自然地引入类型约束在周围的班级水平。注意:如果您想在同一字典中混合使用
MyClass1
和MyClass2
实例,则必须为它们引入一个共同的祖先,继承自UserControl
并实现IEspecialOptions
。在这种情况下,抽象类是正确的方法。Just make a custom ancestor of
Dictionary<TKey,TValue>
to introduce the constraint. Like this:Then you will be able to use it in your code like you want:
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.Note: In case you'd want to mix both
MyClass1
andMyClass2
instances in the same dictionary, you'd have to introduce a common ancestor for them, inheriting fromUserControl
and implementingIEspecialOptions
. An abstract class would be the right way in that case.