C# 关联关系双方的子类化

C# 关联关系双方的子类化,c#,winforms,inheritance,C#,Winforms,Inheritance,我时不时地会遇到这种类型的设计问题,但我还没有找到一个通用的方法来解决它。详情如下: 我有一个Table类,它有Grid行标题、列标题和表本身的实例。这两个类都是可重用的组件 class Grid { public void Bar() { /* ... */} } class Table { public Grid[] Grids { get; } public void Foo() { /* ... */ } } 我还有一个CustomGrid,它添加了一种新方法

我时不时地会遇到这种类型的设计问题,但我还没有找到一个通用的方法来解决它。详情如下:

我有一个
Table
类,它有
Grid
行标题、列标题和表本身的实例。这两个类都是可重用的组件

class Grid {
    public void Bar() { /* ... */}
}

class Table {
    public Grid[] Grids { get; }
    public void Foo() { /* ... */ }
}
我还有一个
CustomGrid
,它添加了一种新方法(用一些逻辑绘制奇特的颜色)。现在,我希望子类Table添加一些方法,这些方法公开了
CustomGrid
附带的新特性

class CustomGrid : Grid {
    public void Bar2() { /* ... */}
}

class CustomTable : Table {
    public void Foo2() { /* ... */ }
}
  • 但是,由于
    表格
    引用了
    网格
    对象,
    自定义表格
    需要将它们向下转换
    自定义网格
    以使用新方法,我认为这不是很漂亮
  • 通过在
    Table
    类中使用泛型,
    CustomTable
    可以使用
    CustomGrid
    s,但我认为类型检查和向下转换仍然是必要的
  • 我希望使用组合而不是继承,但它将阻止重写
    OnPaint
    方法。此外,一些私有构造需要公开,以便在包含类时使用

您将如何处理此设计?我认为上述困难意味着其中存在问题,但请指出期权评估中的任何错误。

您可以使用
new
关键字:

public class CustomTable : Table
{
    new public CustomGrid[] Grids { get; }
    public void Foo2() { /* ... */ }
}

这将覆盖您的
Grid[]Grids{get;}
CustomGrid[]Grids{get;}

谢谢。但是,这将导致在Table和CustomTable类中分配两个单独的数组。