【问题标题】:Custom control with type parameters带有类型参数的自定义控件
【发布时间】:2012-09-29 05:30:51
【问题描述】:

我正在构建一个扩展 DataGridView 的 WinForms 自定义控件。

interface IMyControl<A, B> { }
public partial class MyControl<A, B> : DataGridView, IMyControl<A, B>
{
}

AB 是业务域对象类型。

但是,代码不会编译。 MyControl.Designer.cs 无法编译。

protected override void Dispose(bool disposing) //no suitable method found to override
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    //'object' does not contain a definition for 'Dispose'
    base.Dispose(disposing); 
}

'Infrastructure.MyControl.Dispose(bool)': 找不到合适的方法来覆盖 MyControl.Designer.cs

【问题讨论】:

    标签: c# winforms oop design-patterns


    【解决方案1】:

    您不能拥有通用控件。

    试试这个:

    interface IMyControl<A, B> { }
    public partial abstract class MyControlBase<A, B> : DataGridView, IMyControl<A, B>
    {
        // Generic code goes here
    }
    
    // Create non-generic wrappers for the generic base class
    public partial class MyControl_One : DataGridView, MyControlBase<SomeType, OtherType>
    {
         // Type-specific (if any) code goes here
    }
    public partial class MyControl_Two : DataGridView, MyControlBase<MyType, YourType>
    {
         // Type-specific (if any) code goes here
    }
    

    将您当前拥有的任何通用代码留在通用基类中。包装器类可能非常薄,因为它只用于提供非泛型控件以添加到您的表单中。

    【讨论】:

    • 抽象 MyControlBase 的主体是 emtpy 吗?
    • 不,它应该包含您的通用代码。为了澄清,我编辑了我的答案。
    • 谢谢。看来我不需要接口IMyControl
    猜你喜欢
    • 2021-11-16
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多