Прочитать на английском

Поделиться через


Attribute.GetCustomAttributes Метод

Определение

Извлекает массив настраиваемых атрибутов, применяемых к сборке, модулю, элементу типа или параметру метода.

Перегрузки

GetCustomAttributes(ParameterInfo, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода и следует ли выполнять поиск предков параметра метода.

GetCustomAttributes(MemberInfo, Type, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент, тип настраиваемого атрибута для поиска и поиск предков элемента.

GetCustomAttributes(ParameterInfo, Type, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода, тип настраиваемого атрибута для поиска и поиск предков параметра метода.

GetCustomAttributes(Module, Type, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль, тип настраиваемого атрибута для поиска и игнорируемый параметр поиска.

GetCustomAttributes(MemberInfo, Type)

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент и тип настраиваемого атрибута для поиска.

GetCustomAttributes(Assembly, Type, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку, тип настраиваемого атрибута для поиска и игнорируемый параметр поиска.

GetCustomAttributes(Module, Type)

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль и тип настраиваемого атрибута для поиска.

GetCustomAttributes(ParameterInfo, Type)

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода и тип настраиваемого атрибута для поиска.

GetCustomAttributes(MemberInfo, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент, тип настраиваемого атрибута для поиска и поиск предков элемента.

GetCustomAttributes(Assembly, Type)

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку и тип пользовательского атрибута для поиска.

GetCustomAttributes(Assembly, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку и игнорируемый параметр поиска.

GetCustomAttributes(ParameterInfo)

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметр задает параметр метода.

GetCustomAttributes(Module)

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметр задает модуль.

GetCustomAttributes(MemberInfo)

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметр задает элемент.

GetCustomAttributes(Assembly)

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметр задает сборку.

GetCustomAttributes(Module, Boolean)

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль и игнорируемый параметр поиска.

GetCustomAttributes(ParameterInfo, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода и следует ли выполнять поиск предков параметра метода.

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

Параметры

element
ParameterInfo

Объект, производный от класса ParameterInfo, описывающего параметр члена класса.

inherit
Boolean

Если true, то указывает также поиск предков element для пользовательских атрибутов.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

Свойство Memberelement равно null.

element null.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая ParameterInfo в качестве параметра.

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

Комментарии

Если element представляет параметр в методе производного типа, возвращаемое значение включает наследуемые настраиваемые атрибуты, применяемые к тому же параметру в переопределенных базовых методах.

Применяется к

Продукт Версии

GetCustomAttributes(MemberInfo, Type, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент, тип настраиваемого атрибута для поиска и поиск предков элемента.

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

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, описывающего конструктор, событие, поле, метод или элемент свойства класса.

typeattributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

inherit
Boolean

Если true, то указывает также поиск предков element для пользовательских атрибутов.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа type применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или typenull.

type не является производным от Attribute.

element не является конструктором, методом, свойством, событием, типом или полем.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая MemberInfo в качестве параметра.

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.

*/

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element, если inherittrue.

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности для методов, конструкторов и типов, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(ParameterInfo, Type, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода, тип настраиваемого атрибута для поиска и поиск предков параметра метода.

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

Параметры

element
ParameterInfo

Объект, производный от класса ParameterInfo, описывающего параметр члена класса.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

inherit
Boolean

Если true, то указывает также поиск предков element для пользовательских атрибутов.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая ParameterInfo в качестве параметра.

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

Комментарии

Если element представляет параметр в методе производного типа, возвращаемое значение включает наследуемые настраиваемые атрибуты, применяемые к тому же параметру в переопределенных базовых методах.

Применяется к

Продукт Версии

GetCustomAttributes(Module, Type, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль, тип настраиваемого атрибута для поиска и игнорируемый параметр поиска.

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

Параметры

element
Module

Объект, производный от класса Module, описывающего переносимый исполняемый файл.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

inherit
Boolean

Этот параметр игнорируется и не влияет на работу этого метода.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Module в качестве параметра.

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

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element, если inherittrue.

Применяется к

Продукт Версии

GetCustomAttributes(MemberInfo, Type)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент и тип настраиваемого атрибута для поиска.

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

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, описывающего конструктор, событие, поле, метод или элемент свойства класса.

typeattributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа type применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или typenull.

type не является производным от Attribute.

element не является конструктором, методом, свойством, событием, типом или полем.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttribute, принимая MemberInfo в качестве параметра.

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.

*/

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element.

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности для методов, конструкторов и типов, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Assembly, Type, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку, тип настраиваемого атрибута для поиска и игнорируемый параметр поиска.

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

Параметры

element
Assembly

Объект, производный от класса Assembly, описывающего повторно используемый набор модулей.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

inherit
Boolean

Этот параметр игнорируется и не влияет на работу этого метода.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Assembly в качестве параметра.

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.

Комментарии

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Module, Type)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль и тип настраиваемого атрибута для поиска.

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

Параметры

element
Module

Объект, производный от класса Module, описывающего переносимый исполняемый файл.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Module в качестве параметра.

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

Применяется к

Продукт Версии

GetCustomAttributes(ParameterInfo, Type)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметры указывают параметр метода и тип настраиваемого атрибута для поиска.

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

Параметры

element
ParameterInfo

Объект, производный от класса ParameterInfo, описывающего параметр члена класса.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая ParameterInfo в качестве параметра.

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

Комментарии

Если element представляет параметр в методе производного типа, возвращаемое значение включает наследуемые настраиваемые атрибуты, применяемые к тому же параметру в переопределенных базовых методах.

Применяется к

Продукт Версии

GetCustomAttributes(MemberInfo, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметры указывают элемент, тип настраиваемого атрибута для поиска и поиск предков элемента.

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

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, описывающего конструктор, событие, поле, метод или элемент свойства класса.

inherit
Boolean

Если true, то указывает также поиск предков element для пользовательских атрибутов.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

element не является конструктором, методом, свойством, событием, типом или полем.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая MemberInfo в качестве параметра.

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.

*/

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element, если inherittrue.

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности для методов, конструкторов и типов, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Assembly, Type)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку и тип пользовательского атрибута для поиска.

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

Параметры

element
Assembly

Объект, производный от класса Assembly, описывающего повторно используемый набор модулей.

attributeType
Type

Тип или базовый тип настраиваемого атрибута для поиска.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты типа attributeType применены к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element или attributeTypenull.

attributeType не является производным от Attribute.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Assembly в качестве параметра.

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.

Комментарии

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Assembly, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметры указывают сборку и игнорируемый параметр поиска.

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

Параметры

element
Assembly

Объект, производный от класса Assembly, описывающего повторно используемый набор модулей.

inherit
Boolean

Этот параметр игнорируется и не влияет на работу этого метода.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Assembly в качестве параметра.

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.

Применяется к

Продукт Версии

GetCustomAttributes(ParameterInfo)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к параметру метода. Параметр задает параметр метода.

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

Параметры

element
ParameterInfo

Объект, производный от класса ParameterInfo, описывающего параметр члена класса.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая ParameterInfo в качестве параметра.

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

Комментарии

Если element представляет параметр в методе производного типа, возвращаемое значение включает наследуемые настраиваемые атрибуты, применяемые к тому же параметру в переопределенных базовых методах.

Применяется к

Продукт Версии

GetCustomAttributes(Module)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметр задает модуль.

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

Параметры

element
Module

Объект, производный от класса Module, описывающего переносимый исполняемый файл.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Module в качестве параметра.

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

Применяется к

Продукт Версии

GetCustomAttributes(MemberInfo)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к элементу типа. Параметр задает элемент.

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

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, описывающего конструктор, событие, поле, метод или элемент свойства класса.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

element не является конструктором, методом, свойством, событием, типом или полем.

Не удается загрузить пользовательский тип атрибута.

Примеры

В следующем примере кода показано использование GetCustomAttribute, принимая MemberInfo в качестве параметра.

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.

*/

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element.

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности для методов, конструкторов и типов, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Assembly)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к сборке. Параметр задает сборку.

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

Параметры

element
Assembly

Объект, производный от класса Assembly, описывающего повторно используемый набор модулей.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

Примеры

В следующем примере извлекаются настраиваемые атрибуты, найденные в текущей сборке.

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.

Комментарии

Примечание

Начиная с .NET Framework версии 2.0 этот метод возвращает атрибуты безопасности, если атрибуты хранятся в новом формате метаданных. Сборки, скомпилированные с версией 2.0 или более поздней, используют новый формат. Динамические сборки и сборки, скомпилированные с более ранними версиями .NET Framework, используют старый формат XML. См. раздел выдачи декларативных атрибутов безопасности.

Применяется к

Продукт Версии

GetCustomAttributes(Module, Boolean)

Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs
Исходный код:
Attribute.CoreCLR.cs

Извлекает массив настраиваемых атрибутов, применяемых к модулю. Параметры указывают модуль и игнорируемый параметр поиска.

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

Параметры

element
Module

Объект, производный от класса Module, описывающего переносимый исполняемый файл.

inherit
Boolean

Этот параметр игнорируется и не влияет на работу этого метода.

Возвращаемое значение

Массив Attribute, содержащий настраиваемые атрибуты, применяемые к element, или пустой массив, если такие настраиваемые атрибуты отсутствуют.

Исключения

element null.

Примеры

В следующем примере кода показано использование GetCustomAttributes, принимая Module в качестве параметра.

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

Комментарии

Возвращаемое значение содержит настраиваемые атрибуты для предков element, если inherittrue.

Применяется к

Продукт Версии