【问题标题】:C# - Automatically pass method call to method of object with same signatureC# - 自动将方法调用传递给具有相同签名的对象的方法
【发布时间】:2018-10-21 13:38:08
【问题描述】:

我想在 C# WPF 中创建一个自定义 Rectangle,但无法从 Rectangle 继承。所以基本上我要做的就是从Rectangle复制我需要的方法并将它们传递给我保留在我的自定义Rectangle-class中的Rectangle-Object,如下所示:

private double _width;
public double Width
{
    get => _width;
    set
    {
        _width = value;
        _rectangle.Width = _width;
    }
}
private double _height;
public double Height
{
    get => _height;
    set
    {
        _height = value;
        _rectangle.Height = _height;
    }
}
private Brush _stroke;
public Brush Stroke
{
    get => _stroke;
    set
    {
        _stroke = value;
        _rectangle.Stroke = _stroke;
    }
}
private int _strokeThickness;
public int StrokeThickness
{
    get => _strokeThickness;
    set
    {
        _strokeThickness = value;
        _rectangle.StrokeThickness = _strokeThickness;
    }
}
private Brush _fill;
public Brush Fill
{
    get => _fill;
    set
    {
        _fill = value;
        _rectangle.Fill = _fill;
    }
}
private bool _focusable;
public bool Focusable
{
    get => _focusable;
    set
    {
        _focusable = value;
        _rectangle.Focusable = _focusable;
    }
}

C# .NET 中是否有一个语言功能可以为我做这件事,所以我不必手动编写所有内容?

【问题讨论】:

  • 听起来像是 XY 问题。你为什么要继承/模仿 WPF 的Rectangle
  • 什么是XY Problem?我模仿这种行为是因为我想实现一些自定义的东西(比如在Canvas 中将矩形相互对齐)我认为delegates 是我需要的,但似乎这只是某种方法传递。跨度>
  • 您是否考虑过创建Extension Methods 来扩展Rectangle 的行为,而不必创建一个新类?
  • 您可以改为从 Shape 继承

标签: c# wpf rectangles


【解决方案1】:

在母语中没有。可能是因为这通常不是您想要的。

密封类是有原因的。

在您的示例中,我没有看到任何添加的属性,所以也许扩展方法是要走的路?

我还看到每个属性都有一个字段和一个字段_rectangle。你为什么这样做。您可以在 getter 中返回 _rectangle.width

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多