Ler em inglês

Compartilhar via


Attribute.GetCustomAttributes Método

Definição

Recupera uma matriz dos atributos personalizados aplicados a um assembly, módulo, membro do tipo ou parâmetro de método.

Sobrecargas

GetCustomAttributes(ParameterInfo, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método e se os ancestrais do parâmetro de método devem ser pesquisados.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do membro.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do parâmetro de método.

GetCustomAttributes(Module, Type, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo, o tipo do atributo personalizado a ser pesquisado e uma opção de pesquisa ignorada.

GetCustomAttributes(MemberInfo, Type)

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro e o tipo do atributo personalizado a ser pesquisado.

GetCustomAttributes(Assembly, Type, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly, o tipo do atributo personalizado a ser pesquisado e uma opção de pesquisa ignorada.

GetCustomAttributes(Module, Type)

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo e o tipo do atributo personalizado a ser pesquisado.

GetCustomAttributes(ParameterInfo, Type)

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método e o tipo do atributo personalizado a ser pesquisado.

GetCustomAttributes(MemberInfo, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do membro.

GetCustomAttributes(Assembly, Type)

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly e o tipo do atributo personalizado a ser pesquisado.

GetCustomAttributes(Assembly, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly e uma opção de pesquisa ignorada.

GetCustomAttributes(ParameterInfo)

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Um parâmetro especifica o parâmetro do método.

GetCustomAttributes(Module)

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Um parâmetro especifica o módulo.

GetCustomAttributes(MemberInfo)

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Um parâmetro especifica o membro.

GetCustomAttributes(Assembly)

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Um parâmetro especifica o assembly.

GetCustomAttributes(Module, Boolean)

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo e uma opção de pesquisa ignorada.

GetCustomAttributes(ParameterInfo, Boolean)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método e se os ancestrais do parâmetro de método devem ser pesquisados.

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

Parâmetros

element
ParameterInfo

Um objeto derivado da classe ParameterInfo que descreve um parâmetro de um membro de uma classe.

inherit
Boolean

Se true, especifica também pesquisar os ancestrais de element em busca de atributos personalizados.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

A propriedade Member de element é null.

element é null.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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"
 */

Comentários

Se element representar um parâmetro em um método de um tipo derivado, o valor retornado incluirá os atributos personalizados herdáveis aplicados ao mesmo parâmetro nos métodos base substituídos.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do membro.

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

Um objeto derivado da classe MemberInfo que descreve um construtor, evento, campo, método ou membro de propriedade de uma classe.

typeattributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

inherit
Boolean

Se true, especifica também pesquisar os ancestrais de element em busca de atributos personalizados.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo type aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou type é null.

type não é derivado de Attribute.

element não é um construtor, método, propriedade, evento, tipo ou campo.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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.

*/

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element se inherit for true.

Observação

A partir do .NET Framework versão 2.0, esse método retorna atributos de segurança em métodos, construtores e tipos se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do parâmetro de método.

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

Parâmetros

element
ParameterInfo

Um objeto derivado da classe ParameterInfo que descreve um parâmetro de um membro de uma classe.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

inherit
Boolean

Se true, especifica também pesquisar os ancestrais de element em busca de atributos personalizados.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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"
 */

Comentários

Se element representar um parâmetro em um método de um tipo derivado, o valor retornado incluirá os atributos personalizados herdáveis aplicados ao mesmo parâmetro nos métodos base substituídos.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo, o tipo do atributo personalizado a ser pesquisado e uma opção de pesquisa ignorada.

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

Parâmetros

element
Module

Um objeto derivado da classe Module que descreve um arquivo executável portátil.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

inherit
Boolean

Esse parâmetro é ignorado e não afeta a operação desse método.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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".
 */

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element se inherit for true.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro e o tipo do atributo personalizado a ser pesquisado.

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

Um objeto derivado da classe MemberInfo que descreve um construtor, evento, campo, método ou membro de propriedade de uma classe.

typeattributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo type aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou type é null.

type não é derivado de Attribute.

element não é um construtor, método, propriedade, evento, tipo ou campo.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttribute, tomando um 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.

*/

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element.

Observação

A partir do .NET Framework versão 2.0, esse método retorna atributos de segurança em métodos, construtores e tipos se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly, o tipo do atributo personalizado a ser pesquisado e uma opção de pesquisa ignorada.

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

Parâmetros

element
Assembly

Um objeto derivado da classe Assembly que descreve uma coleção reutilizável de módulos.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

inherit
Boolean

Esse parâmetro é ignorado e não afeta a operação desse método.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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.

Comentários

Observação

A partir do .NET Framework versão 2.0, esse método retornará atributos de segurança se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo e o tipo do atributo personalizado a ser pesquisado.

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

Parâmetros

element
Module

Um objeto derivado da classe Module que descreve um arquivo executável portátil.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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".
 */

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Os parâmetros especificam o parâmetro do método e o tipo do atributo personalizado a ser pesquisado.

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

Parâmetros

element
ParameterInfo

Um objeto derivado da classe ParameterInfo que descreve um parâmetro de um membro de uma classe.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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"
 */

Comentários

Se element representar um parâmetro em um método de um tipo derivado, o valor retornado incluirá os atributos personalizados herdáveis aplicados ao mesmo parâmetro nos métodos base substituídos.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Os parâmetros especificam o membro, o tipo do atributo personalizado a ser pesquisado e se deseja pesquisar ancestrais do membro.

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

Parâmetros

element
MemberInfo

Um objeto derivado da classe MemberInfo que descreve um construtor, evento, campo, método ou membro de propriedade de uma classe.

inherit
Boolean

Se true, especifica também pesquisar os ancestrais de element em busca de atributos personalizados.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

element não é um construtor, método, propriedade, evento, tipo ou campo.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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.

*/

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element se inherit for true.

Observação

A partir do .NET Framework versão 2.0, esse método retorna atributos de segurança em métodos, construtores e tipos se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly e o tipo do atributo personalizado a ser pesquisado.

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

Parâmetros

element
Assembly

Um objeto derivado da classe Assembly que descreve uma coleção reutilizável de módulos.

attributeType
Type

O tipo, ou um tipo base, do atributo personalizado a ser pesquisado.

Retornos

Uma matriz Attribute que contém os atributos personalizados do tipo attributeType aplicados a elementou uma matriz vazia se não existirem tais atributos personalizados.

Exceções

element ou attributeType é null.

attributeType não é derivado de Attribute.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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.

Comentários

Observação

A partir do .NET Framework versão 2.0, esse método retornará atributos de segurança se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Os parâmetros especificam o assembly e uma opção de pesquisa ignorada.

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

Parâmetros

element
Assembly

Um objeto derivado da classe Assembly que descreve uma coleção reutilizável de módulos.

inherit
Boolean

Esse parâmetro é ignorado e não afeta a operação desse método.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um parâmetro de método. Um parâmetro especifica o parâmetro do método.

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

Parâmetros

element
ParameterInfo

Um objeto derivado da classe ParameterInfo que descreve um parâmetro de um membro de uma classe.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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"
 */

Comentários

Se element representar um parâmetro em um método de um tipo derivado, o valor retornado incluirá os atributos personalizados herdáveis aplicados ao mesmo parâmetro nos métodos base substituídos.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Um parâmetro especifica o módulo.

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

Parâmetros

element
Module

Um objeto derivado da classe Module que descreve um arquivo executável portátil.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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".
 */

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um membro de um tipo. Um parâmetro especifica o membro.

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

Parâmetros

element
MemberInfo

Um objeto derivado da classe MemberInfo que descreve um construtor, evento, campo, método ou membro de propriedade de uma classe.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

element não é um construtor, método, propriedade, evento, tipo ou campo.

Não é possível carregar um tipo de atributo personalizado.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttribute, tomando um 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.

*/

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element.

Observação

A partir do .NET Framework versão 2.0, esse método retorna atributos de segurança em métodos, construtores e tipos se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um assembly. Um parâmetro especifica o assembly.

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

Parâmetros

element
Assembly

Um objeto derivado da classe Assembly que descreve uma coleção reutilizável de módulos.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

Exemplos

O exemplo a seguir recupera os atributos personalizados encontrados no assembly atual.

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.

Comentários

Observação

A partir do .NET Framework versão 2.0, esse método retornará atributos de segurança se os atributos forem armazenados no novo formato de metadados. Assemblies compilados com a versão 2.0 ou posterior usam o novo formato. Assemblies e assemblies dinâmicos compilados com versões anteriores do .NET Framework usam o formato XML antigo. Consulte emitindo atributos de segurança declarativa.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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)

Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs
Origem:
Attribute.CoreCLR.cs

Recupera uma matriz dos atributos personalizados aplicados a um módulo. Os parâmetros especificam o módulo e uma opção de pesquisa ignorada.

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

Parâmetros

element
Module

Um objeto derivado da classe Module que descreve um arquivo executável portátil.

inherit
Boolean

Esse parâmetro é ignorado e não afeta a operação desse método.

Retornos

Uma matriz Attribute que contém os atributos personalizados aplicados a elementou uma matriz vazia se nenhum atributo personalizado existir.

Exceções

element é null.

Exemplos

O exemplo de código a seguir demonstra o uso de GetCustomAttributes, tomando um 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".
 */

Comentários

O valor retornado contém os atributos personalizados para ancestrais de element se inherit for true.

Aplica-se a

.NET 9 e outras versões
Produto Versões
.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