【发布时间】:2011-05-22 20:03:28
【问题描述】:
例子:
我想要几个从 TextBox 或 RichTextBox 派生的专用文本框,它们都派生自 TextBoxBase:
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);
}
}
和
class SpecializedRTB : CommonFeatures<RichTextBox>
{
// using methods/properties specific to RichTextBox
}
很遗憾
class CommonFeatures<T> : T where T : TextBoxBase
无法编译(“不能从 'T' 派生,因为它是类型参数”)。
有没有好的解决方案?谢谢。
【问题讨论】:
-
应该是类 CommonFeatures
where T : TextBoxBase -
@Tomas Voracek 这就是重点,类 CommonFeatures
: T where T : TextBoxBase 因为 CommonFeatures 需要从继承 TextBoxBase 的方法/属性的类派生,否则 OnTextChanged 之类的东西不存在。如果我直接从TextBoxBase继承,我以后如何添加来自RichTextBox或TextBox的属性/方法,没有多重继承......
标签: c# generics inheritance