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

时间:2016-04-15 18:43:34

标签: c# class properties declaration

我想像常见的矩形那样理解并创建自己的类:

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

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

如果我想创建更长的链? e.g:

r1.Size.Width.InInches.Color.

1 个答案:

答案 0 :(得分:0)

你可能会发现自己说:我知道了。

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

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

你所谓的 chain 就是面向对象编程中所谓的composition

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