示例:
我想要从TextBox或RichTextBox派生的几个专用文本框,它们都是从TextBoxBase派生的:
class CommonFeatures< T> :T其中T:TextBoxBase { // TextBox和RichTextBox大多数常用功能,例如 protected override OnTextChanged(TextChangedEventArgs e) { //使用像SelectAll()这样的TextBoxBase属性/方法; $ / code $ / pre然后
class SpecializedTB:CommonFeatures< TextBox> { //使用特定于TextBox的属性/方法 protected override void OnTextChanged(TextChangedEventArgs e) { ... base.OnTextChanged(e); code class SpecializedRTB:CommonFeatures< RichTextBox> { //使用特定于RichTextBox的方法/属性}不幸
class CommonFeatures< T> :T其中T:TextBoxBase不能编译(不能从'T'派生,因为它是一个类型参数)。
有没有很好的解决方案?感谢。
解决方案
你真的需要 CommonFeatures 来自 TextBoxBase ?
一个简单的解决方法可能是使用聚合而不是继承。所以你会有这样的东西:
public class CommonFeatures< T>其中T:TextBoxBase { private T innerTextBox; 保护CommonFeatures< T>(T inner) { innerTextBox = inner; innerTextBox.TextChanged + = OnTextChanged; } public T InnerTextBox {get {return innerTextBox; }} protected void OnTextChanged(object sender,TextChangedEventArgs e) { ...做你的东西} }像@oxilumin说的那样,如果你不需要 CommonFeatures 成为 TextBoxBase 。
Example:
I'd like to have several specialized textboxes that derive from either TextBox or RichTextBox, which both derive from 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(); } }and then
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 }Unfortunately
class CommonFeatures<T> : T where T : TextBoxBasedoesn't compile ("Cannot derive from 'T' because it is a type parameter").
Is there a good solution to this? Thanks.
解决方案C# generics don't support inheritance from a parameter type.
Do you really need CommonFeatures to derive from TextBoxBase?
A simple workaround may be to use aggregation instead of inheritance. So that you would have something like this:
public class CommonFeatures<T> where T : TextBoxBase { private T innerTextBox; protected CommonFeatures<T>(T inner) { innerTextBox = inner; innerTextBox.TextChanged += OnTextChanged; } public T InnerTextBox { get { return innerTextBox; } } protected virtual void OnTextChanged(object sender, TextChangedEventArgs e) { ... do your stuff } }Like @oxilumin says, extension methods may also be a great alternative if you don't really need CommonFeatures to be a TextBoxBase.
更多推荐
C#通用继承解决方法
发布评论