Is it possible to use Attributes on Delphi method arguments?

前端 未结 1 436
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 16:52

Is this valid code with newer Delphi versions?

// handle HTTP request \"example.com/products?ProductID=123\"
procedure TMyRESTfulService.HandleRequest([QueryPara         


        
相关标签:
1条回答
  • 2021-02-05 17:28

    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.
    
    0 讨论(0)
提交回复
热议问题