Leggere in inglese

Condividi tramite


Attribute.GetCustomAttributes Metodo

Definizione

Recupera una matrice degli attributi personalizzati applicati a un assembly, un modulo, un membro di tipo o un parametro del metodo.

Overload

GetCustomAttributes(ParameterInfo, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e se cercare i predecessori del parametro del metodo.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del parametro del metodo.

GetCustomAttributes(Module, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttributes(MemberInfo, Type)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(Assembly, Type, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

GetCustomAttributes(Module, Type)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(ParameterInfo, Type)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(MemberInfo, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

GetCustomAttributes(Assembly, Type)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e il tipo dell'attributo personalizzato da cercare.

GetCustomAttributes(Assembly, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e un'opzione di ricerca ignorata.

GetCustomAttributes(ParameterInfo)

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. Un parametro specifica il parametro del metodo.

GetCustomAttributes(Module)

Recupera una matrice degli attributi personalizzati applicati a un modulo. Un parametro specifica il modulo.

GetCustomAttributes(MemberInfo)

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. Un parametro specifica il membro.

GetCustomAttributes(Assembly)

Recupera una matrice degli attributi personalizzati applicati a un assembly. Un parametro specifica l'assembly.

GetCustomAttributes(Module, Boolean)

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e un'opzione di ricerca ignorata.

GetCustomAttributes(ParameterInfo, Boolean)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e se cercare i predecessori del parametro del metodo.

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

Parametri

element
ParameterInfo

Oggetto derivato dalla classe ParameterInfo che descrive un parametro di un membro di una classe.

inherit
Boolean

Se true, specifica anche di cercare gli attributi personalizzati nei predecessori di element.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

La proprietà Member di element è null.

element è null.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un ParameterInfo come parametro.

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"
 */

Commenti

Se element rappresenta un parametro in un metodo di un tipo derivato, il valore restituito include gli attributi personalizzati ereditabili applicati allo stesso parametro nei metodi di base sottoposti a override.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

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

Parametri

element
MemberInfo

Oggetto derivato dalla classe MemberInfo che descrive un costruttore, un evento, un campo, un metodo o un membro della proprietà di una classe.

typeattributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

inherit
Boolean

Se true, specifica anche di cercare gli attributi personalizzati nei predecessori di element.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo type applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o type è null.

type non deriva da Attribute.

element non è un costruttore, un metodo, una proprietà, un evento, un tipo o un campo.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un MemberInfo come parametro.

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.

*/

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element se inherit è true.

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del parametro del metodo.

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

Parametri

element
ParameterInfo

Oggetto derivato dalla classe ParameterInfo che descrive un parametro di un membro di una classe.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

inherit
Boolean

Se true, specifica anche di cercare gli attributi personalizzati nei predecessori di element.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un ParameterInfo come parametro.

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"
 */

Commenti

Se element rappresenta un parametro in un metodo di un tipo derivato, il valore restituito include gli attributi personalizzati ereditabili applicati allo stesso parametro nei metodi di base sottoposti a override.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

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

Parametri

element
Module

Oggetto derivato dalla classe Module che descrive un file eseguibile portabile.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

inherit
Boolean

Questo parametro viene ignorato e non influisce sull'operazione di questo metodo.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Module come parametro.

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".
 */

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element se inherit è true.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro e il tipo dell'attributo personalizzato da cercare.

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

Parametri

element
MemberInfo

Oggetto derivato dalla classe MemberInfo che descrive un costruttore, un evento, un campo, un metodo o un membro della proprietà di una classe.

typeattributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo type applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o type è null.

type non deriva da Attribute.

element non è un costruttore, un metodo, una proprietà, un evento, un tipo o un campo.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttribute, accettando un MemberInfo come parametro.

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.

*/

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element.

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly, il tipo dell'attributo personalizzato da cercare e un'opzione di ricerca ignorata.

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

Parametri

element
Assembly

Oggetto derivato dalla classe Assembly che descrive una raccolta riutilizzabile di moduli.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

inherit
Boolean

Questo parametro viene ignorato e non influisce sull'operazione di questo metodo.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Assembly come parametro.

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.

Commenti

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce gli attributi di sicurezza se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e il tipo dell'attributo personalizzato da cercare.

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

Parametri

element
Module

Oggetto derivato dalla classe Module che descrive un file eseguibile portabile.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Module come parametro.

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".
 */

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. I parametri specificano il parametro del metodo e il tipo dell'attributo personalizzato da cercare.

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

Parametri

element
ParameterInfo

Oggetto derivato dalla classe ParameterInfo che descrive un parametro di un membro di una classe.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un ParameterInfo come parametro.

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"
 */

Commenti

Se element rappresenta un parametro in un metodo di un tipo derivato, il valore restituito include gli attributi personalizzati ereditabili applicati allo stesso parametro nei metodi di base sottoposti a override.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. I parametri specificano il membro, il tipo dell'attributo personalizzato da cercare e se cercare i predecessori del membro.

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

Parametri

element
MemberInfo

Oggetto derivato dalla classe MemberInfo che descrive un costruttore, un evento, un campo, un metodo o un membro della proprietà di una classe.

inherit
Boolean

Se true, specifica anche di cercare gli attributi personalizzati nei predecessori di element.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

element non è un costruttore, un metodo, una proprietà, un evento, un tipo o un campo.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un MemberInfo come parametro.

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.

*/

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element se inherit è true.

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e il tipo dell'attributo personalizzato da cercare.

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

Parametri

element
Assembly

Oggetto derivato dalla classe Assembly che descrive una raccolta riutilizzabile di moduli.

attributeType
Type

Tipo, o tipo di base, dell'attributo personalizzato da cercare.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati di tipo attributeType applicati a elemento una matrice vuota se non esistono attributi personalizzati di questo tipo.

Eccezioni

element o attributeType è null.

attributeType non deriva da Attribute.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Assembly come parametro.

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.

Commenti

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce gli attributi di sicurezza se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un assembly. I parametri specificano l'assembly e un'opzione di ricerca ignorata.

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

Parametri

element
Assembly

Oggetto derivato dalla classe Assembly che descrive una raccolta riutilizzabile di moduli.

inherit
Boolean

Questo parametro viene ignorato e non influisce sull'operazione di questo metodo.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Assembly come parametro.

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.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un parametro del metodo. Un parametro specifica il parametro del metodo.

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

Parametri

element
ParameterInfo

Oggetto derivato dalla classe ParameterInfo che descrive un parametro di un membro di una classe.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un ParameterInfo come parametro.

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"
 */

Commenti

Se element rappresenta un parametro in un metodo di un tipo derivato, il valore restituito include gli attributi personalizzati ereditabili applicati allo stesso parametro nei metodi di base sottoposti a override.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un modulo. Un parametro specifica il modulo.

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

Parametri

element
Module

Oggetto derivato dalla classe Module che descrive un file eseguibile portabile.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Module come parametro.

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".
 */

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un membro di un tipo. Un parametro specifica il membro.

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

Parametri

element
MemberInfo

Oggetto derivato dalla classe MemberInfo che descrive un costruttore, un evento, un campo, un metodo o un membro della proprietà di una classe.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

element non è un costruttore, un metodo, una proprietà, un evento, un tipo o un campo.

Non è possibile caricare un tipo di attributo personalizzato.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttribute, accettando un MemberInfo come parametro.

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.

*/

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element.

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce attributi di sicurezza per metodi, costruttori e tipi se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un assembly. Un parametro specifica l'assembly.

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

Parametri

element
Assembly

Oggetto derivato dalla classe Assembly che descrive una raccolta riutilizzabile di moduli.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

Esempio

Nell'esempio seguente vengono recuperati gli attributi personalizzati trovati nell'assembly corrente.

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.

Commenti

Nota

A partire da .NET Framework versione 2.0, questo metodo restituisce gli attributi di sicurezza se gli attributi vengono archiviati nel nuovo formato di metadati. Gli assembly compilati con la versione 2.0 o successiva usano il nuovo formato. Gli assembly dinamici e gli assembly compilati con le versioni precedenti di .NET Framework usano il formato XML precedente. Vedere creazione di attributi di sicurezza dichiarativi.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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)

Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs
Origine:
Attribute.CoreCLR.cs

Recupera una matrice degli attributi personalizzati applicati a un modulo. I parametri specificano il modulo e un'opzione di ricerca ignorata.

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

Parametri

element
Module

Oggetto derivato dalla classe Module che descrive un file eseguibile portabile.

inherit
Boolean

Questo parametro viene ignorato e non influisce sull'operazione di questo metodo.

Restituisce

Matrice Attribute che contiene gli attributi personalizzati applicati a elemento una matrice vuota se tali attributi personalizzati non esistono.

Eccezioni

element è null.

Esempio

Nell'esempio di codice seguente viene illustrato l'uso di GetCustomAttributes, accettando un Module come parametro.

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".
 */

Commenti

Il valore restituito contiene gli attributi personalizzati per i predecessori di element se inherit è true.

Si applica a

.NET 9 e altre versioni
Prodotto Versioni
.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