MemberInfo.GetCustomAttributes メソッド

定義

派生クラスでオーバーライドされた場合、このメンバーに適用されているカスタム属性を返します。

オーバーロード

GetCustomAttributes(Boolean)

派生クラスでオーバーライドされた場合、このメンバーに適用されているすべてのカスタム属性の配列を返します。

GetCustomAttributes(Type, Boolean)

派生クラスでオーバーライドされた場合は、このメンバーに適用され、Type によって識別されるカスタム属性の配列を返します。

GetCustomAttributes(Boolean)

Source:
MemberInfo.cs
Source:
MemberInfo.cs
Source:
MemberInfo.cs

派生クラスでオーバーライドされた場合、このメンバーに適用されているすべてのカスタム属性の配列を返します。

public:
 abstract cli::array <System::Object ^> ^ GetCustomAttributes(bool inherit);
public abstract object[] GetCustomAttributes (bool inherit);
abstract member GetCustomAttributes : bool -> obj[]
Public MustOverride Function GetCustomAttributes (inherit As Boolean) As Object()

パラメーター

inherit
Boolean

このメンバーの継承チェーンを検索して属性を見つける場合は true。それ以外の場合は false。 プロパティとイベントの場合、このパラメーターは無視されます。

戻り値

Object[]

このメンバーに適用されているすべてのカスタム属性が格納されている配列。定義されている属性がない場合は要素がゼロの配列。

実装

例外

このメンバーは、リフレクションのみのコンテキストに読み込まれる型に属します。 「方法:リフレクションのみのコンテキストにアセンブリを読み込む」を参照してください。

カスタム属性の型を読み込むことができませんでした。

次の例では、カスタム属性を定義し、 属性 MyClass.MyMethodを に関連付け、実行時に 属性を取得し、結果を表示します。

using namespace System;
using namespace System::Reflection;

// Define a custom attribute with one named parameter.

[AttributeUsage(AttributeTargets::All)]
public ref class MyAttribute: public Attribute
{
private:
   String^ myName;

public:
   MyAttribute( String^ name )
   {
      myName = name;
   }

   property String^ Name 
   {
      String^ get()
      {
         return myName;
      }
   }
};

// Define a class that has the custom attribute associated with one of its members.
public ref class MyClass1
{
public:

   [MyAttribute("This is an example attribute.")]
   void MyMethod( int i )
   {
      return;
   }
};

int main()
{
   try
   {
      // Get the type of MyClass1.
      Type^ myType = MyClass1::typeid;

      // Get the members associated with MyClass1.
      array<MemberInfo^>^myMembers = myType->GetMembers();

      // Display the attributes for each of the members of MyClass1.
      for ( int i = 0; i < myMembers->Length; i++ )
      {
         array<Object^>^myAttributes = myMembers[ i ]->GetCustomAttributes( true );
         if ( myAttributes->Length > 0 )
         {
            Console::WriteLine( "\nThe attributes for the member {0} are: \n", myMembers[ i ] );
            for ( int j = 0; j < myAttributes->Length; j++ )
               Console::WriteLine( "The type of the attribute is {0}.", myAttributes[ j ] );
         }
      }
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "An exception occurred: {0}", e->Message );
   }
}
using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name
    {
        get
        {
            return myName;
        }
    }
}

// Define a class that has the custom attribute associated with one of its members.
public class MyClass1
{
    [MyAttribute("This is an example attribute.")]
    public void MyMethod(int i)
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes
{
    public static void Main()
    {
        try
        {
            // Get the type of MyClass1.
            Type myType = typeof(MyClass1);
            // Get the members associated with MyClass1.
            MemberInfo[] myMembers = myType.GetMembers();

            // Display the attributes for each of the members of MyClass1.
            for(int i = 0; i < myMembers.Length; i++)
            {
                Object[] myAttributes = myMembers[i].GetCustomAttributes(true);
                if(myAttributes.Length > 0)
                {
                    Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]);
                    for(int j = 0; j < myAttributes.Length; j++)
                        Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("An exception occurred: {0}", e.Message);
        }
    }
}
Imports System.Reflection

' Define a custom attribute with one named parameter.
<AttributeUsage(AttributeTargets.All)> Public Class MyAttribute
    Inherits Attribute
    Private myName As String

    Public Sub New(ByVal name As String)
        myName = name
    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return myName
        End Get
    End Property
End Class

' Define a class that has the custom attribute associated with one of its members.
Public Class MyClass1

    <MyAttribute("This is an example attribute.")> Public Sub MyMethod(ByVal i As Integer)
        Return
    End Sub
End Class


Public Class MemberInfo_GetCustomAttributes

    Public Shared Sub Main()
        Try
            ' Get the type of MyClass1.
            Dim myType As Type = GetType(MyClass1)
            ' Get the members associated with MyClass1.
            Dim myMembers As MemberInfo() = myType.GetMembers()

            ' Display the attributes for each of the members of MyClass1.
            Dim i As Integer
            For i = 0 To myMembers.Length - 1
                Dim myAttributes As [Object]() = myMembers(i).GetCustomAttributes(False)
                If myAttributes.Length > 0 Then
                    Console.WriteLine("The attributes for the member {0} are: ", myMembers(i))
                    Dim j As Integer
                    For j = 0 To myAttributes.Length - 1
                        Console.WriteLine("The type of the attribute is: {0}", myAttributes(j))
                    Next j
                End If
            Next i
        Catch e As Exception
            Console.WriteLine("An exception occurred: {0}.", e.Message)
        End Try
    End Sub
End Class

注釈

このメソッドは、プロパティとイベントの inherit パラメーターを無視します。 プロパティとイベントの属性を継承チェーンで検索するには、 メソッドの適切なオーバーロードを Attribute.GetCustomAttributes 使用します。

Note

.NET Framework バージョン 2.0 では、メソッド、コンストラクター、および型が新しいメタデータ形式で格納されている場合、このメソッドはセキュリティ属性を返します。 バージョン 2.0 でコンパイルされたアセンブリでは、この形式が使用されます。 以前のバージョンの .NET Framework でコンパイルされた動的アセンブリとアセンブリでは、古い XML 形式が使用されます。 宣言型セキュリティ属性の出力に関するページを参照してください。

こちらもご覧ください

適用対象

GetCustomAttributes(Type, Boolean)

Source:
MemberInfo.cs
Source:
MemberInfo.cs
Source:
MemberInfo.cs

派生クラスでオーバーライドされた場合は、このメンバーに適用され、Type によって識別されるカスタム属性の配列を返します。

public:
 abstract cli::array <System::Object ^> ^ GetCustomAttributes(Type ^ attributeType, bool inherit);
public abstract object[] GetCustomAttributes (Type attributeType, bool inherit);
abstract member GetCustomAttributes : Type * bool -> obj[]
Public MustOverride Function GetCustomAttributes (attributeType As Type, inherit As Boolean) As Object()

パラメーター

attributeType
Type

検索する属性の種類。 この型に代入可能な属性だけが返されます。

inherit
Boolean

このメンバーの継承チェーンを検索して属性を見つける場合は true。それ以外の場合は false。 プロパティとイベントの場合、このパラメーターは無視されます。

戻り値

Object[]

このメンバーに適用されるカスタム属性の配列、または attributeType に割り当て可能な属性が適用されていない場合は要素を持たない配列。

実装

例外

カスタム属性の型を読み込むことはできません。

attributeTypenull の場合。

このメンバーは、リフレクションのみのコンテキストに読み込まれる型に属します。 「方法:リフレクションのみのコンテキストにアセンブリを読み込む」を参照してください。

次の例では、 という名前のスレッド静的フィールドtotalと という名前BaseClassの非 CLS 準拠メソッドという 2 つの非継承メンバーを持つ という名前MethodAのクラスを定義します。 という名前 DerivedClass のクラスは、 から BaseClass 継承し、その MethodA メソッドをオーバーライドします。 のメンバー DerivedClassには属性が適用されていないことに注意してください。 この例では、 のメンバーDerivedClassを反復処理して、 属性または ThreadStaticAttribute 属性がCLSCompliantAttribute適用されているかどうかを判断します。 が trueであるためinherit、 メソッドは、 の継承階層DerivedClassで指定された属性を検索します。 この例の出力に示すように、 total フィールドは 属性で ThreadStaticAttribute 修飾され MethodA 、 メソッドは 属性で CLSCompliantAttribute 修飾されます。

using System;

public class BaseClass
{
   [ThreadStatic] public int total;

   [CLSCompliant(false)] public virtual uint MethodA()
   {
      return (uint) 100;
   }
}

public class DerivedClass : BaseClass
{
   public override uint MethodA()
   {
      total++;
      return 200;
   }
}

public class Example
{
   public static void Main()
   {
      Type t = typeof(DerivedClass);
      Console.WriteLine("Members of {0}:", t.FullName);
      foreach (var m in t.GetMembers())
      {
         bool hasAttribute = false;
         Console.Write("   {0}: ", m.Name);
         if (m.GetCustomAttributes(typeof(CLSCompliantAttribute), true).Length > 0) {
            Console.Write("CLSCompliant");
            hasAttribute = true;
         }
         if (m.GetCustomAttributes(typeof(ThreadStaticAttribute), true).Length > 0) {
            Console.Write("ThreadStatic");
            hasAttribute = true;
         }
         if (! hasAttribute)
            Console.Write("No attributes");

         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       Members of DerivedClass:
//          MethodA: CLSCompliant
//          ToString: No attributes
//          Equals: No attributes
//          GetHashCode: No attributes
//          typeof: No attributes
//          .ctor: No attributes
//          total: ThreadStatic
Public Class BaseClass
   <ThreadStatic> Public total As Integer
   
   <CLSCompliant(False)> Public Overridable Function MethodA() As UInt32
      Return CUInt(100)
   End Function
End Class

Public Class DerivedClass : Inherits BaseClass
   Public Overrides Function MethodA() As UInt32
      total += 1
      Return 200
   End Function
End Class

Module Example
   Public Sub Main()
      Dim t As Type = GetType(DerivedClass)
      Console.WriteLine("Members of {0}:", t.FullName)
      For Each m In t.GetMembers()
         Dim hasAttribute As Boolean = False
         Console.Write("   {0}: ", m.Name)
         If m.GetCustomAttributes(GetType(CLSCompliantAttribute), True).Length > 0 Then
            Console.Write("CLSCompliant")
            hasAttribute = True
         End If
         If m.GetCustomAttributes(GetType(ThreadStaticAttribute), True).Length > 0 Then
            Console.Write("ThreadStatic")
            hasAttribute = True
         End If
         If Not hasAttribute Then
            Console.Write("No attributes")
         End If
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output:
'       Members of DerivedClass:
'          MethodA: CLSCompliant
'          ToString: No attributes
'          Equals: No attributes
'          GetHashCode: No attributes
'          GetType: No attributes
'          .ctor: No attributes
'          total: ThreadStatic

注釈

このメソッドは、プロパティとイベントの inherit パラメーターを無視します。 プロパティとイベントの属性を継承チェーンで検索するには、 メソッドの適切なオーバーロードを Attribute.GetCustomAttributes 使用します。

Note

.NET Framework バージョン 2.0 では、属性が新しいメタデータ形式で格納されている場合、このメソッドはメソッド、コンストラクター、および型のセキュリティ属性を返します。 バージョン 2.0 でコンパイルされたアセンブリでは、この形式が使用されます。 以前のバージョンの .NET Framework でコンパイルされた動的アセンブリとアセンブリでは、古い XML 形式が使用されます。 宣言型セキュリティ属性の出力に関するページを参照してください。

適用対象