如何使用RTTI在Delphi中获取访问字段?

boo*_*tic 6 delphi field rtti delphi-2010

考虑以下:

TFieldType = class
  fValue: string;
end;

TMainClass = class
private
  Ffield: TFieldType;
public
  function GetValue: string;
end;
Run Code Online (Sandbox Code Playgroud)

在TMainClass.GetValue中,我试着获取TMainClass字段的值:

function TMainClass.GetValue;
begin
  vCtx := TRTTIContext.Create;
  vType := vCtx.GetType(Self.ClassInfo);
  for vField in vType.GetFields do
    vField.GetValue(
        //Here's the trouble, because i don't know how to get the instance
    );
Run Code Online (Sandbox Code Playgroud)

可能有另一种获取字段值的方法,这些字段是另一个类的实例?

Hei*_* Z. 6

您必须将实例作为GetValue的参数传递

vField.GetValue(self);

为了更好地理解Rtti,请阅读Robert Love 撰写的关于RTTI非凡文章.对于这个问题,特别是关于Properties和Fields的这个问题.