gpt4 book ai didi

delphi - 是否可以在 Delphi 方法参数上使用属性?

转载 作者:行者123 更新时间:2023-12-03 14:37:32 26 4
gpt4 key购买 nike

此代码对于较新的 Delphi 版本有效吗?

// handle HTTP request "example.com/products?ProductID=123"
procedure TMyRESTfulService.HandleRequest([QueryParam] ProductID: string);

在此示例中,参数“ProductID”的属性为[QueryParam]。如果这是 Delphi 中的有效代码,则还必须有一种方法来编写基于 RTTI 的代码来查找属性参数类型信息。

请参阅我之前的问题 Which language elements can be annotated using attributes language feature of Delphi? ,其中列出了一些已报告可与属性一起使用的语言元素。此列表中缺少参数的属性。

最佳答案

是的,你可以:

program Project1;

{$APPTYPE CONSOLE}

uses
Rtti,
SysUtils;

type
QueryParamAttribute = class(TCustomAttribute)
end;

TMyRESTfulService = class
procedure HandleRequest([QueryParam] ProductID: string);
end;

procedure TMyRESTfulService.HandleRequest(ProductID: string);
begin

end;

var
ctx: TRttiContext;
t: TRttiType;
m: TRttiMethod;
p: TRttiParameter;
a: TCustomAttribute;
begin
try
t := ctx.GetType(TMyRESTfulService);
m := t.GetMethod('HandleRequest');
for p in m.GetParameters do
for a in p.GetAttributes do
Writeln('Attribute "', a.ClassName, '" found on parameter "', p.Name, '"');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.

关于delphi - 是否可以在 Delphi 方法参数上使用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22954446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com