Share via


属性の適用

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

  1. 新しい属性を定義するか、または .NET Framework から名前空間をインポートして既存の属性を使用します。

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

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

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

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

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

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

メソッドへの属性の適用

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

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
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 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();
}

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

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

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

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

参照

参照

属性 (C# および Visual Basic)

概念

属性を使用したメタデータの拡張

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

その他の技術情報

属性付きプログラミングの概念