微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

哪些语言元素可以使用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检索它们。以下是一个快速控制台演示:声明自定义属性

>枚举
>功能类型
>过程类型
>方法类型(对象)
>别名类型
>记录类型
>类类型
>类的内部的记录类型
>记录字段
>记录方法
>类实例字段
>类类字段(class var)
>类方法
>全局变量
>全局功能
>局部变量

没有找到一种方法来声明一个类的属性自定义属性。但是自定义属性可以附加到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,因此无法检索有关属性的信息。

原文地址:https://www.jb51.cc/delphi/103654.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐