【问题标题】:variant record in delphidelphi中的变体记录
【发布时间】:2016-09-09 07:22:35
【问题描述】:

我只是想学习变体记录。有人可以解释我如何检查记录中的形状是矩形/三角形等还是任何可用的好例子? 我检查了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;

【问题讨论】:

  • 根据您的需要,类层次结构可能是一个更好的主意。

标签: delphi delphi-2010


【解决方案1】:

你必须像这样为形状添加一个字段:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多