gpt4 book ai didi

delphi - Delphi 2010 RTTI和Pointer字段

转载 作者:行者123 更新时间:2023-12-03 19:45:13 25 4
gpt4 key购买 nike

我在以下代码中遇到问题:

program Project4;

{$APPTYPE CONSOLE}

uses
SysUtils, RTTI;

type

TRecord2 = record
c: integer;
d: integer;
end;

TClass1 = class
public
FRecord: record
a: integer;
b: integer;
end;
FRecord2: TRecord2;
FPointRecord3: ^TRecord2;

constructor Create;
end;

constructor TClass1.Create;
begin
FPointRecord3 := nil;
end;

var
lContext: TRttiContext;
lType: TRttiType;
lFields: TArray<TRttiField>;
i: integer;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
lContext := TRttiContext.Create;

lType := lContext.GetType(TClass1);

lFields := lType.GetFields;
for i := 0 to Length(lFields) - 1 do
begin
write('Name = '+lFields[i].Name+', ');
if lFields[i].FieldType <> nil then
writeln('Type = '+lFields[i].FieldType.ToString)
else
writeln('Type = NIL!!!');
end;
lContext.Free;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.


输出:

Name = FRecord, Type = :TClass1.:1
Name = FRecord2, Type = TRecord2
Name = FPointRecord3, Type = NIL!!!


lFields [i] .FieldType返回NIL
如何使用RTTI获取类型指针类型字段?

最佳答案

它不会创建任何类型信息,因为您从未为它定义类型。您只需将字段定义为指向已定义类型的指针,因此编译器会即时为其创建一个临时的“类型”,但没有RTTI。

如果您希望它正常工作,请按照以下步骤操作:

type

TRecord2 = record
c: integer;
d: integer;
end;
PRecord2 = ^TRecord2;

TClass1 = class
public
FRecord: record
a: integer;
b: integer;
end;
FRecord2: TRecord2;
FPointRecord3: PRecord2;

constructor Create;
end;

关于delphi - Delphi 2010 RTTI和Pointer字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3086272/

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