简体   繁体   English

C#通用继承解决方法

[英]C# Generic Inheritance workaround

Example: 例:

I'd like to have several specialized textboxes that derive from either TextBox or RichTextBox, which both derive from TextBoxBase: 我想有几个专门从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();  
    }
}

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 : TextBoxBase

doesn't compile ("Cannot derive from 'T' because it is a type parameter"). 无法编译(“因为它是类型参数,所以不能从'T'派生”)。

Is there a good solution to this? 有一个好的解决方案吗? Thanks. 谢谢。

C# generics don't support inheritance from a parameter type. C#泛型不支持从参数类型继承。

Do you really need CommonFeatures to derive from TextBoxBase ? 您是否真的需要CommonFeatures来从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 . 就像@oxilumin所说的那样,如果您真的不需要CommonFeatures作为TextBoxBase ,则扩展方法也可能是一个不错的选择。

If your CommonFeature class has not an it's own condition - you can use extension methods for this. 如果您的CommonFeature类没有它自己的条件-您可以为此使用扩展方法。

public static class TextBoxBaseExtensions
{
    public static YourReturnType YourExtensionMethodName(this TextBoxBase textBoxBase, /*your parameters list*/)
    {
        // Method body.
    }
}

And then you can use this method in the same way with all real class-methods: 然后,您可以对所有真实的类方法以相同的方式使用此方法:

var textBox = new TextBox();
textBox.YourExtensionMethodName(/* your parameters list */);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM