Delphi – 包含变体部分的记录

前端之家收集整理的这篇文章主要介绍了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;
原文链接:https://www.f2er.com/delphi/239256.html

猜你在找的Delphi相关文章