繁体   English   中英

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

[英]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; }
    }
}

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

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

r1.Size.Width.InInches.Color.

等等

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM