32

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);
4

1 回答 1

27

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

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

找不到为property类的 a 声明自定义属性的方法。但是可以将自定义属性附加到 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,因此无法检索有关属性的信息。

于 2011-05-25T06:10:15.727 回答