您可能会发现自己在说:我知道。
类属性可以与其他类关联:
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 与其他类关联,并将另一个类与其他类关联,依此类推...