加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Delphi – 包含变体部分的记录

发布时间:2020-12-15 04:08:01 所属栏目:大数据 来源:网络整理
导读:我想要一个带有’多态’组合的记录(结构).在所有情况下都会使用几个字段,我只想在需要时才使用其他字段.我知道我可以通过记录中声明的变体部分来实现这一点.我不知道是否有可能在设计时我只能访问我需要的元素.更具体地说,请看下面的示例 program consapp;{$
我想要一个带有’多态’组合的记录(结构).在所有情况下都会使用几个字段,我只想在需要时才使用其他字段.我知道我可以通过记录中声明的变体部分来实现这一点.我不知道是否有可能在设计时我只能访问我需要的元素.更具体地说,请看下面的示例
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读