属性の適用

コードの要素に属性を適用するには、次のプロセスを使用します。

  1. 新しい属性を定義するか、または **.**NET Framework から名前空間をインポートして既存の属性を使用します。
  2. 必要なフラグや情報を指定して属性のコンストラクタを呼び出して、記述する要素の直前で属性を初期化します。

コードをコンパイルすると属性がメタデータに格納され、ランタイム リフレクション サービスを通じて共通言語ランタイム、すべてのカスタム ツールやアプリケーションで使用できるようになります。

規則では、属性の名前の最後は Attribute にします。ただし、Visual Basic や C# など、ランタイムを対象とする言語では、属性をフルネームで指定する必要はありません。たとえば、System.ObsoleteAttribute を初期化する場合は、Obsolete と指定するだけで参照できます。

次の例では、System.ObsoleteAttribute をどのように宣言するかを解説しています。System.ObsoleteAttribute は、コードを互換性のために残されているものとして記述しておくために使用します。文字列 "Will be removed in next version" が属性に渡されます。属性が記述されているコードが呼び出された時点で、渡された文字列を示すコンパイラの警告が表示されます。

using System;
public class MainApp
{
    public static void Main()
    {
        //This generates a compile-time warning.
        int MyInt = Add(2,2); 
    }
    //Specify attributes between square brackets in C#.
    //This attribute is applied only to the Add method.
    [Obsolete("Will be removed in next version")]
    public static int Add( int a, int b)
    {
        return (a+b);
    }  
}

[C++]
#using <mscorlib.dll>
using namespace System;
int Add(int a, int b);   
void main(void)
{
    //This generates a compile-time warning.
    int MyInt = Add(2, 2);
    return;
}
//Specify attributes between square brackets in C++.
//This attribute is applied only to the Add method.
[Obsolete("Will be removed in next version ")]
Add( int a, int b)
{
    return (a+b);
}

[Visual Basic]
Imports System 
'Call attributes between < and > in Visual Basic.
Public Module main
    Sub Main()
    'This generates a compile-time warning.
    Dim MyInt as Integer = Add(2,2)
    End Sub
    'Specify attributes between < and > brackets in Visual Basic.
    'This attribute is applied only to the Add method.
    
<Obsolete("Will be removed in next version ")> Function Add(a as Integer, b as Integer) as Integer
        Add = a + b
    End Function
End Module 

アセンブリ レベルでの属性の適用

アセンブリ レベルで属性を適用する場合は、キーワード Assembly を使用します。AssemblyNameAttribute をアセンブリ レベルで適用するコードを次に示します。

using System.Reflection;
[assembly:AssemblyName("MyAssembly")]
[C++]
using namespace System::Reflection;
[assembly:AssemblyName("MyAssembly")]
[Visual Basic]
Imports System.Reflection
<Assembly:AssemblyName("MyAssembly")> 

この属性が適用されると、ファイルのメタデータ部分のアセンブリ マニフェストの中に、文字列 "MyAssembly" が挿入されます。この属性を表示するには、MSIL 逆アセンブラ (Ildasm.exe) を使用するか、または属性を取得するためのプログラムを作成します。

参照   

属性を使用したメタデータの拡張 | 属性に格納されている情報の取得