[英]How to constrain type of generic extension
I am trying to extend a specific class (say WPF's StackPanel). 我试图扩展一个特定的类(比如WPF的StackPanel)。 Let's call this extension MyGenericPanel.
我们将此扩展称为MyGenericPanel。 I guess its declaration should be:
我猜它的声明应该是:
class MyGenericPanel : StackPanel
But... if I want this extension to hold variable type of reference (say T) declaration would become: 但是......如果我希望这个扩展包含变量类型的引用(比方说T)声明将成为:
class MyGenericPanel<T> : StackPanel
Now what if I want to restrict T to be of type Identifiable... where Identifiable is another class. 现在如果我想将T限制为类型可识别...其中Identifiable是另一个类。
class MyGenericPanel<T> where T: Identifiable, StackPanel
complains that StackPanel should come first... if I put 抱怨StackPanel应该先来......如果我放的话
class MyGenericPanel<T> where T: StackPanel, Identifiable
the compiler complains Identifiable should come before StackPanel. 编译器抱怨Identifiable应该出现在StackPanel之前。
Bottomline: 底线:
How can I do this?... (or, can it be done?) 我怎么能这样做?......(或者,可以吗?)
I think you are confusing the specfication of the base class with the generic type constraint: 我认为你混淆基类的规范与泛型类型约束:
class MyGenericPanel<T> : StackPanel where T: Identifiable
The class that comes after MyGenericPanel<T> :
is the base class, the class after where T:
is the generic type constraint MyGenericPanel<T> :
之后的类是基类, where T:
是泛型类型约束之后的类
MyGenericPanel
extends StackPanel
MyGenericPanel
扩展了StackPanel
T
is an extension of Identifiable
T
是Identifiable
的扩展
translated into 翻译成
class MyGenericPanel<T> : StackPanel where T : Identifiable
Now what if I want to restrict T to be of type Identifiable... where Identifiable is another class
现在如果我想将T限制为类型可识别...其中Identifiable是另一个类
well if Identifiable
and StackPanel
are both classes than it can't work because putting 2 class type contraints would mean multiple inheritance , something that's not allowed in C#. 好吧,如果
Identifiable
和StackPanel
都是类而不是它不能工作,因为放入2类类型约束将意味着多重继承,这是C#中不允许的。 That's why the complier complains about your constraints . 这就是编译器抱怨你的约束的原因。
If you mean to have your MyGenericPanel<T>
extend the functionality of StackPanel
and restrict T
to be of type Identifiable
, then following would work : 如果您的意思是让
MyGenericPanel<T>
扩展StackPanel
的功能并将T
限制为Identifiable
类型,那么以下方法可行:
class MyGenericPanel<T> : StackPanel where T : Identifiable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.