属性の対象の明確化 (C# プログラミング ガイド)

更新 : 2007 年 11 月

場合によっては、属性の対象 (属性が適用されるエンティティ) が明確でないことがあります。たとえば、次に示すメソッドの宣言では、SomeAttr 属性は、メソッド自体にもメソッドの戻り値にも適用される可能性があります。

public class SomeAttr : System.Attribute { }

[SomeAttr]
int Method()
{
    return 0;
}

このような状況は、マーシャリング時によく発生します。あいまいさを排除するため、C# では宣言の種類ごとに既定の対象が決められています。属性の対象を明示的に指定することで、既定の対象をオーバーライドできます。

// default: applies to method
[SomeAttr]
int Method1() { return 0; } 

// applies to method
[method: SomeAttr]
int Method2() { return 0; } 

// applies to return value
[return: SomeAttr]
int Method3() { return 0; } 

上の例では、SomeAttr が実際に適用される対象と、SomeAttr に対して定義されている有効な対象は無関係であることに注意してください。つまり、これが戻り値だけに適用される属性として定義されている場合でも、対象を示す return を指定する必要があります。コンパイラには、AttributeUsage の情報を使用して属性の対象のあいまいさを解決する機能はありません。詳細については、「AttributeUsage (C# プログラミング ガイド)」を参照してください。

属性対象指定の構文は、次のとおりです。

[target : attribute-list]

パラメータ

  • target
    assembly、field、event、method、module、param、property、return、type のいずれかです。

  • attribute-list
    適用する属性のリストです。

次の表は、属性を指定できるすべての宣言をまとめたものです。宣言ごとに、その宣言の属性の対象を右側の列に示してあります。太字で示した対象が既定値です。

宣言

指定できる対象

assembly

assembly

module

module

class

type

struct

type

interface

type

enum

type

delegate

type、return

method

method、return

parameter

param

Field

field

property - indexer

property

property - get accessor

method、return

property - set accessor

method、param、return

event - field

event、field、method

event - property

event、property

event - add

method、param

event - remove

method、param

assembly レベルと module レベルの属性には既定の対象がありません。詳細については、「グローバル属性」を参照してください。

使用例

using System.Runtime.InteropServices;
[Guid("12345678-1234-1234-1234-123456789abc"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ISampleInterface
{
    [DispId(17)]  // set the DISPID of the method
    [return: MarshalAs(UnmanagedType.Interface)]  // set the marshaling on the return type
    object DoWork();
}

参照

概念

C# プログラミング ガイド

参照

リフレクション (C# プログラミング ガイド)

属性 (C# プログラミング ガイド)

属性の使用 (C# プログラミング ガイド)

カスタム属性の作成 (C# プログラミング ガイド)

リフレクションによる属性へのアクセス (C# プログラミング ガイド)

System.Reflection

Attribute