delphi 中的变体记录

variant record in delphi

我只是想学习变体 records.Can 有人解释我如何检查记录中的形状是否是 rectangle/Triangle 等或任何可用的实施的好例子? 我检查了 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;

注意 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;