你必须像这样为形状添加一个字段:
type
TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
TFigure = record
case Shape: TShapeList of
Rectangle: (Height, Width: Real);
Triangle: (Side1, Side2, Angle: Real);
Circle: (Radius: Real);
Ellipse, Other: ();
end;
注意Shape 字段。
还请注意,这并不意味着 Delphi 会进行任何自动检查 - 您必须自己进行。例如,您可以将所有字段设为私有并仅允许通过属性进行访问。在他们的 getter/setter 方法中,您可以根据需要分配和检查 Shape 字段。这是一个草图:
type
TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
TFigureImpl = record
case Shape: TShapeList of
Rectangle: (Height, Width: Real);
Triangle: (Side1, Side2, Angle: Real);
Circle: (Radius: Real);
Ellipse, Other: ();
end;
TFigure = record
strict private
FImpl: TFigureImpl;
function GetHeight: Real;
procedure SetHeight(const Value: Real);
public
property Shape: TShapeList read FImpl.Shape;
property Height: Real read GetHeight write SetHeight;
// ... more properties
end;
{ TFigure }
function TFigure.GetHeight: Real;
begin
Assert(FImpl.Shape = Rectangle); // Checking shape
Result := FImpl.Height;
end;
procedure TFigure.SetHeight(const Value: Real);
begin
FImpl.Shape := Rectangle; // Setting shape
FImpl.Height := Value;
end;
我将记录分为两种类型,因为否则编译器不会接受需要的可见性说明符。此外,我认为它更具可读性,GExperts 代码格式化程序也不会因此而窒息。 :-)
现在这样的事情会违反断言:
procedure Test;
var
f: TFigure;
begin
f.Height := 10;
Writeln(f.Radius);
end;