gpt4 book ai didi

delphi - delphi中的变体记录

转载 作者:行者123 更新时间:2023-12-03 15:24:50 25 4
gpt4 key购买 nike

我只是想学习变体记录。有人可以解释一下我如何检查记录中的形状是否是矩形/三角形等,或者有任何可用的实现的好例子吗?我查过variants record here但没有可用的实现..

type
TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
TFigure = record
case TShapeList of
Rectangle: (Height, Width: Real);
Triangle: (Side1, Side2, Angle: Real);
Circle: (Radius: Real);
Ellipse, Other: ();
end;

最佳答案

您必须为形状添加一个字段,如下所示:

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;

注意形状字段。

另请注意,这并不意味着 Delphi 会进行任何自动检查 - 您必须自己执行此操作。例如,您可以将所有字段设为私有(private)并仅允许通过属性进行访问。在它们的 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;

关于delphi - delphi中的变体记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39405988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com