加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 05:22:14 所属栏目:大数据 来源:网络整理
导读:Delphi 2010引入了可以添加到类型声明和方法的自定义属性。对于哪些语言元素可以使用自定义属性? 我到目前为止发现的例子包括类声明,字段和方法。 (而且AFAIK通用类不支持自定义属性)。 一些例子显示在this article.它看起来像变量(任何类声明外部)也可以
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,因此无法检索有关属性的信息。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读