【发布时间】:2019-08-02 18:32:47
【问题描述】:
我已经声明了以下自定义属性
unit SpecialAttribute;
interface
type
TSpecialAttribute = class(TCustomAttribute)
procedure SetValue(aValue: String);
public
FValue: String;
property Value: String read FValue write SetValue;
constructor Create(const AValue: String);
end;
implementation
{ TSpecialAttribute }
constructor TSpecialAttribute.Create(const AValue: String);
begin
FValue := aValue;
end;
procedure TSpecialAttribute.SetValue(aValue: String);
begin
FValue := aValue;
end;
end.
并用于装饰如下界面:
unit ITestInterface;
interface
uses
SpecialAttribute;
type
ITestIntf = interface(IInvokable)
[TSpecialAttribute('IntfAttribute')]
procedure Test;
end;
implementation
end.
我正在尝试使用 RTTI 从接口获取属性:
unit Unit17;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
SpecialAttribute,ITestInterface;
type
TTestClass = class(TInterfacedObject, ITestIntf)
[TSpecialAttribute('TestClass')]
procedure Test;
end;
TForm17 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form17: TForm17;
implementation
uses
Rtti;
{$R *.dfm}
procedure TForm17.FormCreate(Sender: TObject);
var
LContext: TRttiContext;
LType: TRttiType;
LAttr: TCustomAttribute;
begin
try
LContext := TRttiContext.Create;
LType := LContext.GetType(TypeInfo(ITestIntf));
for LAttr in LType.GetAttributes() do
if LAttr is TSpecialAttribute then
Memo1.Lines.Add(TSpecialAttribute(LAttr).FValue)
else
Memo1.Lines.Add(LAttr.ClassName);
finally
LContext.Free;
end;
end;
end.
在自定义属性构造函数上设置断点时,代码永远不会停止。如何从界面获取属性?
【问题讨论】:
-
您将属性应用于接口和实现类的方法,而不是接口/类本身,但您正在查询接口本身的属性。因此,您的备忘录中当然不会出现任何内容,因为您正在查询错误级别的属性。您需要先使用
TRttiType.Get(Declared)Methods()枚举接口/对象的方法,然后您可以使用TRttiMethod.GetAttributes()查询每个方法的属性。
标签: delphi rtti delphi-10.1-berlin