【问题标题】:Creating multiple / multinode properties in class在类中创建多个/多节点属性
【发布时间】:2016-04-15 18:43:33
【问题描述】:

我想像普通矩形一样理解并制作自己的类:

Rectangle r1 = new Rectangle();
Size s = r1.Size;
int size = r1.Size.Width;

我不想使用方法,只是简单的属性值。

public partial class Rectangle
{
    private Size _size;
    public Size Size
    {
        get { return _size; }
        set { _size = value; }
    }
}

那么如何创建Width、Height等属性呢?

如果我想创建更长的链?例如:

r1.Size.Width.InInches.Color.

等等

【问题讨论】:

  • Width 和 Height 是 Size 结构的属性,请参阅 here 要创建方法链,它通常称为 Fluent Interface 或 Syntax,请参阅 here 了解更多信息。跨度>
  • 创建嵌套对象,然后在其中嵌套对象,等等。
  • @amura.cxg 嗯,流利的有点不同。 Fluent 通常返回原始对象,因此您可以链接多个调用 - 这只是普通的 OOP 封装。
  • 为什么不使用“public Size Size { get; set; }”?

标签: c# class properties declaration


【解决方案1】:

您可能会发现自己在说:我知道。

类属性可以与其他类关联:

public class Size 
{
    public Size(double width, double height)
    {
        Width = width;
        Height = height;
    }
    public double Width { get; }
    public double Height { get; }
}

现在您将能够获得矩形的大小,如下所示:rect1.Size.Width

关于提供大小单位,我不会创建InInches 属性,但我会创建一个枚举:

public enum Unit
{
    Inch = 1,
    Pixel
}

...我将向Size 添加一个属性,如下所示:

public class Size 
{
    public Size(double width, double height, Unit unit)
    {
        Width = width;
        Height = height;
        Unit = unit;
    }

    public double Width { get; }
    public double Height { get; }
    public Unit Unit { get; }
}

...如果您需要执行转换,您也可以在Size 中轻松实现它们:

public class Size 
{
    public Size(double width, double height, Unit unit)
    {
        Width = width;
        Height = height;
        Unit = unit;
    }

    public double Width { get; }
    public double Height { get; }
    public Unit Unit { get; }

    public Size ConvertTo(Unit unit)
    {
        Size convertedSize;

        switch(unit) 
        {
            case Unit.Inch:
                // Calc here the conversion from current Size
                // unit to inches, and return
                // a new size
                convertedSize = new Size(...);
                break;


            case Unit.Pixel:
                // Calc here the conversion from current Size 
                // unit to pixels, and return
                // a new size
                convertedSize = new Size(...);
                break;

            default:
                throw new NotSupportedException("Unit not supported yet");
                break;
        }

        return convertedSize;
    }
}

你所称的在面向对象编程中被称为composition

因此,您可以将 Size 与其他类关联,并将另一个类与其他类关联,依此类推...

【讨论】:

  • 感谢您的快速回答,两个答案都是正确且有帮助的,再次感谢 Size ConvertTo 的想法!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多