Delphi の属性言語機能を使用して注釈を付けることができる言語要素はどれですか? 質問する

Delphi の属性言語機能を使用して注釈を付けることができる言語要素はどれですか? 質問する

Delphi 2010 では、型宣言とメソッドに追加できるカスタム属性が導入されました。カスタム属性はどの言語要素に使用できますか?

これまでに見つけた例には、クラス宣言、フィールド、メソッドが含まれています。(私の知る限り、ジェネリック クラスはカスタム属性をサポートしていません)。

いくつかの例を以下に示す。この記事変数 (クラス宣言の外部) にも属性を持たせることができるようです。

この記事に基づいて、属性は次の目的で使用できます。

  • クラスとレコードのフィールドとメソッド
  • メソッドパラメータ
  • プロパティ
  • 非ローカル列挙宣言
  • 非ローカル変数宣言

属性を配置できる他の言語要素はありますか?


更新: この記事では、カスタム属性をプロパティの前に配置できることが示されています。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);

ベストアンサー1

興味深い質問ですね!属性を宣言することができますほとんど何でも問題は、RTTI を使用してそれらを取得することです。以下は、カスタム属性を宣言する簡単なコンソール デモです。

  • 列挙型
  • 関数タイプ
  • 手順の種類
  • メソッドタイプ ( of object)
  • エイリアス型
  • レコードタイプ
  • クラスタイプ
  • クラス内部のレコード型
  • レコードフィールド
  • 記録方法
  • クラスインスタンスフィールド
  • クラスclassフィールド ( class var)
  • クラスメソッド
  • グローバル変数
  • グローバル機能
  • ローカル変数

クラスのカスタム属性を宣言する方法が見つかりませんでした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 を取得する方法はないため、属性に関する情報を取得する方法はありません。

おすすめ記事