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

时间:2009-10-12 07:44:17

标签: delphi field delphi-2010 rtti

请考虑以下事项:

TFieldType = class
  fValue: string;
end;

TMainClass = class
private
  Ffield: TFieldType;
public
  function GetValue: string;
end;

在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
    );

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

1 个答案:

答案 0 :(得分:6)

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

vField.GetValue(self);

为了更好地理解Rtti,请阅读Robert Love的remarkable articles about RTTI。对于这个问题,这个问题特别关于Properties and Fields