Delphi – 包含变体部分的记录

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

这可能吗?

解决方法

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

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

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;

相关文章

 从网上看到《Delphi API HOOK完全说明》这篇文章,基本上都...
  从网上看到《Delphi API HOOK完全说明》这篇文章,基本上...
ffmpeg 是一套强大的开源的多媒体库 一般都是用 c/c+&#x...
32位CPU所含有的寄存器有:4个数据寄存器(EAX、EBX、ECX和ED...
1 mov dst, src dst是目的操作数,src是源操作数,指令实现的...