Is it possible to use Attributes on Delphi method arguments?

為{幸葍}努か 提交于 2021-02-06 08:57:13

问题


Is this valid code with newer Delphi versions?

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

In this example, the argument "ProductID" is attributed with [QueryParam]. If this is valid code in Delphi, there must also be a way to write RTTI based code to find the attributed argument type information.

See my previous question Which language elements can be annotated using attributes language feature of Delphi?, which lists some language elements which have reported to work with attributes. Attributes on arguments were missing on this list.


回答1:


Yes you can:

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.


来源:https://stackoverflow.com/questions/22954446/is-it-possible-to-use-attributes-on-delphi-method-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!