如何在Delphi中获取属性的指针?

huangapple go评论77阅读模式
英文:

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() 获取 TEditTRttiType,然后使用 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');

huangapple
  • 本文由 发表于 2023年7月20日 20:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76729720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定