简体   繁体   English

使用泛型创建可重用的基类Control类

[英]Using generics to create a reusable base Control class

I don't know if this is possible but this is what I was thinking: 我不知道这是否可能,但这就是我的想法:

public class ValidationControl<T> where T : Control, new()
{
    [Browsable(true)]
    [Category("Validation")]
    [DefaultValue(false)]
    public bool Required { get; set; }

    public ValidationControl() { Required = false; }

    public virtual void RunValidation() { ... }
}

Then for all of my custom controls I could simply use the generic control as a reusable base class: 然后,对于我的所有自定义控件,我可以简单地将通用控件用作可重用的基类:

public class ValidationTextBox : ValidationControl<TextBox> { }

public class ValidationComboBox : ValidationControl<ComboBox> { }

I understand that I could use interfaces but then I would have to retype/copy & paste the required property, etc., for each new control I make. 我知道我可以使用接口但是我必须为我制作的每个新控件重新输入/复制和粘贴所需的属性等。 Also I am unable to override any virtual properties / methods this way for TextBox/ComboBox. 此外,我无法以TextB / ComboBox的方式覆盖任何虚拟属性/方法。 Is this possible? 这可能吗?

Inheriting is something different then using generics. 继承与使用泛型不同。 You want to specify in a 'generics' way what your class needs to inherit from, and no, that is not going to work. 您希望以“泛型”方式指定您的类需要继承的内容,而不是,这不会起作用。 You already said it, you cannot override any properties, which is because you do not inherit from your T. 你已经说过了,你不能覆盖任何属性,这是因为你没有从你的T继承。

For your control to work you must inherit from your control type (T). 要使控件正常工作, 必须从控件类型(T)继承。

Also I am unable to override any virtual properties / methods this way for TextBox/ComboBox. 此外,我无法以TextB / ComboBox的方式覆盖任何虚拟属性/方法。 Is this possible? 这可能吗?

You won't be able to override anything from TextBox/ComboBox. 您将无法覆盖TextBox / ComboBox中的任何内容。 You can only override virtual methods from base class, in Your exemple, only overridable method is RunValidation() (ValidationControl being base class). 您只能从基类覆盖虚方法,在您的示例中,只有可覆盖的方法是RunValidation()(ValidationControl是基类)。

You class can contain TextBox/ComboBox, fe: 你的类可以包含TextBox / ComboBox,fe:

private T Control;

and make some calls to it but that's all. 然后打电话给它,但就是这样。

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

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