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

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


Attribute.GetCustomAttribute Метод

Определение

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

Перегрузки

GetCustomAttribute(ParameterInfo, Type, Boolean)

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

GetCustomAttribute(MemberInfo, Type, Boolean)

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

GetCustomAttribute(Assembly, Type, Boolean)

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

GetCustomAttribute(Module, Type, Boolean)

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

GetCustomAttribute(Module, Type)

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

GetCustomAttribute(MemberInfo, Type)

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

GetCustomAttribute(Assembly, Type)

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

GetCustomAttribute(ParameterInfo, Type)

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

GetCustomAttribute(ParameterInfo, Type, Boolean)

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

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

Параметры

element
ParameterInfo

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

attributeType
Type

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

inherit
Boolean

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Не удалось загрузить тип настраиваемого атрибута.

Примеры

В следующем примере кода определяется пользовательский класс параметров Attribute и применяется пользовательский атрибут к методу в производном классе и базе производного класса. В примере показано использование GetCustomAttribute метода для возврата атрибутов.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Комментарии

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

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

GetCustomAttribute(MemberInfo, Type, Boolean)

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

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

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, который описывает член класса (конструктор, событие, поле, метод или свойство).

attributeType
Type

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

inherit
Boolean

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

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

Найдено несколько запрошенных атрибутов.

Не удалось загрузить тип настраиваемого атрибута.

Примеры

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

using System;
using System.Reflection;

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

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

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

Комментарии

Примечание

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

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

GetCustomAttribute(Assembly, Type, Boolean)

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

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

Параметры

element
Assembly

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

attributeType
Type

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

inherit
Boolean

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Примеры

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

using System;
using System.Reflection;

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

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

Комментарии

Примечание

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

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

GetCustomAttribute(Module, Type, Boolean)

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

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

Параметры

element
Module

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

attributeType
Type

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

inherit
Boolean

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Примеры

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

using System;
using System.Diagnostics;

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

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

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

GetCustomAttribute(Module, Type)

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

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

Параметры

element
Module

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

attributeType
Type

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Примеры

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

using System;
using System.Diagnostics;

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

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

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

GetCustomAttribute(MemberInfo, Type)

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

public static Attribute? GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.MemberInfo element, Type attributeType);

Параметры

element
MemberInfo

Объект, производный от класса MemberInfo, который описывает член класса (конструктор, событие, поле, метод или свойство).

attributeType
Type

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

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

Найдено несколько запрошенных атрибутов.

Не удалось загрузить тип настраиваемого атрибута.

Примеры

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

using System;
using System.Reflection;

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

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

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

Комментарии

Совпадение определяется так же, как описано в разделе Type.IsAssignableFrom"Возвращаемое значение".

Примечание

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

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

GetCustomAttribute(Assembly, Type)

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

public static Attribute? GetCustomAttribute (System.Reflection.Assembly element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.Assembly element, Type attributeType);

Параметры

element
Assembly

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

attributeType
Type

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Примеры

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

using System;
using System.Reflection;

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

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

Комментарии

Используйте метод, GetCustomAttributes если ожидается возврат нескольких значений или AmbiguousMatchException будет выдано несколько значений.

Примечание

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

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

GetCustomAttribute(ParameterInfo, Type)

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

public static Attribute? GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType);
public static Attribute GetCustomAttribute (System.Reflection.ParameterInfo element, Type attributeType);

Параметры

element
ParameterInfo

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

attributeType
Type

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

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

Attribute

Ссылка на один настраиваемый атрибут типа attributeType, примененный к element, или null, если такого атрибута нет.

Исключения

Параметр element или attributeType имеет значение null.

Тип attributeType не является производным объекта Attribute.

Найдено несколько запрошенных атрибутов.

Не удалось загрузить тип настраиваемого атрибута.

Примеры

В следующем примере кода определяется пользовательский класс параметров Attribute и применяется пользовательский атрибут к методу в производном классе и базе производного класса. В примере показано использование GetCustomAttribute метода для возврата атрибутов.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Комментарии

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

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