英文:
How do I get a pointer to a property in Delphi?
问题
我想要一个指向 TEdit.Text 的指针,但不管我怎么表达,Delphi都坚持说 E2036 变量需要。
英文:
I'd like a pointer to TEdit.Text, but no matter how I express it Delphi insists that E2036 Variable required.
答案1
得分: 6
没有指向属性的指针,尤其是像 TEdit.Text 这样的属性,它使用 getter/setter 方法而不是由物理变量支持。
如果需要动态访问属性,请使用 RTTI。
使用旧的 System.TypInfo 单元中的 RTTI,您可以使用 GetPropInfo() 获取 TEdit.Text 属性的 PPropInfo 指针,然后使用 GetStrProp() 和 SetStrProp() 函数来读取/写入其值。
uses
..., TypInfo;
var
TextProp: PPropInfo;
S: string;
TextProp := GetPropInfo(Edit1.ClassType, 'Text');
...
S := GetStrProp(Edit1, TextProp);
SetStrProp(Edit1, TextProp, S + ' hello');
另外,使用较新的 System.Rtti 单元中的增强型 RTTI,您可以使用 TRttiContext.GetType() 获取 TEdit 的 TRttiType,然后使用 TRttiType.GetProperty() 获取其 Text 属性的 TRttiProperty,然后使用 TRttiProperty.GetValue() 和 TRttiProperty.SetValue() 读取/写入其值。
uses
..., System.Rtti;
var
Ctx: TRttiContext;
TextProp: TRttiProperty;
S: string;
TextProp := Ctx.GetType(Edit1.ClassType).GetProperty('Text');
...
S := TextProp.GetValue(Edit1);
TextProp.SetValue(Edit1, S + ' hello');
英文:
There is no such thing as a pointer to a property. Especially a property like TEdit.Text, which uses getter/setter methods instead of being backed by a physical variable.
If you need to access a property dynamically, use RTTI for that purpose.
Using RTTI from the older System.TypInfo unit, you can use GetPropInfo() to get a PPropInfo pointer for the TEdit.Text property, and then use the GetStrProp() and SetStrProp() functions to read/write its value.
uses
..., TypInfo;
var
TextProp: PPropInfo;
S: string;
TextProp := GetPropInfo(Edit1.ClassType, 'Text');
...
S := GetStrProp(Edit1, TextProp);
SetStrProp(Edit1, TextProp, S + ' hello');
Alternatively, using enhanced RTTI from the newer System.Rtti unit, you can use TRttiContext.GetType() to get a TRttiType for TEdit, and then use TRttiType.GetProperty() to get a TRttiProperty for its Text property, and then use TRttiProperty.GetValue() and TRttiProperty.SetValue() to read/write its value.
uses
..., System.Rtti;
var
Ctx: TRttiContext;
TextProp: TRttiProperty;
S: string;
TextProp := Ctx.GetType(Edit1.ClassType).GetProperty('Text');
...
S := TextProp.GetValue(Edit1);
TextProp.SetValue(Edit1, S + ' hello');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论