例子:C#泛型继承的解决办法
我想有一个无论从文本框或RichTextBox中派生几个专门的文本框,这无论从Control派生:
class CommonFeatures<T> : T where T : TextBoxBase
{
// lots of features common to the TextBox and RichTextBox cases, like
protected override void OnTextChanged(TextChangedEventArgs e)
{
//using TextBoxBase properties/methods like SelectAll();
}
}
然后
class SpecializedTB : CommonFeatures<TextBox>
{
// using properties/methods specific to TextBox
protected override void OnTextChanged(TextChangedEventArgs e)
{
... base.OnTextChanged(e);
}
}
and
class SpecializedRTB : CommonFeatures<RichTextBox>
{
// using methods/properties specific to RichTextBox
}
不幸的是
class CommonFeatures<T> : T where T : TextBoxBase
不编译(“无法从‘T’派生,因为它是一个类型参数”)。
有没有很好的解决方案呢?谢谢。
它应该是类CommonFeatures其中T:TextBoxBase –
2011-05-22 20:08:00
@Tomas Voracek好这一点,类CommonFeatures:其中T:TextBoxBase因为CommonFeatures需要从它继承TextBoxBase的方法/属性,否则事情像OnTextChanged唐一类派生不存在。如果我直接从TextBoxBase继承,如何从RichTextBox或TextBox稍后添加属性/方法,而没有多重继承... –
SemMike
2011-05-22 20:23:44