MemberInfo.GetCustomAttributes MemberInfo.GetCustomAttributes MemberInfo.GetCustomAttributes MemberInfo.GetCustomAttributes Method

定義

在衍生類別中覆寫時,傳回套用至此成員的自訂屬性。When overridden in a derived class, returns custom attributes applied to this member.

多載

GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean)

在衍生類別中覆寫時,傳回套用至此成員之所有自訂屬性的陣列。When overridden in a derived class, returns an array of all custom attributes applied to this member.

GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean)

當在衍生的類別中覆寫時,會傳回套用至這個成員的自訂屬性陣列,並以 Type 識別。When overridden in a derived class, returns an array of custom attributes applied to this member and identified by Type.

GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean)

在衍生類別中覆寫時,傳回套用至此成員之所有自訂屬性的陣列。When overridden in a derived class, returns an array of all custom attributes applied to this member.

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 Boolean Boolean Boolean

true 表示要搜尋這個成員的繼承鏈結以尋找屬性;否則為 falsetrue to search this member's inheritance chain to find the attributes; otherwise, false. 這個參數會忽略屬性和事件。This parameter is ignored for properties and events.

傳回

Object[]

包含套用至此成員之所有自訂屬性的陣列,如果沒有定義屬性,則為包含零個元素的陣列。An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined.

實作

例外狀況

這個成員所屬的型別已載入僅限反映的內容中。This member belongs to a type that is loaded into the reflection-only context. 請參閱如何:將組件載入僅限反映的內容See How to: Load Assemblies into the Reflection-Only Context.

無法載入自訂屬性型別。A custom attribute type could not be loaded.

範例

下列範例會定義自訂屬性,並將屬性與MyClass.MyMethod建立關聯,並在執行時間抓取屬性,並顯示結果。The following example defines a custom attribute and associates the attribute with MyClass.MyMethod, retrieves the attribute at run time, and displays the result.

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 'New

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

' 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 'MyMethod
End Class 'MyClass1


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 'Main
End Class 'MemberInfo_GetCustomAttributes

備註

這個方法會忽略inherit屬性和事件的參數。This method ignores the inherit parameter for properties and events. 若要在繼承鏈中搜尋屬性和事件的屬性,請使用Attribute.GetCustomAttributes方法的適當多載。To search the inheritance chain for attributes on properties and events, use the appropriate overloads of the Attribute.GetCustomAttributes method.

注意

在 .NET Framework 版本2.0 中,如果方法、函式和類型是以新的元資料格式儲存,則這個方法會傳回這些屬性。In the .NET Framework version 2.0, this method returns security attributes on methods, constructors, and types if they are stored in the new metadata format. 以2.0 版編譯的元件會使用此格式。Assemblies compiled with version 2.0 use this format. 使用舊版 .NET Framework 編譯的動態元件和元件會使用舊的 XML 格式。Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. 請參閱發出宣告式安全性屬性See Emitting Declarative Security Attributes.

另請參閱

GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean)

當在衍生的類別中覆寫時,會傳回套用至這個成員的自訂屬性陣列,並以 Type 識別。When overridden in a derived class, returns an array of custom attributes applied to this member and identified by 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 Type Type Type

要搜尋的屬性類型。The type of attribute to search for. 只會傳回可指派給這種類型的屬性。Only attributes that are assignable to this type are returned.

inherit
Boolean Boolean Boolean Boolean

true 表示要搜尋這個成員的繼承鏈結以尋找屬性;否則為 falsetrue to search this member's inheritance chain to find the attributes; otherwise, false. 這個參數會忽略屬性和事件。This parameter is ignored for properties and events.

傳回

Object[]

套用至這個成員的自訂屬性陣列,或如果 attributeType 沒有套用任何可指派的屬性,則為零個項目的陣列。An array of custom attributes applied to this member, or an array with zero elements if no attributes assignable to attributeType have been applied.

實作

例外狀況

無法載入自訂屬性型別。A custom attribute type cannot be loaded.

如果 attributeTypenullIf attributeType is null.

這個成員所屬的型別已載入僅限反映的內容中。This member belongs to a type that is loaded into the reflection-only context. 請參閱如何:將組件載入僅限反映的內容See How to: Load Assemblies into the Reflection-Only Context.

範例

下列範例會定義名為BaseClass的類別,其中包含兩個非繼承的成員:名total為的執行緒靜態欄位,以及名為MethodA的不符合 CLS 規範的方法。The following example defines a class named BaseClass that has two non-inherited members: a thread static field named total and a non-CLS-compliant method named MethodA. 名為DerivedClass的類別會BaseClass繼承自, MethodA並覆寫其方法。A class named DerivedClass inherits from BaseClass and overrides its MethodA method. 請注意,沒有任何屬性會套用至的DerivedClass成員。Note that no attributes are applied to the members of DerivedClass. 此範例會逐一查看的DerivedClass成員,以判斷CLSCompliantAttribute是否ThreadStaticAttribute已套用或屬性。The example iterates the members of DerivedClass to determine whether the CLSCompliantAttribute or ThreadStaticAttribute attribute as been applied to them. 因為inherittrue,所以方法會在的繼承DerivedClass階層架構中搜尋指定的屬性。Because inherit is true, the method searches the inheritance hierarchy of DerivedClass for the specified attribute. 如範例的輸出total所示,欄位是ThreadStaticAttribute以屬性裝飾,而MethodA方法則是以CLSCompliantAttribute屬性裝飾。As the output from the example shows, the total field is decorated with the ThreadStaticAttribute attribute, and the MethodA method is decorated with the CLSCompliantAttribute attribute.

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屬性和事件的參數。This method ignores the inherit parameter for properties and events. 若要在繼承鏈中搜尋屬性和事件的屬性,請使用Attribute.GetCustomAttributes方法的適當多載。To search the inheritance chain for attributes on properties and events, use the appropriate overloads of the Attribute.GetCustomAttributes method.

注意

在 .NET Framework 版本2.0 中,如果屬性是以新的元資料格式儲存,這個方法就會傳回方法、函式和類型上的安全性屬性。In the .NET Framework version 2.0, this method returns security attributes on methods, constructors, and types if the attributes are stored in the new metadata format. 以2.0 版編譯的元件會使用此格式。Assemblies compiled with version 2.0 use this format. 使用舊版 .NET Framework 編譯的動態元件和元件會使用舊的 XML 格式。Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. 請參閱發出宣告式安全性屬性See Emitting Declarative Security Attributes.

適用於