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

Definición

Cuando se reemplaza en una clase derivada, devuelve los atributos personalizados aplicados a este miembro.When overridden in a derived class, returns custom attributes applied to this member.

Sobrecargas

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

Cuando se reemplaza en una clase derivada, devuelve una matriz de todos los atributos personalizados aplicados a este miembro.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)

Cuando se invalida en una clase derivada, devuelve una matriz de atributos personalizados aplicados a este miembro e identificado por 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)

Cuando se reemplaza en una clase derivada, devuelve una matriz de todos los atributos personalizados aplicados a este miembro.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()

Parámetros

inherit
Boolean Boolean Boolean Boolean

true para buscar la cadena de herencia de este miembro para encontrar los atributos; en caso contrario, false.true to search this member's inheritance chain to find the attributes; otherwise, false. Este parámetro se omite para las propiedades y los eventos.This parameter is ignored for properties and events.

Devoluciones

Object[]

Matriz que contiene todos los atributos personalizados aplicados a este miembro, o matriz con cero elementos si no se ha definido ningún atributo.An array that contains all the custom attributes applied to this member, or an array with zero elements if no attributes are defined.

Implementaciones

Excepciones

Este miembro pertenece a un tipo que se carga en el contexto de solo reflexión.This member belongs to a type that is loaded into the reflection-only context. Vea Cómo: Cargar ensamblados en el contexto de solo reflexión.See How to: Load Assemblies into the Reflection-Only Context.

No ha podido cargarse un tipo de atributo personalizado.A custom attribute type could not be loaded.

Ejemplos

En el ejemplo siguiente se define un atributo personalizado y se asocia MyClass.MyMethodel atributo con, se recupera el atributo en tiempo de ejecución y se muestra el resultado.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

    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

Comentarios

Este método omite el inherit parámetro para propiedades y eventos.This method ignores the inherit parameter for properties and events. Para buscar en la cadena de herencia atributos de propiedades y eventos, use las sobrecargas adecuadas del Attribute.GetCustomAttributes método.To search the inheritance chain for attributes on properties and events, use the appropriate overloads of the Attribute.GetCustomAttributes method.

Nota

En la .NET Framework versión 2,0, este método devuelve atributos de seguridad en métodos, constructores y tipos si se almacenan en el nuevo formato de metadatos.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. Los ensamblados compilados con la versión 2,0 usan este formato.Assemblies compiled with version 2.0 use this format. Los ensamblados y ensamblados dinámicos compilados con versiones anteriores de la .NET Framework usar el formato XML antiguo.Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. Consulte emisión de atributos de seguridad declarativa.See Emitting Declarative Security Attributes.

Consulte también:

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

Cuando se invalida en una clase derivada, devuelve una matriz de atributos personalizados aplicados a este miembro e identificado por 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()

Parámetros

attributeType
Type Type Type Type

El tipo de atributo que se va a buscar.The type of attribute to search for. Solo se devuelven los atributos que son asignables a este tipo.Only attributes that are assignable to this type are returned.

inherit
Boolean Boolean Boolean Boolean

true para buscar la cadena de herencia de este miembro para encontrar los atributos; en caso contrario, false.true to search this member's inheritance chain to find the attributes; otherwise, false. Este parámetro se omite para las propiedades y los eventos.This parameter is ignored for properties and events.

Devoluciones

Object[]

Se ha aplicado una matriz de atributos personalizados aplicados a este miembro, o matriz con cero elementos si no hay atributos asignables al 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.

Implementaciones

Excepciones

No se puede cargar un tipo de atributo personalizado.A custom attribute type cannot be loaded.

Si attributeType es null.If attributeType is null.

Este miembro pertenece a un tipo que se carga en el contexto de solo reflexión.This member belongs to a type that is loaded into the reflection-only context. Vea Cómo: Cargar ensamblados en el contexto de solo reflexión.See How to: Load Assemblies into the Reflection-Only Context.

Ejemplos

En el ejemplo siguiente se define una BaseClass clase denominada que tiene dos miembros no heredados: un campo estático total de subproceso denominado y un método no conforme MethodAa CLS denominado.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. Una clase denominada DerivedClass hereda de BaseClass e invalida su MethodA método.A class named DerivedClass inherits from BaseClass and overrides its MethodA method. Tenga en cuenta que no se aplica ningún atributo a DerivedClasslos miembros de.Note that no attributes are applied to the members of DerivedClass. En el ejemplo se recorren DerivedClass en iteración los CLSCompliantAttribute miembros ThreadStaticAttribute de para determinar si se les ha aplicado el atributo o.The example iterates the members of DerivedClass to determine whether the CLSCompliantAttribute or ThreadStaticAttribute attribute as been applied to them. Dado inherit que truees, el método busca el atributo especificado DerivedClass en la jerarquía de herencia de.Because inherit is true, the method searches the inheritance hierarchy of DerivedClass for the specified attribute. Como muestra la salida del total ejemplo, el campo se decora con el ThreadStaticAttribute atributo y el MethodA método se decora con el CLSCompliantAttribute atributo.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

Comentarios

Este método omite el inherit parámetro para propiedades y eventos.This method ignores the inherit parameter for properties and events. Para buscar en la cadena de herencia atributos de propiedades y eventos, use las sobrecargas adecuadas del Attribute.GetCustomAttributes método.To search the inheritance chain for attributes on properties and events, use the appropriate overloads of the Attribute.GetCustomAttributes method.

Nota

En la .NET Framework versión 2,0, este método devuelve atributos de seguridad en métodos, constructores y tipos si los atributos se almacenan en el nuevo formato de metadatos.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. Los ensamblados compilados con la versión 2,0 usan este formato.Assemblies compiled with version 2.0 use this format. Los ensamblados y ensamblados dinámicos compilados con versiones anteriores de la .NET Framework usar el formato XML antiguo.Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. Consulte emisión de atributos de seguridad declarativa.See Emitting Declarative Security Attributes.

Se aplica a