属性を適用する

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

  1. 新しい属性を定義するか、既存の .NET 属性を使用します。

  2. 属性をコード要素の直前に記述することで、その要素に属性を適用します。

    各言語には独自の属性構文があります。 C++ および C# では、属性が角かっこで囲まれ、要素とは空白で区切られます。属性と要素の間には改行を入れることもできます。 Visual Basic では、属性が山かっこで囲まれ、同じ論理行に記述されている必要があります。改行が必要な場合は、行連結文字を使用できます。

  3. 属性に、位置指定パラメーターと名前付きパラメーターを指定します。

    "位置指定" パラメーターは必須で、名前付きパラメーターの前に指定する必要があり、1 つの属性のコンストラクターのパラメーターに対応します。 "名前付き" パラメーターは省略可能で、属性の読み取り/書き込みプロパティに対応します。 C++ と C# では、オプションのパラメーターごとに name=value を指定します。name はプロパティの名前です。 Visual Basic では、name:=value を指定します。

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

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

メソッドに属性を適用する

次のコードからは、コードに非推奨を指定する System.ObsoleteAttribute の使用方法を確認できます。 文字列 "Will be removed in next version" が属性に渡されます。 属性が記述されているコードが呼び出された時点で、渡された文字列を示すコンパイラの警告が表示されます。

public ref class Example
{
    // Specify attributes between square brackets in C#.
    // This attribute is applied only to the Add method.
public:
    [Obsolete("Will be removed in next version.")]
    static int Add(int a, int b)
    {
        return (a + b);
    }
};

ref class Test
{
public:
    static void Main()
    {
        // This generates a compile-time warning.
        int i = Example::Add(2, 2);
    }
};

int main()
{
    Test::Main();
}
public class Example
{
    // 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);
    }
}

class Test
{
    public static void Main()
    {
        // This generates a compile-time warning.
        int i = Example.Add(2, 2);
    }
}
Public Class Example
    ' Specify attributes between square brackets in C#.
    ' This attribute is applied only to the Add method.
    <Obsolete("Will be removed in next version.")>
    Public Shared Function Add(a As Integer, b As Integer) As Integer
        Return a + b
    End Function
End Class

Class Test
    Public Shared Sub Main()
        ' This generates a compile-time warning.
        Dim i As Integer = Example.Add(2, 2)
    End Sub
End Class

アセンブリ レベルで属性を適用する

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

using namespace System::Reflection;
[assembly:AssemblyTitle("My Assembly")];
using System.Reflection;
[assembly:AssemblyTitle("My Assembly")]
Imports System.Reflection
<Assembly: AssemblyTitle("My Assembly")>

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

関連項目