在 class 中创建多个/多节点属性

Creating multiple / multinode properties in class

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

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; }
    }
}

那么如何创建宽度、高度等属性?

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

r1.Size.Width.InInches.Color.

等等

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

Class 属性可以与其他 classes:

关联
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 与其他 class 关联,并将另一个 class 与另一个 class 关联,依此类推...