gpt4 book ai didi

Delphi - 带有变体部分的记录

转载 作者:行者123 更新时间:2023-12-03 14:59:40 24 4
gpt4 key购买 nike

我想要一个具有“多态”行为的记录(结构)。它将在所有情况下使用多个字段,并且我只想在需要时使用其他字段。我知道我可以通过记录中声明的变体部分来完成此操作。我不知道是否有可能在设计时我只能访问我需要的元素。更具体地说,请看下面的示例

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 - 带有变体部分的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7901805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com