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

7
请看下面的内容:

考虑以下情况:

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个回答

7
您需要将实例作为GetValue的参数传递,如下所示:
vField.GetValue(self);
如果想更好地理解Rtti,请阅读Robert Love关于RTTI的卓越文章。对于这个问题,特别是关于属性和字段的文章。

非常感谢,我已经阅读了这些文章,但似乎不是很仔细。你的答案解决了我的问题。 - boombastic
第二个链接与第一个一样... 是粘贴错误了吗?我想他的意思是粘贴这个链接:http://robstechcorner.blogspot.com/2009/09/exploring-trttimember-descendants-in.html - oOo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接