MemberInfo.GetCustomAttributes Metodo

Definizione

Quando se ne effettua l'override in una classe derivata, restituisce gli attributi personalizzati applicati a questo membro.

Overload

GetCustomAttributes(Boolean)

Se sottoposto a override in una classe derivata, restituisce una matrice di tutti gli attributi personalizzati applicati a questo membro.

GetCustomAttributes(Type, Boolean)

Quando viene sottoposto a override in una classe derivata, questo metodo restituisce una matrice di attributi personalizzati applicati a questo membro e identificati da Type.

GetCustomAttributes(Boolean)

Se sottoposto a override in una classe derivata, restituisce una matrice di tutti gli attributi personalizzati applicati a questo membro.

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

Parametri

inherit
Boolean

true per eseguire la ricerca nella catena di ereditarietà del membro per trovare gli attributi; in caso contrario, false. Questo parametro viene ignorato per proprietà ed eventi.

Restituisce

Object[]

Matrice contenente tutti gli attributi personalizzati applicati a questo membro o matrice con zero elementi se non è stato definito alcun attributo.

Implementazioni

Eccezioni

Questo membro appartiene a un tipo caricato nel contesto Reflection-Only. Vedere How to: Load Assemblies into the Reflection-Only Context (Procedura: Caricare assembly nel contesto di sola reflection).

Impossibile caricare il tipo di attributo personalizzato.

Esempio

L'esempio seguente definisce un attributo personalizzato e associa l'attributo a , recupera l'attributo in fase di esecuzione MyClass.MyMethod e visualizza il risultato.

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

Commenti

Questo metodo ignora il parametro inherit per proprietà ed eventi. Per cercare attributi su proprietà ed eventi nella catena di ereditarietà, usare gli overload appropriati del Attribute.GetCustomAttributes metodo .

Nota

Nella versione .NET Framework 2.0 questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se sono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 usano questo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti del .NET Framework usano il formato XML precedente. Vedere Creazione di attributi di sicurezza dichiarativa.

Vedi anche

Si applica a

GetCustomAttributes(Type, Boolean)

Quando viene sottoposto a override in una classe derivata, questo metodo restituisce una matrice di attributi personalizzati applicati a questo membro e identificati da 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()

Parametri

attributeType
Type

Tipo di attributo da cercare. Vengono restituiti solo gli attributi assegnabili a questo tipo.

inherit
Boolean

true per eseguire la ricerca nella catena di ereditarietà del membro per trovare gli attributi; in caso contrario, false. Questo parametro viene ignorato per proprietà ed eventi.

Restituisce

Object[]

Matrice degli attributi personalizzati applicati a questo membro o matrice con zero elementi se non è stato applicato alcun attributo assegnabile a attributeType.

Implementazioni

Eccezioni

Non è possibile caricare un tipo di attributo personalizzato.

Se attributeType è null.

Questo membro appartiene a un tipo caricato nel contesto Reflection-Only. Vedere How to: Load Assemblies into the Reflection-Only Context (Procedura: Caricare assembly nel contesto di sola reflection).

Esempio

Nell'esempio seguente viene definita una classe denominata con due membri non ereditati: un campo statico del thread denominato e un metodo non conforme BaseClass total a CLS denominato MethodA . Una classe denominata DerivedClass eredita da ed esegue BaseClass l'override del MethodA relativo metodo . Si noti che non vengono applicati attributi ai membri di DerivedClass . Nell'esempio vengono iterati i membri di DerivedClass per determinare se l'attributo o CLSCompliantAttribute è stato ThreadStaticAttribute applicato. Poiché è , il metodo cerca l'attributo specificato nella inherit true gerarchia DerivedClass di ereditarietà di . Come illustrato nell'output dell'esempio, il campo è decorato con l'attributo e total il metodo è decorato con ThreadStaticAttribute MethodA CLSCompliantAttribute l'attributo .

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

Commenti

Questo metodo ignora il parametro inherit per proprietà ed eventi. Per cercare attributi su proprietà ed eventi nella catena di ereditarietà, usare gli overload appropriati del Attribute.GetCustomAttributes metodo .

Nota

Nella versione .NET Framework 2.0 questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se gli attributi sono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 usano questo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti del .NET Framework usano il formato XML precedente. Vedere Creazione di attributi di sicurezza dichiarativa.

Si applica a