是否可以在Delphi方法参数上使用Attributes?

mjn*_*mjn 13 delphi attributes rtti

这是有效的代码与较新的Delphi版本?

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

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

查看我之前的问题使用Delphi的属性语言功能可以注释哪些语言元素?,列出了一些已报告使用属性的语言元素.此列表中缺少参数的属性.

Ste*_*nke 21

是的你可以:

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.
Run Code Online (Sandbox Code Playgroud)

  • +1 - 这些属性很强大但没有很好地记录:( (3认同)