是否可以在Delphi方法参数上使用属性? [英] Is it possible to use Attributes on Delphi method arguments?

查看:66
本文介绍了是否可以在Delphi方法参数上使用属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此有效代码是否具有较新的Delphi版本?

Is this valid code with newer Delphi versions?

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

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

In this example, the argument "ProductID" is attributed with [QueryParam]. If this is valid code in Delp 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.

推荐答案

是的,您可以:

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方法参数上使用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆