MemberInfo.GetCustomAttributes Método

Definição

Quando substituído em uma classe derivada, retorna atributos personalizados aplicados a esse membro.

Sobrecargas

GetCustomAttributes(Boolean)

Quando substituído em uma classe derivada, retorna uma matriz de todos os atributos personalizados aplicados a esse membro.

GetCustomAttributes(Type, Boolean)

Quando substituído em uma classe derivada, retorna uma matriz de atributos personalizados aplicados a esse membro e identificados por Type.

GetCustomAttributes(Boolean)

Quando substituído em uma classe derivada, retorna uma matriz de todos os atributos personalizados aplicados a esse 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()

Parâmetros

inherit
Boolean

true para pesquisar a cadeia de herança desse membro para encontrar os atributos; caso contrário, false. Esse parâmetro é ignorado para propriedades e eventos.

Retornos

Object[]

Uma matriz que contém todos os atributos personalizados aplicados a esse membro ou uma matriz com zero elementos se nenhum atributo for definido.

Implementações

Exceções

Esse membro pertence a um tipo carregado no contexto somente reflexão. Consulte Como carregar assemblies no contexto de somente reflexão.

Um tipo de atributo personalizado não pôde ser carregado.

Exemplos

O exemplo a seguir define um atributo personalizado e associa o atributo a , recupera o atributo em tempo de executar e MyClass.MyMethod exibe o resultado.

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

Comentários

Esse método ignora o parâmetro inherit para propriedades e eventos. Para pesquisar atributos na cadeia de herança em propriedades e eventos, use as sobrecargas apropriadas do Attribute.GetCustomAttributes método.

Observação

No .NET Framework versão 2.0, esse método retornará atributos de segurança em métodos, construtores e tipos se eles são armazenados no novo formato de metadados. Os assemblies compilados com a versão 2.0 usam esse formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte Emitindo atributos de segurança declarativa.

Confira também

Aplica-se a

GetCustomAttributes(Type, Boolean)

Quando substituído em uma classe derivada, retorna uma matriz de atributos personalizados aplicados a esse membro e identificados por 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()

Parâmetros

attributeType
Type

O tipo de atributo a ser pesquisado. Somente os atributos que podem ser atribuídos a esse tipo são retornados.

inherit
Boolean

true para pesquisar a cadeia de herança desse membro para encontrar os atributos; caso contrário, false. Esse parâmetro é ignorado para propriedades e eventos.

Retornos

Object[]

Uma matriz de atributos personalizados aplicados a este membro ou uma matriz com zero elemento se nenhum atributo que puder ser atribuído a attributeType for aplicado.

Implementações

Exceções

Um tipo de atributo personalizado não pode ser carregado.

Se attributeType for null.

Esse membro pertence a um tipo carregado no contexto somente reflexão. Consulte How to: Load Assemblies into the Reflection-Only Context.

Exemplos

O exemplo a seguir define uma classe chamada que tem dois membros não herdados: um campo estático de thread chamado e um método não compatível com BaseClass total CLS chamado MethodA . Uma classe chamada DerivedClass herda BaseClass de e substitui seu MethodA método. Observe que nenhum atributos é aplicado aos membros do DerivedClass . O exemplo itera os membros de DerivedClass para determinar se o atributo ou foi aplicado a CLSCompliantAttribute ThreadStaticAttribute eles. Como inherit é , o método pesquisa a hierarquia de herança de para o atributo true DerivedClass especificado. Como mostra a saída do exemplo, o campo é decorado com o atributo e o método total é decorado com o atributo 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

Comentários

Esse método ignora o parâmetro inherit para propriedades e eventos. Para pesquisar atributos na cadeia de herança em propriedades e eventos, use as sobrecargas apropriadas do Attribute.GetCustomAttributes método.

Observação

No .NET Framework versão 2.0, esse método retornará atributos de segurança em métodos, construtores e tipos se os atributos são armazenados no novo formato de metadados. Os assemblies compilados com a versão 2.0 usam esse formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte Emitindo atributos de segurança declarativa.

Aplica-se a