如何使用rtti访问类属性?

问题描述 投票:0回答:2

是否可以通过 rtti 获得类属性?下面的代码有什么问题吗?

...
type
  TTest = class
  private
    class function GetCP: string; static;
  public
    class property CP: string read GetCP;
  end;

class function TTest.GetCP: string;
begin
  Result := 'ABC';
end;
...
procedure TForm1.Button5Click(Sender: TObject);
var
  oTest: TTest;
  oType: TRttiType;
begin
  oTest := TTest.Create;
  try
    oType := TRttiContext.Create.GetType(oTest.ClassType);
    ShowMessage(Length(oType.GetProperties).ToString);  // oType.GetProperties = nil !!! 
  finally
    oTest.Free;
  end;
end;  

TIA 致以最诚挚的问候, 布兰科

delphi rtti
2个回答
5
投票

无法通过 RTTI 访问类属性。


0
投票

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

function GetClassInfo(obj: TObject): TDictionary<string, TTypeKind>;
var
  context: TRttiContext;
  rType: TRttiType;
  field: TRttiProperty;
begin
  context := TRttiContext.Create;
  try
    rType := context.GetType(obj.ClassType);
    Result := TDictionary<string, TTypeKind>.create;

    for field in rType.GetProperties do
      if field <> nil then
        Result.Add(Field.Name,Field.GetValue(obj).Kind);
  finally
    context.Free;
  end;
end;
© www.soinside.com 2019 - 2024. All rights reserved.