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

时间:2014-04-09 06:26:08

标签: delphi attributes rtti

这个有效的代码是否有更新的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?,其中列出了一些报告使用属性的语言元素。此列表中缺少参数的属性。

1 个答案:

答案 0 :(得分: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.