哪些语言元素可以使用Delphi的属性语言特性进行注释?
Delphi 2010引入了可以添加到类型声明和方法的自定义属性。对于哪些语言元素可以使用自定义属性?
我到目前为止发现的例子包括类声明,字段和方法。 (而且AFAIK通用类不支持自定义属性)。 一些例子显示在this article.它看起来像变量(任何类声明外部)也可以有属性。 基于本文,可以使用属性 >类和记录字段和方法 是否有其他语言元素可以放置属性? 更新:本文指出自定义属性可以放在属性之前: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检索它们。以下是一个快速控制台演示:声明自定义属性:
>枚举 没有找到一种方法来声明一个类的属性的自定义属性。但是自定义属性可以附加到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) 没有办法为“单元”级别或局部变量和过程检索任何类型的RTTI,因此无法检索有关属性的信息。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |