Leer en inglés

Compartir a través de


Attribute.GetCustomAttribute Método

Definición

Recupera un atributo personalizado de un tipo especificado aplicado a un ensamblado, módulo, miembro de tipo o parámetro de método.

Sobrecargas

GetCustomAttribute(ParameterInfo, Type, Boolean)

Recupera un atributo personalizado aplicado 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 deben buscar los antecesores del parámetro de método.

GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera un atributo personalizado aplicado 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 deben buscar los antecesores del miembro.

GetCustomAttribute(Assembly, Type, Boolean)

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

GetCustomAttribute(Module, Type, Boolean)

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

GetCustomAttribute(Module, Type)

Recupera un atributo personalizado aplicado a un módulo. Los parámetros especifican el módulo y el tipo del atributo personalizado que se va a buscar.

GetCustomAttribute(MemberInfo, Type)

Recupera un atributo personalizado aplicado a un miembro de un tipo. Los parámetros especifican el miembro y el tipo del atributo personalizado que se va a buscar.

GetCustomAttribute(Assembly, Type)

Recupera un atributo personalizado aplicado a un ensamblado especificado. Los parámetros especifican el ensamblado y el tipo del atributo personalizado que se va a buscar.

GetCustomAttribute(ParameterInfo, Type)

Recupera un atributo personalizado aplicado 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.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Recupera un atributo personalizado aplicado 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 deben buscar los antecesores del parámetro de método.

C#
public static Attribute? GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType, bool inherit);
C#
public static Attribute GetCustomAttribute (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 es true, especifica que se busquen también los atributos personalizados de los antecesores de element.

Devoluciones

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se define una clase de parámetro Attribute personalizada y se aplica el atributo personalizado a un método de una clase derivada y la base de la clase derivada. En el GetCustomAttribute ejemplo se muestra el uso del método para devolver los atributos.

C#
// Example for the Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
// method.
using System;
using System.Reflection;

namespace NDP_UE_CS
{
    // Define a custom parameter attribute that takes a single message argument.
    [AttributeUsage( AttributeTargets.Parameter )]
    public class ArgumentUsageAttribute : Attribute
    {
        // This is the attribute constructor.
        public ArgumentUsageAttribute( string UsageMsg )
        {
            this.usageMsg = UsageMsg;
        }

        // usageMsg is storage for the attribute message.
        protected string usageMsg;

        // This is the Message property for the attribute.
        public string Message
        {
            get { return usageMsg; }
            set { usageMsg = value; }
        }
    }

    public class BaseClass
    {
        // Assign an ArgumentUsage attribute to the strArray parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public virtual void TestMethod(
            [ArgumentUsage("Must pass an array here.")]
            String[] strArray,
            params String[] strList)
        { }
    }

    public class DerivedClass : BaseClass
    {
        // Assign an ArgumentUsage attribute to the strList parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public override void TestMethod(
            String[] strArray,
            [ArgumentUsage("Can pass a parameter list or array here.")]
            params String[] strList)
        { }
    }

    class CustomParamDemo
    {
        static void Main( )
        {
            Console.WriteLine(
                "This example of Attribute.GetCustomAttribute( Parameter" +
                "Info, Type, Boolean )\ngenerates the following output." );

            // Get the class type, and then get the MethodInfo object
            // for TestMethod to access its metadata.
            Type clsType = typeof(DerivedClass);
            MethodInfo mInfo = clsType.GetMethod("TestMethod");

            // Iterate through the ParameterInfo array for the method parameters.
            ParameterInfo[] pInfoArray = mInfo.GetParameters();
            if (pInfoArray != null)
            {
                DisplayParameterAttributes( mInfo, pInfoArray, false );
                DisplayParameterAttributes( mInfo, pInfoArray, true );
            }
            else
                Console.WriteLine("The parameters information could " +
                    "not be retrieved for method {0}.", mInfo.Name);
        }

        static void DisplayParameterAttributes( MethodInfo mInfo,
            ParameterInfo[] pInfoArray, bool includeInherited )
        {
            Console.WriteLine(
                "\nParameter attribute information for method \"" +
                "{0}\"\nincludes inheritance from base class: {1}.",
                mInfo.Name, includeInherited ? "Yes" : "No" );

            // Display the attribute information for the parameters.
            foreach( ParameterInfo paramInfo in pInfoArray )
            {
                // See if the ParamArray attribute is defined.
                bool isDef = Attribute.IsDefined( paramInfo,
                    typeof(ParamArrayAttribute));

                if( isDef )
                    Console.WriteLine(
                        "\n    The ParamArray attribute is defined " +
                        "for \n    parameter {0} of method {1}.",
                        paramInfo.Name, mInfo.Name);

                // See if ParamUsageAttribute is defined.
                // If so, display a message.
                ArgumentUsageAttribute usageAttr = (ArgumentUsageAttribute)
                    Attribute.GetCustomAttribute( paramInfo,
                        typeof(ArgumentUsageAttribute),
                        includeInherited );

                if( usageAttr != null )
                {
                    Console.WriteLine(
                        "\n    The ArgumentUsage attribute is def" +
                        "ined for \n    parameter {0} of method {1}.",
                        paramInfo.Name, mInfo.Name );

                    Console.WriteLine( "\n        The usage " +
                        "message for {0} is:\n        \"{1}\".",
                        paramInfo.Name, usageAttr.Message);
                }
            }
        }
    }
}

/*
This example of Attribute.GetCustomAttribute( ParameterInfo, Type, Boolean )
generates the following output.

Parameter attribute information for method "TestMethod"
includes inheritance from base class: No.

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".

Parameter attribute information for method "TestMethod"
includes inheritance from base class: Yes.

    The ArgumentUsage attribute is defined for
    parameter strArray of method TestMethod.

        The usage message for strArray is:
        "Must pass an array here.".

    The ParamArray attribute is defined for
    parameter strList of method TestMethod.

    The ArgumentUsage attribute is defined for
    parameter strList of method TestMethod.

        The usage message for strList is:
        "Can pass a parameter list or array here.".
*/

Comentarios

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

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera un atributo personalizado aplicado 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 deben buscar los antecesores del miembro.

C#
public static Attribute? GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType, bool inherit);
C#
public static Attribute GetCustomAttribute (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.

attributeType
Type

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

inherit
Boolean

Si es true, especifica que se busquen también los atributos personalizados de los antecesores de element.

Devoluciones

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

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

Se ha encontrado más de un atributo de los atributos solicitados.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como MemberInfo parámetro .

C#
using System;
using System.Reflection;

namespace IsDef4CS
{
    public class TestClass
    {
        // Assign the Obsolete attribute to a method.
        [Obsolete("This method is obsolete. Use Method2 instead.")]
        public void Method1()
        {}
        public void Method2()
        {}
    }

    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(TestClass);
            // Get the MethodInfo object for Method1.
            MethodInfo mInfo = clsType.GetMethod("Method1");
            // See if the Obsolete attribute is defined for this method.
            bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute));
            // Display the result.
            Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.",
                isDef ? "is" : "is not", mInfo.Name, clsType.Name);
            // If it's defined, display the attribute's message.
            if (isDef)
            {
                ObsoleteAttribute obsAttr =
                                 (ObsoleteAttribute)Attribute.GetCustomAttribute(
                                                    mInfo, typeof(ObsoleteAttribute));
                if (obsAttr != null)
                    Console.WriteLine("The message is: \"{0}\".",
                        obsAttr.Message);
                else
                    Console.WriteLine("The message could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */

Comentarios

Nota

A partir de la versión 2.0 de .NET Framework, este método devuelve atributos de seguridad en tipos, métodos y constructores 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 del .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(Assembly, Type, Boolean)

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

C#
public static Attribute? GetCustomAttribute (System.Reflection.Assembly element, Type attributeType, bool inherit);
C#
public static Attribute GetCustomAttribute (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

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como Assembly parámetro .

C#
using System;
using System.Reflection;

// Add an AssemblyDescription attribute
[assembly: AssemblyDescription("A sample description")]
namespace IsDef1CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // Get the assembly object.
            Assembly assy = clsType.Assembly;
            // Store the assembly's name.
            String assyName = assy.GetName().Name;
            // See if the Assembly Description is defined.
            bool isdef = Attribute.IsDefined(assy,
                typeof(AssemblyDescriptionAttribute));
            if (isdef)
            {
                // Affirm that the attribute is defined.
                Console.WriteLine("The AssemblyDescription attribute " +
                    "is defined for assembly {0}.", assyName);
                // Get the description attribute itself.
                AssemblyDescriptionAttribute adAttr =
                    (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
                    assy, typeof(AssemblyDescriptionAttribute));
                // Display the description.
                if (adAttr != null)
                    Console.WriteLine("The description is \"{0}\".",
                        adAttr.Description);
                else
                    Console.WriteLine("The description could not " +
                        "be retrieved.");
            }
            else
                Console.WriteLine("The AssemblyDescription attribute is not " +
                    "defined for assembly {0}.", assyName);
        }
    }
}

/*
 * Output:
 * The AssemblyDescription attribute is defined for assembly IsDef1CS.
 * The description is "A sample description".
 */

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 del .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(Module, Type, Boolean)

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

C#
public static Attribute? GetCustomAttribute (System.Reflection.Module element, Type attributeType, bool inherit);
C#
public static Attribute GetCustomAttribute (System.Reflection.Module element, Type attributeType, bool inherit);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portable.

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

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como Module parámetro .

C#
using System;
using System.Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true, false)]
namespace IsDef2CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // See if the Debuggable attribute is defined for this module.
            bool isDef = Attribute.IsDefined(clsType.Module,
                typeof(DebuggableAttribute));
            // Display the result.
            Console.WriteLine("The Debuggable attribute {0} " +
                "defined for Module {1}.",
                isDef ? "is" : "is not",
                clsType.Module.Name);
            // If the attribute is defined, display the JIT settings.
            if (isDef)
            {
                // Retrieve the attribute itself.
                DebuggableAttribute dbgAttr = (DebuggableAttribute)
                    Attribute.GetCustomAttribute(clsType.Module,
                    typeof(DebuggableAttribute));
                if (dbgAttr != null)
                {
                    Console.WriteLine("JITTrackingEnabled is {0}.",
                        dbgAttr.IsJITTrackingEnabled);
                    Console.WriteLine("JITOptimizerDisabled is {0}.",
                        dbgAttr.IsJITOptimizerDisabled);
                }
                else
                    Console.WriteLine("The Debuggable attribute " +
                        "could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(Module, Type)

Recupera un atributo personalizado aplicado 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? GetCustomAttribute (System.Reflection.Module element, Type attributeType);
C#
public static Attribute GetCustomAttribute (System.Reflection.Module element, Type attributeType);

Parámetros

element
Module

Objeto derivado de la clase Module que describe un archivo ejecutable portable.

attributeType
Type

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

Devoluciones

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como Module parámetro .

C#
using System;
using System.Diagnostics;

// Add the Debuggable attribute to the module.
[module:Debuggable(true, false)]
namespace IsDef2CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // See if the Debuggable attribute is defined for this module.
            bool isDef = Attribute.IsDefined(clsType.Module,
                typeof(DebuggableAttribute));
            // Display the result.
            Console.WriteLine("The Debuggable attribute {0} " +
                "defined for Module {1}.",
                isDef ? "is" : "is not",
                clsType.Module.Name);
            // If the attribute is defined, display the JIT settings.
            if (isDef)
            {
                // Retrieve the attribute itself.
                DebuggableAttribute dbgAttr = (DebuggableAttribute)
                    Attribute.GetCustomAttribute(clsType.Module,
                    typeof(DebuggableAttribute));
                if (dbgAttr != null)
                {
                    Console.WriteLine("JITTrackingEnabled is {0}.",
                        dbgAttr.IsJITTrackingEnabled);
                    Console.WriteLine("JITOptimizerDisabled is {0}.",
                        dbgAttr.IsJITOptimizerDisabled);
                }
                else
                    Console.WriteLine("The Debuggable attribute " +
                        "could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Debuggable attribute is defined for Module IsDef2CS.exe.
 * JITTrackingEnabled is True.
 * JITOptimizerDisabled is False.
 */

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(MemberInfo, Type)

Recupera un atributo personalizado aplicado 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? GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType);
C#
public static Attribute GetCustomAttribute (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.

attributeType
Type

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

Devoluciones

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

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

Se ha encontrado más de un atributo de los atributos solicitados.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como MemberInfo parámetro .

C#
using System;
using System.Reflection;

namespace IsDef4CS
{
    public class TestClass
    {
        // Assign the Obsolete attribute to a method.
        [Obsolete("This method is obsolete. Use Method2 instead.")]
        public void Method1()
        {}
        public void Method2()
        {}
    }

    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(TestClass);
            // Get the MethodInfo object for Method1.
            MethodInfo mInfo = clsType.GetMethod("Method1");
            // See if the Obsolete attribute is defined for this method.
            bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute));
            // Display the result.
            Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.",
                isDef ? "is" : "is not", mInfo.Name, clsType.Name);
            // If it's defined, display the attribute's message.
            if (isDef)
            {
                ObsoleteAttribute obsAttr =
                                 (ObsoleteAttribute)Attribute.GetCustomAttribute(
                                                    mInfo, typeof(ObsoleteAttribute));
                if (obsAttr != null)
                    Console.WriteLine("The message is: \"{0}\".",
                        obsAttr.Message);
                else
                    Console.WriteLine("The message could not be retrieved.");
            }
        }
    }
}

/*
 * Output:
 * The Obsolete Attribute is defined for Method1 of class TestClass.
 * The message is: "This method is obsolete. Use Method2 instead.".
 */

Comentarios

Una coincidencia se determina de la misma manera que se describe en la sección Valor devuelto de Type.IsAssignableFrom.

Nota

A partir de la versión 2.0 de .NET Framework, este método devuelve atributos de seguridad en tipos, métodos y constructores 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 del .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(Assembly, Type)

Recupera un atributo personalizado aplicado a un ensamblado especificado. Los parámetros especifican el ensamblado y el tipo del atributo personalizado que se va a buscar.

C#
public static Attribute? GetCustomAttribute (System.Reflection.Assembly element, Type attributeType);
C#
public static Attribute GetCustomAttribute (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

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del GetCustomAttribute método que toma como Assembly parámetro .

C#
using System;
using System.Reflection;

// Add an AssemblyDescription attribute
[assembly: AssemblyDescription("A sample description")]
namespace IsDef1CS
{
    public class DemoClass
    {
        static void Main(string[] args)
        {
            // Get the class type to access its metadata.
            Type clsType = typeof(DemoClass);
            // Get the assembly object.
            Assembly assy = clsType.Assembly;
            // Store the assembly's name.
            String assyName = assy.GetName().Name;
            // See if the Assembly Description is defined.
            bool isdef = Attribute.IsDefined(assy,
                typeof(AssemblyDescriptionAttribute));
            if (isdef)
            {
                // Affirm that the attribute is defined.
                Console.WriteLine("The AssemblyDescription attribute " +
                    "is defined for assembly {0}.", assyName);
                // Get the description attribute itself.
                AssemblyDescriptionAttribute adAttr =
                    (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
                    assy, typeof(AssemblyDescriptionAttribute));
                // Display the description.
                if (adAttr != null)
                    Console.WriteLine("The description is \"{0}\".",
                        adAttr.Description);
                else
                    Console.WriteLine("The description could not " +
                        "be retrieved.");
            }
            else
                Console.WriteLine("The AssemblyDescription attribute is not " +
                    "defined for assembly {0}.", assyName);
        }
    }
}

/*
 * Output:
 * The AssemblyDescription attribute is defined for assembly IsDef1CS.
 * The description is "A sample description".
 */

Comentarios

Use el GetCustomAttributes método si espera que se devuelva más de un valor o AmbiguousMatchException se producirá.

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 del .NET Framework usan el formato XML antiguo. Consulte Emisión de atributos de seguridad declarativos.

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1

GetCustomAttribute(ParameterInfo, Type)

Recupera un atributo personalizado aplicado 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? GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType);
C#
public static Attribute GetCustomAttribute (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

Attribute

Referencia al atributo personalizado único de tipo attributeType que se aplica a element, o null si no existe dicho atributo.

Excepciones

element o attributeType es null.

attributeType no se deriva de Attribute.

Se ha encontrado más de un atributo de los atributos solicitados.

No se puede cargar un tipo de atributo personalizado.

Ejemplos

En el ejemplo de código siguiente se define una clase de parámetro Attribute personalizada y se aplica el atributo personalizado a un método de una clase derivada y la base de la clase derivada. En el GetCustomAttribute ejemplo se muestra el uso del método para devolver los atributos.

C#
// Example for the Attribute.GetCustomAttribute( ParameterInfo, Type ) method.
using System;
using System.Reflection;

namespace NDP_UE_CS
{
    // Define a custom parameter attribute that takes a single message argument.
    [AttributeUsage( AttributeTargets.Parameter )]
    public class ArgumentUsageAttribute : Attribute
    {
        // This is the attribute constructor.
        public ArgumentUsageAttribute( string UsageMsg )
        {
            this.usageMsg = UsageMsg;
        }

        // usageMsg is storage for the attribute message.
        protected string usageMsg;

        // This is the Message property for the attribute.
        public string Message
        {
            get { return usageMsg; }
            set { usageMsg = value; }
        }
    }

    public class BaseClass
    {
        // Assign an ArgumentUsage attribute to the strArray parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public virtual void TestMethod(
            [ArgumentUsage("Must pass an array here.")]
            String[] strArray,
            params String[] strList)
        { }
    }

    public class DerivedClass : BaseClass
    {
        // Assign an ArgumentUsage attribute to the strList parameter.
        // Assign a ParamArray attribute to strList using the params keyword.
        public override void TestMethod(
            String[] strArray,
            [ArgumentUsage("Can pass a parameter list or array here.")]
            params String[] strList)
        { }
    }

    class CustomParamDemo
    {
        static void Main( )
        {
            Console.WriteLine(
                "This example of Attribute.GetCustomAttribute( Param" +
                "eterInfo, Type )\ngenerates the following output." );

            // Get the class type, and then get the MethodInfo object
            // for TestMethod to access its metadata.
            Type clsType = typeof( DerivedClass );
            MethodInfo mInfo = clsType.GetMethod("TestMethod");

            // Iterate through the ParameterInfo array for the method parameters.
            ParameterInfo[] pInfoArray = mInfo.GetParameters();
            if (pInfoArray != null)
            {
                foreach( ParameterInfo paramInfo in pInfoArray )
                {
                    // See if the ParamArray attribute is defined.
                    bool isDef = Attribute.IsDefined(
                        paramInfo, typeof(ParamArrayAttribute));

                    if( isDef )
                        Console.WriteLine(
                            "\nThe ParamArray attribute is defined " +
                            "for \nparameter {0} of method {1}.",
                            paramInfo.Name, mInfo.Name);

                    // See if ParamUsageAttribute is defined.
                    // If so, display a message.
                    ArgumentUsageAttribute usageAttr = (ArgumentUsageAttribute)
                        Attribute.GetCustomAttribute(
                            paramInfo, typeof(ArgumentUsageAttribute) );

                    if( usageAttr != null )
                    {
                        Console.WriteLine(
                            "\nThe ArgumentUsage attribute is defined " +
                            "for \nparameter {0} of method {1}.",
                            paramInfo.Name, mInfo.Name );

                        Console.WriteLine( "\n    The usage " +
                            "message for {0} is:\n    \"{1}\".",
                            paramInfo.Name, usageAttr.Message);
                    }
                }
            }
            else
                Console.WriteLine(
                    "The parameters information could not " +
                    "be retrieved for method {0}.", mInfo.Name);
        }
    }
}

/*
This example of Attribute.GetCustomAttribute( ParameterInfo, Type )
generates the following output.

The ArgumentUsage attribute is defined for
parameter strArray of method TestMethod.

    The usage message for strArray is:
    "Must pass an array here.".

The ParamArray attribute is defined for
parameter strList of method TestMethod.

The ArgumentUsage attribute is defined for
parameter strList of method TestMethod.

    The usage message for strList is:
    "Can pass a parameter list or array here.".
*/

Comentarios

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

Se aplica a

.NET 7 y otras versiones
Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.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
.NET Standard 2.0, 2.1