delphi 如何使用rtti访问类属性?

u3r8eeie  于 2024-01-07  发布在  其他
关注(0)|答案(2)|浏览(100)

有没有可能用rtti来获取一个类的属性?下面的代码有什么问题?

  1. ...
  2. type
  3. TTest = class
  4. private
  5. class function GetCP: string; static;
  6. public
  7. class property CP: string read GetCP;
  8. end;
  9. class function TTest.GetCP: string;
  10. begin
  11. Result := 'ABC';
  12. end;
  13. ...
  14. procedure TForm1.Button5Click(Sender: TObject);
  15. var
  16. oTest: TTest;
  17. oType: TRttiType;
  18. begin
  19. oTest := TTest.Create;
  20. try
  21. oType := TRttiContext.Create.GetType(oTest.ClassType);
  22. ShowMessage(Length(oType.GetProperties).ToString); // oType.GetProperties = nil !!!
  23. finally
  24. oTest.Free;
  25. end;
  26. end;

字符串
最好的问候,布兰科

wkyowqbh

wkyowqbh1#

无法通过RTTI访问类属性。

zd287kbt

zd287kbt2#

我用这个函数获取类属性:

  1. function GetClassInfo(obj: TObject): TDictionary<string, TTypeKind>;
  2. var
  3. context: TRttiContext;
  4. rType: TRttiType;
  5. field: TRttiProperty;
  6. begin
  7. context := TRttiContext.Create;
  8. try
  9. rType := context.GetType(obj.ClassType);
  10. Result := TDictionary<string, TTypeKind>.create;
  11. for field in rType.GetProperties do
  12. if field <> nil then
  13. Result.Add(Field.Name,Field.GetValue(obj).Kind);
  14. finally
  15. context.Free;
  16. end;
  17. end;

字符串

展开查看全部

相关问题