哪些语言元素可以使用Delphi的属性语言特性进行注释



Delphi 2010引入了可以添加到类型声明和方法中的自定义属性。自定义属性可以用于哪些语言元素?

到目前为止,我发现的例子包括类声明、字段和方法。(并且AFAIK泛型类不支持自定义属性)。

本文展示了一些示例。看起来变量(任何类声明的外部)也可以具有属性。

基于本文,属性可以用于

  • 类和记录字段及方法
  • 方法参数
  • 特性
  • 非局部枚举声明
  • 非局部变量声明

是否存在可以放置属性的其他语言元素?


更新:本文指出自定义属性可以放在属性之前:http://francois-piette.blogspot.de/2013/01/using-custom-attribute-for-data.html

它包含以下代码示例:

type
  TConfig = class(TComponent)
  public
    [PersistAs('Config', 'Version', '1.0')]
    Version : String;
    [PersistAs('Config', 'Description', 'No description')]
    Description : String;
    FTest : Integer;
    // No attribute => not persistent
    Count : Integer;
    [PersistAs('Config', 'Test', '0')]
    property Test : Integer read FTest write FTest;
  end;

我想还有一种方法可以读取方法参数上的属性,比如

procedure Request([FormParam] AUsername: string; [FormParam] APassword: string);

有趣的问题!您几乎可以在上声明任何东西的属性,问题是使用RTTI检索它们。以下是为声明自定义属性的快速控制台演示

  • 枚举
  • 函数类型
  • 程序类型
  • 方法类型(of object
  • 别名类型
  • 记录类型
  • 类别类型
  • 类内部的记录类型
  • 记录字段
  • 记录方法
  • 类实例字段
  • 类别class字段(class var
  • Class方法
  • 全局变量
  • 全局函数
  • 局部变量

找不到为类的property声明自定义属性的方法。但是自定义属性可以附加到getter或setter方法。

代码,故事在代码后继续:

program Project25;
{$APPTYPE CONSOLE}
uses
  Rtti;
type
  TestAttribute = class(TCustomAttribute);
  [TestAttribute] TEnum = (first, second, third);
  [TestAttribute] TFunc = function: Integer;
  [TestAttribute] TEvent = procedure of object;
  [TestAttribute] AliasInteger = Integer;
  [TestAttribute] ARecord = record
    x:Integer;
    [TestAttribute] RecordField: Integer;
    [TestAttribute] procedure DummyProc;
  end;
  [TestAttribute] AClass = class
  strict private
    type [TestAttribute] InnerType = record y:Integer; end;
  private
    [TestAttribute]
    function GetTest: Integer;
  public
    [TestAttribute] x: Integer;
    [TestAttribute] class var z: Integer;
    // Can't find a way to declare attribute for property!
    property Test:Integer read GetTest;
    [TestAttribute] class function ClassFuncTest:Integer;
  end;
var [TestAttribute] GlobalVar: Integer;
[TestAttribute]
procedure GlobalFunction;
var [TestAttribute] LocalVar: Integer;
begin
end;
{ ARecord }
procedure ARecord.DummyProc;
begin
end;
{ AClass }
class function AClass.ClassFuncTest: Integer;
begin
end;
function AClass.GetTest: Integer;
begin
end;
begin
end.

问题在于检索那些自定义属性。查看rtti.pas单元,可以检索以下属性的自定义属性:

  • 记录类型(TRttiRecordType
  • 实例类型(TRttiInstanceType
  • 方法类型(TRttiMethodType
  • 指针类型(TRttiPointerType)-这是用来做什么的
  • 程序类型(TRttiProcedureType

无法检索"单元"级或局部变量和过程的任何类型的RTTI,因此无法检索有关属性的信息。

最新更新