How to modify delphi property Getter/Setter with RTTI?

末鹿安然 提交于 2019-12-04 03:59:02

问题


I would like to replace the getter/setter for properties using RTTI.

I know that you can access the getter setter with TPropInfo.SetProc/GetProc and I know that these fields points to different data depending if the property uses virtual methods, direct field access or static methods.

I'm interesting on replacing propertiy setters/getters that point to virtual methods with custom virtual methods.

TRttiInstanceProperty(RttiProperty).PropInfo^.SetProc := ? // SomeOtherInstance.Setter
TRttiInstanceProperty(RttiProperty).PropInfo^.GetProc := ? // SomeOtherInstance.Getter

回答1:


You cannot achieve your goal this way because your question is based on a mis-conception. The RTTI information gives you the getter/setter as specified in the compiled code. But when you access a property, the RTTI information is not consulted. Rather the getter/setter is called directly.

To illustrate, consider the following canonical read only property:

property Count: Integer read GetCount;

You can query this property with RTTI to find out the method that implements the getter. However when you write this in code:

Writeln(Obj.Count);

the compiler translates this to:

Writeln(Obj.GetCount);

and compiles that. At the call site the RTTI information is never consulted. So any attempt to modify the RTTI information will have no impact on code that accesses the property.

You need to find a different solution to your problem.



来源:https://stackoverflow.com/questions/21749715/how-to-modify-delphi-property-getter-setter-with-rtti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!