次の方法で共有


方法 : カスタム属性を取得する

更新 : 2007 年 11 月

Attribute クラスの GetCustomAttribute メソッドまたは GetCustomAttributes メソッドを使用して、カスタム属性を取得できます。

クラスからカスタム属性の単一のインスタンスを取得するには

  1. ソース コードの先頭に Imports ステートメントを追加して、System 名前空間から Attribute クラスをインポートします。

    Imports System.Attribute
    
  2. 属性を取得するプロシージャを作成します。

    Sub RetrieveAttribute()
    
    End Sub
    
  3. プロシージャ内で、Attribute 型の変数と、取得する属性と同じ型の変数を宣言します。

    Dim Attr As Attribute
    Dim CustAttr As CustomAttribute
    
  4. GetType 演算子を使用して、クラスおよび属性の型を GetCustomAttribute メソッドの呼び出しに渡し、Attribute で宣言された変数に戻り値を代入します。

    Attr = GetCustomAttribute(Me.GetType, _
                              GetType(CustomAttribute), False)
    
  5. CType 関数を使用して、属性のデータ型を汎用の属性から取得した型の属性に変換します。カスタム属性型として宣言した変数に結果を代入します。

    CustAttr = CType(Attr, CustomAttribute)
    
  6. 属性が取得されたかどうかを確認します。属性が取得された場合は、属性のフィールド、プロパティ、およびメソッドを使用します。

    If CustAttr Is Nothing Then
        MsgBox("The attribute was not found.")
    Else
        'Get the label and value from the custom attribute.
        MsgBox("The attribute label is: " & CustAttr.Label)
        MsgBox("The attribute value is: " & CustAttr.Value)
    End If
    

    上の例では、カスタム属性を ThisClass クラスに適用するために、RetrieveAttribute プロシージャによって、System.Attribute クラスの GetCustomAttribute メソッドが呼び出されます。GetCustomAttribute は共有メソッドであるため、System.Attribute のインスタンスを最初に作成する必要はありません。CType 関数は、返された属性を System.Attribute 型からカスタム属性型の CustomAttribute に変換します。

参照

処理手順

方法 : 独自の属性を定義する

概念

属性の適用

属性に格納されている情報の取得

参照

GetCustomAttribute

GetCustomAttributes

GetType 演算子

CType 関数

IsNothing 関数

GetAttr 関数

AttributeUsageAttribute