如何在运行时转换 class 的 属性?

How to transform a property of a class at runtime?

我有一个class

type
  myClass = class
  private 
    FId: Integer;
  public
    function GetId: Integer;
    property Id: Integer read FId;
  end;

现在,我想在运行时交换 Id 属性 getter 以使用 GetId 方法而不是 FId 字段。我可以使用RTTI或其他方法来实现吗?

您不能在运行时用 getter 方法替换 属性 reader 字段。但是你可以这样写:

type
  TMyClass = class
  private
    FId: Integer;
    function GetId: Integer;
  public
    property Id: Integer read GetId;
  end;

implementation

function TMyClass.GetId: Integer;
begin
  if IWantToReturnField then
    Result := FId
  else
    Result := FId + SomeExtraStuff;
end;