Ler en inglés

Compartir por


Attribute.GetCustomAttributes Método

Definición

Recupera una matriz de los atributos personalizados aplicados a un ensamblado, módulo, miembro de tipo o parámetro de método.

Sobrecargas

GetCustomAttributes(ParameterInfo, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método y si se van a buscar antecesores del parámetro de método.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del miembro.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del parámetro de método.

GetCustomAttributes(Module, Type, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo, el tipo del atributo personalizado que se va a buscar y una opción de búsqueda omitida.

GetCustomAttributes(MemberInfo, Type)

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro y el tipo del atributo personalizado que se va a buscar.

GetCustomAttributes(Assembly, Type, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado, el tipo del atributo personalizado que se va a buscar y una opción de búsqueda omitida.

GetCustomAttributes(Module, Type)

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo y el tipo del atributo personalizado que se va a buscar.

GetCustomAttributes(ParameterInfo, Type)

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método y el tipo del atributo personalizado que se va a buscar.

GetCustomAttributes(MemberInfo, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del miembro.

GetCustomAttributes(Assembly, Type)

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado y el tipo del atributo personalizado que se va a buscar.

GetCustomAttributes(Assembly, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado y una opción de búsqueda omitida.

GetCustomAttributes(ParameterInfo)

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Un parámetro especifica el parámetro de método.

GetCustomAttributes(Module)

Recupera una matriz de los atributos personalizados aplicados a un módulo. Un parámetro especifica el módulo.

GetCustomAttributes(MemberInfo)

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Un parámetro especifica el miembro.

GetCustomAttributes(Assembly)

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Un parámetro especifica el ensamblado.

GetCustomAttributes(Module, Boolean)

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo y una opción de búsqueda ignorada.

GetCustomAttributes(ParameterInfo, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método y si se van a buscar antecesores del parámetro de método.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.ParameterInfo element, bool inherit);

Parámetros

element
ParameterInfo

Objeto derivado de la clase ParameterInfo que describe un parámetro de un miembro de una clase.

inherit
Boolean

Si true, especifica también buscar los antecesores de element para los atributos personalizados.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

La propiedad Member de element es null.

element es null.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un ParameterInfo como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

namespace CustAttrs5CS {
    public class AClass {
        public void ParamArrayAndDesc(
            // Add ParamArray (with the keyword) and Description attributes.
            [Description("This argument is a ParamArray")]
            params int[] args)
        {}
    }

    class DemoClass {
        static void Main(string[] args) {
            // Get the Class type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for the method.
            MethodInfo mInfo = clsType.GetMethod("ParamArrayAndDesc");
            if (mInfo != null) {
                // Get the parameter information.
                ParameterInfo[] pInfo = mInfo.GetParameters();
                if (pInfo != null) {
                    // Iterate through all the attributes for the parameter.
                    foreach(Attribute attr in
                        Attribute.GetCustomAttributes(pInfo[0])) {
                        // Check for the ParamArray attribute.
                        if (attr.GetType() == typeof(ParamArrayAttribute))
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has the ParamArray attribute.",
                                pInfo[0].Name, mInfo.Name);
                        // Check for the Description attribute.
                        else if (attr.GetType() ==
                            typeof(DescriptionAttribute)) {
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has a description attribute.",
                                pInfo[0].Name, mInfo.Name);
                            Console.WriteLine("The description is: \"{0}\"",
                                ((DescriptionAttribute)attr).Description);
                        }
                    }
                }
            }
        }
    }
}

/*
 * Output:
 * Parameter args for method ParamArrayAndDesc has the ParamArray attribute.
 * Parameter args for method ParamArrayAndDesc has a description attribute.
 * The description is: "This argument is a ParamArray"
 */

Comentarios

Si element representa un parámetro en un método de un tipo derivado, el valor devuelto incluye los atributos personalizados que se pueden heredar aplicados al mismo parámetro en los métodos base invalidados.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(MemberInfo, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del miembro.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element, Type type, bool inherit);
C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element, Type attributeType, bool inherit);

Parámetros

element
MemberInfo

Objeto derivado de la clase MemberInfo que describe un constructor, evento, campo, método o miembro de propiedad de una clase.

typeattributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

inherit
Boolean

Si true, especifica también buscar los antecesores de element para los atributos personalizados.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo type aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o type es null.

type no se deriva de Attribute.

element no es un constructor, método, propiedad, evento, tipo o campo.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un MemberInfo como parámetro.

C#
using System;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;

namespace CustAttrs4CS
{

    // Define an enumeration of Win32 unmanaged types
    public enum UnmanagedType
    {
        User,
        GDI,
        Kernel,
        Shell,
        Networking,
        Multimedia
    }

    // Define the Unmanaged attribute.
    public class UnmanagedAttribute : Attribute
    {
        // Storage for the UnmanagedType value.
        protected UnmanagedType thisType;

        // Set the unmanaged type in the constructor.
        public UnmanagedAttribute(UnmanagedType type)
        {
            thisType = type;
        }

        // Define a property to get and set the UnmanagedType value.
        public UnmanagedType Win32Type
        {
            get { return thisType; }
            set { thisType = Win32Type; }
        }
    }

    // Create a class for an imported Win32 unmanaged function.
    public class Win32 {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type);
    }

    public class AClass {
        // Add some attributes to Win32CallMethod.
        [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
        [Unmanaged(UnmanagedType.User)]
        public void Win32CallMethod()
        {
            Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0);
        }
    }

    class DemoClass {
        static void Main(string[] args)
            {
            // Get the AClass type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for Win32CallMethod.
            MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
            if (mInfo != null)
            {
                // Iterate through all the attributes of the method.
                foreach(Attribute attr in
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the Obsolete attribute.
                    if (attr.GetType() == typeof(ObsoleteAttribute))
                    {
                        Console.WriteLine("Method {0} is obsolete. " +
                            "The message is:",
                            mInfo.Name);
                        Console.WriteLine("  \"{0}\"",
                            ((ObsoleteAttribute)attr).Message);
                    }

                    // Check for the Unmanaged attribute.
                    else if (attr.GetType() == typeof(UnmanagedAttribute))
                    {
                        Console.WriteLine(
                            "This method calls unmanaged code.");
                        Console.WriteLine(
                            String.Format("The Unmanaged attribute type is {0}.",
                                          ((UnmanagedAttribute)attr).Win32Type));
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    }
}

/*

This code example produces the following results.

First, the compilation yields the warning, "... This method is
obsolete. Use managed MsgBox instead."
Second, execution yields a message box with a title of "Caution!"
and message text of "This is an unmanaged call."
Third, the following text is displayed in the console window:

Method Win32CallMethod is obsolete. The message is:
  "This method is obsolete. Use managed MsgBox instead."
This method calls unmanaged code.
The Unmanaged attribute type is User.

*/

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element si inherit es true.

Nota

A partir de .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. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(ParameterInfo, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del parámetro de método.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.ParameterInfo element, Type attributeType, bool inherit);

Parámetros

element
ParameterInfo

Objeto derivado de la clase ParameterInfo que describe un parámetro de un miembro de una clase.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

inherit
Boolean

Si true, especifica también buscar los antecesores de element para los atributos personalizados.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un ParameterInfo como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

namespace CustAttrs5CS {
    public class AClass {
        public void ParamArrayAndDesc(
            // Add ParamArray (with the keyword) and Description attributes.
            [Description("This argument is a ParamArray")]
            params int[] args)
        {}
    }

    class DemoClass {
        static void Main(string[] args) {
            // Get the Class type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for the method.
            MethodInfo mInfo = clsType.GetMethod("ParamArrayAndDesc");
            if (mInfo != null) {
                // Get the parameter information.
                ParameterInfo[] pInfo = mInfo.GetParameters();
                if (pInfo != null) {
                    // Iterate through all the attributes for the parameter.
                    foreach(Attribute attr in
                        Attribute.GetCustomAttributes(pInfo[0])) {
                        // Check for the ParamArray attribute.
                        if (attr.GetType() == typeof(ParamArrayAttribute))
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has the ParamArray attribute.",
                                pInfo[0].Name, mInfo.Name);
                        // Check for the Description attribute.
                        else if (attr.GetType() ==
                            typeof(DescriptionAttribute)) {
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has a description attribute.",
                                pInfo[0].Name, mInfo.Name);
                            Console.WriteLine("The description is: \"{0}\"",
                                ((DescriptionAttribute)attr).Description);
                        }
                    }
                }
            }
        }
    }
}

/*
 * Output:
 * Parameter args for method ParamArrayAndDesc has the ParamArray attribute.
 * Parameter args for method ParamArrayAndDesc has a description attribute.
 * The description is: "This argument is a ParamArray"
 */

Comentarios

Si element representa un parámetro en un método de un tipo derivado, el valor devuelto incluye los atributos personalizados que se pueden heredar aplicados al mismo parámetro en los métodos base invalidados.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Module, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo, el tipo del atributo personalizado que se va a buscar y una opción de búsqueda omitida.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Module element, Type attributeType, bool inherit);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portátil.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

inherit
Boolean

Este parámetro se omite y no afecta al funcionamiento de este método.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Module como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

// Assign some attributes to the module.
[module:Description("A sample description")]

// Set the module's CLSCompliant attribute to false
// The CLSCompliant attribute is applicable for /target:module.
[module:CLSCompliant(false)]

namespace CustAttrs2CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Module type to access its metadata.
            Module module = clsType.Module;

            // Iterate through all the attributes for the module.
            foreach(Attribute attr in Attribute.GetCustomAttributes(module)) {
                // Check for the Description attribute.
                if (attr.GetType() == typeof(DescriptionAttribute))
                    Console.WriteLine("Module {0} has the description " +
                        "\"{1}\".", module.Name,
                        ((DescriptionAttribute)attr).Description);
                // Check for the CLSCompliant attribute.
                else if (attr.GetType() == typeof(CLSCompliantAttribute))
                    Console.WriteLine("Module {0} {1} CLSCompliant.",
                        module.Name,
                        ((CLSCompliantAttribute)attr).IsCompliant ?
                            "is" : "is not");
            }
        }
    }
}

/*
 * Output:
 * Module CustAttrs2CS.exe is not CLSCompliant.
 * Module CustAttrs2CS.exe has the description "A sample description".
 */

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element si inherit es true.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(MemberInfo, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro y el tipo del atributo personalizado que se va a buscar.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element, Type type);
C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element, Type attributeType);

Parámetros

element
MemberInfo

Objeto derivado de la clase MemberInfo que describe un constructor, evento, campo, método o miembro de propiedad de una clase.

typeattributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo type aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o type es null.

type no se deriva de Attribute.

element no es un constructor, método, propiedad, evento, tipo o campo.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttribute, tomando un MemberInfo como parámetro.

C#
using System;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;

namespace CustAttrs4CS
{

    // Define an enumeration of Win32 unmanaged types
    public enum UnmanagedType
    {
        User,
        GDI,
        Kernel,
        Shell,
        Networking,
        Multimedia
    }

    // Define the Unmanaged attribute.
    public class UnmanagedAttribute : Attribute
    {
        // Storage for the UnmanagedType value.
        protected UnmanagedType thisType;

        // Set the unmanaged type in the constructor.
        public UnmanagedAttribute(UnmanagedType type)
        {
            thisType = type;
        }

        // Define a property to get and set the UnmanagedType value.
        public UnmanagedType Win32Type
        {
            get { return thisType; }
            set { thisType = Win32Type; }
        }
    }

    // Create a class for an imported Win32 unmanaged function.
    public class Win32 {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type);
    }

    public class AClass {
        // Add some attributes to Win32CallMethod.
        [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
        [Unmanaged(UnmanagedType.User)]
        public void Win32CallMethod()
        {
            Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0);
        }
    }

    class DemoClass {
        static void Main(string[] args)
            {
            // Get the AClass type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for Win32CallMethod.
            MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
            if (mInfo != null)
            {
                // Iterate through all the attributes of the method.
                foreach(Attribute attr in
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the Obsolete attribute.
                    if (attr.GetType() == typeof(ObsoleteAttribute))
                    {
                        Console.WriteLine("Method {0} is obsolete. " +
                            "The message is:",
                            mInfo.Name);
                        Console.WriteLine("  \"{0}\"",
                            ((ObsoleteAttribute)attr).Message);
                    }

                    // Check for the Unmanaged attribute.
                    else if (attr.GetType() == typeof(UnmanagedAttribute))
                    {
                        Console.WriteLine(
                            "This method calls unmanaged code.");
                        Console.WriteLine(
                            String.Format("The Unmanaged attribute type is {0}.",
                                          ((UnmanagedAttribute)attr).Win32Type));
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    }
}

/*

This code example produces the following results.

First, the compilation yields the warning, "... This method is
obsolete. Use managed MsgBox instead."
Second, execution yields a message box with a title of "Caution!"
and message text of "This is an unmanaged call."
Third, the following text is displayed in the console window:

Method Win32CallMethod is obsolete. The message is:
  "This method is obsolete. Use managed MsgBox instead."
This method calls unmanaged code.
The Unmanaged attribute type is User.

*/

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element.

Nota

A partir de .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. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Assembly, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado, el tipo del atributo personalizado que se va a buscar y una opción de búsqueda omitida.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Assembly element, Type attributeType, bool inherit);

Parámetros

element
Assembly

Objeto derivado de la clase Assembly que describe una colección reutilizable de módulos.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

inherit
Boolean

Este parámetro se omite y no afecta al funcionamiento de este método.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Assembly como parámetro.

C#
using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

class Example {
    static void Main() {
        // Get the Assembly object to access its metadata.
        Assembly assy = typeof(Example).Assembly;

        // Iterate through the attributes for the assembly.
        foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
            // Check for the AssemblyTitle attribute.
            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                Console.WriteLine("Assembly title is \"{0}\".",
                    ((AssemblyTitleAttribute)attr).Title);

            // Check for the AssemblyDescription attribute.
            else if (attr.GetType() ==
                typeof(AssemblyDescriptionAttribute))
                Console.WriteLine("Assembly description is \"{0}\".",
                    ((AssemblyDescriptionAttribute)attr).Description);

            // Check for the AssemblyCompany attribute.
            else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                Console.WriteLine("Assembly company is {0}.",
                    ((AssemblyCompanyAttribute)attr).Company);
        }
   }
}
// The example displays the following output:
//     Assembly title is "CustAttrs1CS".
//     Assembly description is "GetCustomAttributes() Demo".
//     Assembly company is Microsoft.

Comentarios

Nota

A partir de la versión 2.0 de .NET Framework, este método devuelve atributos de seguridad si los atributos se almacenan en el nuevo formato de metadatos. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Module, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo y el tipo del atributo personalizado que se va a buscar.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Module element, Type attributeType);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portátil.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Module como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

// Assign some attributes to the module.
[module:Description("A sample description")]

// Set the module's CLSCompliant attribute to false
// The CLSCompliant attribute is applicable for /target:module.
[module:CLSCompliant(false)]

namespace CustAttrs2CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Module type to access its metadata.
            Module module = clsType.Module;

            // Iterate through all the attributes for the module.
            foreach(Attribute attr in Attribute.GetCustomAttributes(module)) {
                // Check for the Description attribute.
                if (attr.GetType() == typeof(DescriptionAttribute))
                    Console.WriteLine("Module {0} has the description " +
                        "\"{1}\".", module.Name,
                        ((DescriptionAttribute)attr).Description);
                // Check for the CLSCompliant attribute.
                else if (attr.GetType() == typeof(CLSCompliantAttribute))
                    Console.WriteLine("Module {0} {1} CLSCompliant.",
                        module.Name,
                        ((CLSCompliantAttribute)attr).IsCompliant ?
                            "is" : "is not");
            }
        }
    }
}

/*
 * Output:
 * Module CustAttrs2CS.exe is not CLSCompliant.
 * Module CustAttrs2CS.exe has the description "A sample description".
 */

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(ParameterInfo, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Los parámetros especifican el parámetro de método y el tipo del atributo personalizado que se va a buscar.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.ParameterInfo element, Type attributeType);

Parámetros

element
ParameterInfo

Objeto derivado de la clase ParameterInfo que describe un parámetro de un miembro de una clase.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un ParameterInfo como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

namespace CustAttrs5CS {
    public class AClass {
        public void ParamArrayAndDesc(
            // Add ParamArray (with the keyword) and Description attributes.
            [Description("This argument is a ParamArray")]
            params int[] args)
        {}
    }

    class DemoClass {
        static void Main(string[] args) {
            // Get the Class type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for the method.
            MethodInfo mInfo = clsType.GetMethod("ParamArrayAndDesc");
            if (mInfo != null) {
                // Get the parameter information.
                ParameterInfo[] pInfo = mInfo.GetParameters();
                if (pInfo != null) {
                    // Iterate through all the attributes for the parameter.
                    foreach(Attribute attr in
                        Attribute.GetCustomAttributes(pInfo[0])) {
                        // Check for the ParamArray attribute.
                        if (attr.GetType() == typeof(ParamArrayAttribute))
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has the ParamArray attribute.",
                                pInfo[0].Name, mInfo.Name);
                        // Check for the Description attribute.
                        else if (attr.GetType() ==
                            typeof(DescriptionAttribute)) {
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has a description attribute.",
                                pInfo[0].Name, mInfo.Name);
                            Console.WriteLine("The description is: \"{0}\"",
                                ((DescriptionAttribute)attr).Description);
                        }
                    }
                }
            }
        }
    }
}

/*
 * Output:
 * Parameter args for method ParamArrayAndDesc has the ParamArray attribute.
 * Parameter args for method ParamArrayAndDesc has a description attribute.
 * The description is: "This argument is a ParamArray"
 */

Comentarios

Si element representa un parámetro en un método de un tipo derivado, el valor devuelto incluye los atributos personalizados que se pueden heredar aplicados al mismo parámetro en los métodos base invalidados.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(MemberInfo, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Los parámetros especifican el miembro, el tipo del atributo personalizado que se va a buscar y si se van a buscar antecesores del miembro.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element, bool inherit);

Parámetros

element
MemberInfo

Objeto derivado de la clase MemberInfo que describe un constructor, evento, campo, método o miembro de propiedad de una clase.

inherit
Boolean

Si true, especifica también buscar los antecesores de element para los atributos personalizados.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

element no es un constructor, método, propiedad, evento, tipo o campo.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un MemberInfo como parámetro.

C#
using System;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;

namespace CustAttrs4CS
{

    // Define an enumeration of Win32 unmanaged types
    public enum UnmanagedType
    {
        User,
        GDI,
        Kernel,
        Shell,
        Networking,
        Multimedia
    }

    // Define the Unmanaged attribute.
    public class UnmanagedAttribute : Attribute
    {
        // Storage for the UnmanagedType value.
        protected UnmanagedType thisType;

        // Set the unmanaged type in the constructor.
        public UnmanagedAttribute(UnmanagedType type)
        {
            thisType = type;
        }

        // Define a property to get and set the UnmanagedType value.
        public UnmanagedType Win32Type
        {
            get { return thisType; }
            set { thisType = Win32Type; }
        }
    }

    // Create a class for an imported Win32 unmanaged function.
    public class Win32 {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type);
    }

    public class AClass {
        // Add some attributes to Win32CallMethod.
        [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
        [Unmanaged(UnmanagedType.User)]
        public void Win32CallMethod()
        {
            Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0);
        }
    }

    class DemoClass {
        static void Main(string[] args)
            {
            // Get the AClass type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for Win32CallMethod.
            MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
            if (mInfo != null)
            {
                // Iterate through all the attributes of the method.
                foreach(Attribute attr in
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the Obsolete attribute.
                    if (attr.GetType() == typeof(ObsoleteAttribute))
                    {
                        Console.WriteLine("Method {0} is obsolete. " +
                            "The message is:",
                            mInfo.Name);
                        Console.WriteLine("  \"{0}\"",
                            ((ObsoleteAttribute)attr).Message);
                    }

                    // Check for the Unmanaged attribute.
                    else if (attr.GetType() == typeof(UnmanagedAttribute))
                    {
                        Console.WriteLine(
                            "This method calls unmanaged code.");
                        Console.WriteLine(
                            String.Format("The Unmanaged attribute type is {0}.",
                                          ((UnmanagedAttribute)attr).Win32Type));
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    }
}

/*

This code example produces the following results.

First, the compilation yields the warning, "... This method is
obsolete. Use managed MsgBox instead."
Second, execution yields a message box with a title of "Caution!"
and message text of "This is an unmanaged call."
Third, the following text is displayed in the console window:

Method Win32CallMethod is obsolete. The message is:
  "This method is obsolete. Use managed MsgBox instead."
This method calls unmanaged code.
The Unmanaged attribute type is User.

*/

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element si inherit es true.

Nota

A partir de .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. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Assembly, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado y el tipo del atributo personalizado que se va a buscar.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Assembly element, Type attributeType);

Parámetros

element
Assembly

Objeto derivado de la clase Assembly que describe una colección reutilizable de módulos.

attributeType
Type

Tipo, o tipo base, del atributo personalizado que se va a buscar.

Devoluciones

Matriz Attribute que contiene los atributos personalizados de tipo attributeType aplicados a element, o una matriz vacía si no existen atributos personalizados.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Assembly como parámetro.

C#
using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

class Example {
    static void Main() {
        // Get the Assembly object to access its metadata.
        Assembly assy = typeof(Example).Assembly;

        // Iterate through the attributes for the assembly.
        foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
            // Check for the AssemblyTitle attribute.
            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                Console.WriteLine("Assembly title is \"{0}\".",
                    ((AssemblyTitleAttribute)attr).Title);

            // Check for the AssemblyDescription attribute.
            else if (attr.GetType() ==
                typeof(AssemblyDescriptionAttribute))
                Console.WriteLine("Assembly description is \"{0}\".",
                    ((AssemblyDescriptionAttribute)attr).Description);

            // Check for the AssemblyCompany attribute.
            else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                Console.WriteLine("Assembly company is {0}.",
                    ((AssemblyCompanyAttribute)attr).Company);
        }
   }
}
// The example displays the following output:
//     Assembly title is "CustAttrs1CS".
//     Assembly description is "GetCustomAttributes() Demo".
//     Assembly company is Microsoft.

Comentarios

Nota

A partir de la versión 2.0 de .NET Framework, este método devuelve atributos de seguridad si los atributos se almacenan en el nuevo formato de metadatos. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Assembly, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Los parámetros especifican el ensamblado y una opción de búsqueda omitida.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Assembly element, bool inherit);

Parámetros

element
Assembly

Objeto derivado de la clase Assembly que describe una colección reutilizable de módulos.

inherit
Boolean

Este parámetro se omite y no afecta al funcionamiento de este método.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Assembly como parámetro.

C#
using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

class Example {
    static void Main() {
        // Get the Assembly object to access its metadata.
        Assembly assy = typeof(Example).Assembly;

        // Iterate through the attributes for the assembly.
        foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
            // Check for the AssemblyTitle attribute.
            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                Console.WriteLine("Assembly title is \"{0}\".",
                    ((AssemblyTitleAttribute)attr).Title);

            // Check for the AssemblyDescription attribute.
            else if (attr.GetType() ==
                typeof(AssemblyDescriptionAttribute))
                Console.WriteLine("Assembly description is \"{0}\".",
                    ((AssemblyDescriptionAttribute)attr).Description);

            // Check for the AssemblyCompany attribute.
            else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                Console.WriteLine("Assembly company is {0}.",
                    ((AssemblyCompanyAttribute)attr).Company);
        }
   }
}
// The example displays the following output:
//     Assembly title is "CustAttrs1CS".
//     Assembly description is "GetCustomAttributes() Demo".
//     Assembly company is Microsoft.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(ParameterInfo)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un parámetro de método. Un parámetro especifica el parámetro de método.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.ParameterInfo element);

Parámetros

element
ParameterInfo

Objeto derivado de la clase ParameterInfo que describe un parámetro de un miembro de una clase.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un ParameterInfo como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

namespace CustAttrs5CS {
    public class AClass {
        public void ParamArrayAndDesc(
            // Add ParamArray (with the keyword) and Description attributes.
            [Description("This argument is a ParamArray")]
            params int[] args)
        {}
    }

    class DemoClass {
        static void Main(string[] args) {
            // Get the Class type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for the method.
            MethodInfo mInfo = clsType.GetMethod("ParamArrayAndDesc");
            if (mInfo != null) {
                // Get the parameter information.
                ParameterInfo[] pInfo = mInfo.GetParameters();
                if (pInfo != null) {
                    // Iterate through all the attributes for the parameter.
                    foreach(Attribute attr in
                        Attribute.GetCustomAttributes(pInfo[0])) {
                        // Check for the ParamArray attribute.
                        if (attr.GetType() == typeof(ParamArrayAttribute))
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has the ParamArray attribute.",
                                pInfo[0].Name, mInfo.Name);
                        // Check for the Description attribute.
                        else if (attr.GetType() ==
                            typeof(DescriptionAttribute)) {
                            Console.WriteLine("Parameter {0} for method {1} " +
                                "has a description attribute.",
                                pInfo[0].Name, mInfo.Name);
                            Console.WriteLine("The description is: \"{0}\"",
                                ((DescriptionAttribute)attr).Description);
                        }
                    }
                }
            }
        }
    }
}

/*
 * Output:
 * Parameter args for method ParamArrayAndDesc has the ParamArray attribute.
 * Parameter args for method ParamArrayAndDesc has a description attribute.
 * The description is: "This argument is a ParamArray"
 */

Comentarios

Si element representa un parámetro en un método de un tipo derivado, el valor devuelto incluye los atributos personalizados que se pueden heredar aplicados al mismo parámetro en los métodos base invalidados.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Module)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un módulo. Un parámetro especifica el módulo.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Module element);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portátil.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Module como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

// Assign some attributes to the module.
[module:Description("A sample description")]

// Set the module's CLSCompliant attribute to false
// The CLSCompliant attribute is applicable for /target:module.
[module:CLSCompliant(false)]

namespace CustAttrs2CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Module type to access its metadata.
            Module module = clsType.Module;

            // Iterate through all the attributes for the module.
            foreach(Attribute attr in Attribute.GetCustomAttributes(module)) {
                // Check for the Description attribute.
                if (attr.GetType() == typeof(DescriptionAttribute))
                    Console.WriteLine("Module {0} has the description " +
                        "\"{1}\".", module.Name,
                        ((DescriptionAttribute)attr).Description);
                // Check for the CLSCompliant attribute.
                else if (attr.GetType() == typeof(CLSCompliantAttribute))
                    Console.WriteLine("Module {0} {1} CLSCompliant.",
                        module.Name,
                        ((CLSCompliantAttribute)attr).IsCompliant ?
                            "is" : "is not");
            }
        }
    }
}

/*
 * Output:
 * Module CustAttrs2CS.exe is not CLSCompliant.
 * Module CustAttrs2CS.exe has the description "A sample description".
 */

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(MemberInfo)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un miembro de un tipo. Un parámetro especifica el miembro.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.MemberInfo element);

Parámetros

element
MemberInfo

Objeto derivado de la clase MemberInfo que describe un constructor, evento, campo, método o miembro de propiedad de una clase.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

element no es un constructor, método, propiedad, evento, tipo o campo.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttribute, tomando un MemberInfo como parámetro.

C#
using System;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;

namespace CustAttrs4CS
{

    // Define an enumeration of Win32 unmanaged types
    public enum UnmanagedType
    {
        User,
        GDI,
        Kernel,
        Shell,
        Networking,
        Multimedia
    }

    // Define the Unmanaged attribute.
    public class UnmanagedAttribute : Attribute
    {
        // Storage for the UnmanagedType value.
        protected UnmanagedType thisType;

        // Set the unmanaged type in the constructor.
        public UnmanagedAttribute(UnmanagedType type)
        {
            thisType = type;
        }

        // Define a property to get and set the UnmanagedType value.
        public UnmanagedType Win32Type
        {
            get { return thisType; }
            set { thisType = Win32Type; }
        }
    }

    // Create a class for an imported Win32 unmanaged function.
    public class Win32 {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type);
    }

    public class AClass {
        // Add some attributes to Win32CallMethod.
        [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
        [Unmanaged(UnmanagedType.User)]
        public void Win32CallMethod()
        {
            Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0);
        }
    }

    class DemoClass {
        static void Main(string[] args)
            {
            // Get the AClass type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for Win32CallMethod.
            MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
            if (mInfo != null)
            {
                // Iterate through all the attributes of the method.
                foreach(Attribute attr in
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the Obsolete attribute.
                    if (attr.GetType() == typeof(ObsoleteAttribute))
                    {
                        Console.WriteLine("Method {0} is obsolete. " +
                            "The message is:",
                            mInfo.Name);
                        Console.WriteLine("  \"{0}\"",
                            ((ObsoleteAttribute)attr).Message);
                    }

                    // Check for the Unmanaged attribute.
                    else if (attr.GetType() == typeof(UnmanagedAttribute))
                    {
                        Console.WriteLine(
                            "This method calls unmanaged code.");
                        Console.WriteLine(
                            String.Format("The Unmanaged attribute type is {0}.",
                                          ((UnmanagedAttribute)attr).Win32Type));
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    }
}

/*

This code example produces the following results.

First, the compilation yields the warning, "... This method is
obsolete. Use managed MsgBox instead."
Second, execution yields a message box with a title of "Caution!"
and message text of "This is an unmanaged call."
Third, the following text is displayed in the console window:

Method Win32CallMethod is obsolete. The message is:
  "This method is obsolete. Use managed MsgBox instead."
This method calls unmanaged code.
The Unmanaged attribute type is User.

*/

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element.

Nota

A partir de .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. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Assembly)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un ensamblado. Un parámetro especifica el ensamblado.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Assembly element);

Parámetros

element
Assembly

Objeto derivado de la clase Assembly que describe una colección reutilizable de módulos.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

Ejemplos

En el ejemplo siguiente se recuperan los atributos personalizados que se encuentran en el ensamblado actual.

C#
using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

class Example {
    static void Main() {
        // Get the Assembly object to access its metadata.
        Assembly assy = typeof(Example).Assembly;

        // Iterate through the attributes for the assembly.
        foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
            // Check for the AssemblyTitle attribute.
            if (attr.GetType() == typeof(AssemblyTitleAttribute))
                Console.WriteLine("Assembly title is \"{0}\".",
                    ((AssemblyTitleAttribute)attr).Title);

            // Check for the AssemblyDescription attribute.
            else if (attr.GetType() ==
                typeof(AssemblyDescriptionAttribute))
                Console.WriteLine("Assembly description is \"{0}\".",
                    ((AssemblyDescriptionAttribute)attr).Description);

            // Check for the AssemblyCompany attribute.
            else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                Console.WriteLine("Assembly company is {0}.",
                    ((AssemblyCompanyAttribute)attr).Company);
        }
   }
}
// The example displays the following output:
//     Assembly title is "CustAttrs1CS".
//     Assembly description is "GetCustomAttributes() Demo".
//     Assembly company is Microsoft.

Comentarios

Nota

A partir de la versión 2.0 de .NET Framework, este método devuelve atributos de seguridad si los atributos se almacenan en el nuevo formato de metadatos. Los ensamblados compilados con la versión 2.0 o posterior usan el nuevo formato. Los ensamblados dinámicos y los ensamblados compilados con versiones anteriores de .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

GetCustomAttributes(Module, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Recupera una matriz de los atributos personalizados aplicados a un módulo. Los parámetros especifican el módulo y una opción de búsqueda ignorada.

C#
public static Attribute[] GetCustomAttributes (System.Reflection.Module element, bool inherit);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portátil.

inherit
Boolean

Este parámetro se omite y no afecta al funcionamiento de este método.

Devoluciones

Matriz Attribute que contiene los atributos personalizados aplicados a elemento una matriz vacía si no existe ningún atributo personalizado.

Excepciones

element es null.

Ejemplos

En el ejemplo de código siguiente se muestra el uso de GetCustomAttributes, tomando un Module como parámetro.

C#
using System;
using System.Reflection;
using System.ComponentModel;

// Assign some attributes to the module.
[module:Description("A sample description")]

// Set the module's CLSCompliant attribute to false
// The CLSCompliant attribute is applicable for /target:module.
[module:CLSCompliant(false)]

namespace CustAttrs2CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Module type to access its metadata.
            Module module = clsType.Module;

            // Iterate through all the attributes for the module.
            foreach(Attribute attr in Attribute.GetCustomAttributes(module)) {
                // Check for the Description attribute.
                if (attr.GetType() == typeof(DescriptionAttribute))
                    Console.WriteLine("Module {0} has the description " +
                        "\"{1}\".", module.Name,
                        ((DescriptionAttribute)attr).Description);
                // Check for the CLSCompliant attribute.
                else if (attr.GetType() == typeof(CLSCompliantAttribute))
                    Console.WriteLine("Module {0} {1} CLSCompliant.",
                        module.Name,
                        ((CLSCompliantAttribute)attr).IsCompliant ?
                            "is" : "is not");
            }
        }
    }
}

/*
 * Output:
 * Module CustAttrs2CS.exe is not CLSCompliant.
 * Module CustAttrs2CS.exe has the description "A sample description".
 */

Comentarios

El valor devuelto contiene los atributos personalizados para los antecesores de element si inherit es true.

Se aplica a

.NET 9 e outras versións
Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1