C#通用继承解决方法

Sem*_*ike 2 c# generics inheritance

例:

我想要从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();  
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

class SpecializedTB : CommonFeatures<TextBox>
{
    // using properties/methods specific to TextBox
    protected override void OnTextChanged(TextChangedEventArgs e) 
    { 
        ... base.OnTextChanged(e); 
    }
}
Run Code Online (Sandbox Code Playgroud)

class SpecializedRTB : CommonFeatures<RichTextBox>
{
    // using methods/properties specific to RichTextBox
}
Run Code Online (Sandbox Code Playgroud)

不幸

class CommonFeatures<T> : T where T : TextBoxBase
Run Code Online (Sandbox Code Playgroud)

不编译("不能从'T'派生,因为它是一个类型参数").

有一个很好的解决方案吗?谢谢.

Ran*_*Ran 6

C#泛型不支持从参数类型继承.

你真的需要CommonFeatures派生出来TextBoxBase吗?

一个简单的解决方法可能是使用聚合而不是继承.所以你会有这样的事情:

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            
    }
}
Run Code Online (Sandbox Code Playgroud)

像@oxilumin说,扩展方法也可以是一个伟大的选择,如果你并不真的需要CommonFeatures成为一个TextBoxBase.