德尔福的变种记录

时间:2016-09-09 07:22:36

标签: delphi delphi-2010

我只是想学习变体记录。有人可以解释我如何在记录中检查形状是否是矩形/三角形等,或者是否有可用的实施例? 我查了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;

1 个答案:

答案 0 :(得分:4)

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

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;