Delphi - 包含变体部分的记录

RBA*_*RBA 6 delphi record delphi-2009

我想要一个带有'多态'组合的记录(结构).在所有情况下都会使用几个字段,我只想在需要时才使用其他字段.我知道我可以通过记录中声明的变体部分来实现这一点.我不知道是否有可能在设计时我只能访问我需要的元素.更具体地说,请看下面的示例

program consapp;

{$APPTYPE CONSOLE}

uses
  ExceptionLog,
  SysUtils;

type
  a = record
   b : integer;
   case isEnabled : boolean of
    true : (c:Integer);
    false : (d:String[50]);
  end;


var test:a;

begin
 test.b:=1;
 test.isEnabled := False;
 test.c := 3; //because isenabled is false, I want that the c element to be unavailable to the coder, and to access only the d element. 
 Writeln(test.c);
 readln;
end.
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Dav*_*nan 8

无论标签的值如何,都可以随时访问变体记录中的所有变体字段.

为了实现可访问性控制,您需要使用属性并进行运行时检查以控制可访问性.

type
  TMyRecord = record
  strict private
    FIsEnabled: Boolean;
    FInt: Integer;
    FStr: string;
    // ... declare the property getters and settings here
  public
    property IsEnabled: Boolean read FIsEnabled write FIsEnabled;
    property Int: Integer read GetInt write SetInt;
    property Str: string read GetString write SetString;
  end;
...
function TMyRecord.GetInt: Integer;
begin
  if IsEnabled then
    Result := FInt
  else
    raise EValueNotAvailable.Create('blah blah');
end;
Run Code Online (Sandbox Code Playgroud)

  • 这是完全正确的,但在这种情况下,我宁愿使用类而不是记录.它将允许添加继承功能,这在这里是有意义的(例如,IsEnable属性通常在父级别处理,并在子级之间共享). (2认同)