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)

检索应用于方法参数的自定义属性。 参数指定方法参数、要搜索的自定义属性的类型以及是否搜索方法参数的祖先。

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

参数

element
ParameterInfo

一个从 ParameterInfo 类派生的对象,该类描述类成员的参数。

attributeType
Type

要搜索的自定义属性的类型或基类型。

inherit
Boolean

如果为 true,则指定还在 element 的祖先中搜索自定义属性。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

无法加载自定义属性类型。

示例

下面的代码示例定义自定义参数 Attribute 类,并将自定义属性应用于派生类和派生类的基的方法。 该示例演示如何使用 GetCustomAttribute 该方法返回属性。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

注解

如果 element 表示派生类型的方法中的参数,则返回值包括应用于重写基方法中相同参数的可继承自定义属性。

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(MemberInfo, Type, Boolean)

检索应用于类型成员的自定义属性。 参数指定成员、要搜索的自定义属性的类型以及是否搜索成员的祖先。

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

参数

element
MemberInfo

一个从 MemberInfo 类派生的对象,该类描述类的构造函数、事件、字段、方法或属性成员。

attributeType
Type

要搜索的自定义属性的类型或基类型。

inherit
Boolean

如果为 true,则指定还在 element 的祖先中搜索自定义属性。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

element 不是构造函数、方法、属性、事件、类型或字段。

找到多个请求的属性。

无法加载自定义属性类型。

示例

下面的代码示例演示如何使用 GetCustomAttribute 采用参数 MemberInfo 的方法。

C#
using System;
using System.Reflection;

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

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

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

注解

备注

从 .NET Framework 版本 2.0 开始,如果属性以新的元数据格式存储,此方法将返回类型、方法和构造函数的安全属性。 使用版本 2.0 或更高版本编译的程序集使用新格式。 使用早期版本的.NET Framework编译的动态程序集和程序集使用旧的 XML 格式。 请参阅 发出声明性安全属性

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(Assembly, Type, Boolean)

检索应用于程序集的自定义属性。 参数指定程序集、要搜索的自定义属性的类型以及忽略的搜索选项。

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

参数

element
Assembly

一个派生自 Assembly 类的对象,用于描述模块的可重用集合。

attributeType
Type

要搜索的自定义属性的类型或基类型。

inherit
Boolean

此参数被忽略,并且不会影响此方法的操作。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

示例

下面的代码示例演示了采用 GetCustomAttribute 参数 Assembly 的方法的使用。

C#
using System;
using System.Reflection;

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

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

注解

备注

从 .NET Framework 版本 2.0 开始,如果属性以新的元数据格式存储,此方法将返回安全属性。 使用版本 2.0 或更高版本编译的程序集使用新格式。 使用早期版本的.NET Framework编译的动态程序集和程序集使用旧的 XML 格式。 请参阅 发出声明性安全属性

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(Module, Type, Boolean)

检索应用于模块的自定义属性。 参数指定模块、要搜索的自定义属性的类型以及忽略的搜索选项。

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

参数

element
Module

一个从 Module 类派生的对象,该类描述可移植的可执行文件。

attributeType
Type

要搜索的自定义属性的类型或基类型。

inherit
Boolean

此参数被忽略,并且不会影响此方法的操作。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

示例

下面的代码示例演示如何使用 GetCustomAttribute 采用参数 Module 的方法。

C#
using System;
using System.Diagnostics;

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

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

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(Module, Type)

检索应用于模块的自定义属性。 参数指定模块和要搜索的自定义属性的类型。

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

参数

element
Module

一个从 Module 类派生的对象,该类描述可移植的可执行文件。

attributeType
Type

要搜索的自定义属性的类型或基类型。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

示例

下面的代码示例演示如何使用 GetCustomAttribute 采用参数 Module 的方法。

C#
using System;
using System.Diagnostics;

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

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

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(MemberInfo, Type)

检索应用于类型成员的自定义属性。 参数指定成员和要搜索的自定义属性的类型。

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

参数

element
MemberInfo

一个从 MemberInfo 类派生的对象,该类描述类的构造函数、事件、字段、方法或属性成员。

attributeType
Type

要搜索的自定义属性的类型或基类型。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

element 不是构造函数、方法、属性、事件、类型或字段。

找到多个请求的属性。

无法加载自定义属性类型。

示例

下面的代码示例演示如何使用 GetCustomAttribute 采用参数 MemberInfo 的方法。

C#
using System;
using System.Reflection;

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

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

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

注解

匹配项的确定方式与 “返回值”部分 Type.IsAssignableFrom中所述的方式相同。

备注

从 .NET Framework 版本 2.0 开始,如果属性以新的元数据格式存储,此方法将返回类型、方法和构造函数的安全属性。 使用版本 2.0 或更高版本编译的程序集使用新格式。 使用早期版本的.NET Framework编译的动态程序集和程序集使用旧的 XML 格式。 请参阅 发出声明性安全属性

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(Assembly, Type)

检索应用于指定程序集的自定义属性。 参数指定程序集和要搜索的自定义属性的类型。

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

参数

element
Assembly

一个派生自 Assembly 类的对象,用于描述模块的可重用集合。

attributeType
Type

要搜索的自定义属性的类型或基类型。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

示例

下面的代码示例演示了采用 GetCustomAttribute 参数 Assembly 的方法的使用。

C#
using System;
using System.Reflection;

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

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

注解

GetCustomAttributes如果希望返回多个值或将引发,AmbiguousMatchException请使用该方法。

备注

从 .NET Framework 版本 2.0 开始,如果属性以新的元数据格式存储,此方法将返回安全属性。 使用版本 2.0 或更高版本编译的程序集使用新格式。 使用早期版本的.NET Framework编译的动态程序集和程序集使用旧的 XML 格式。 请参阅 发出声明性安全属性

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

GetCustomAttribute(ParameterInfo, Type)

检索应用于方法参数的自定义属性。 参数指定方法参数和要搜索的自定义属性的类型。

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

参数

element
ParameterInfo

一个从 ParameterInfo 类派生的对象,该类描述类成员的参数。

attributeType
Type

要搜索的自定义属性的类型或基类型。

返回

Attribute

一个引用,指向应用于 attributeTypeelement 类型的单个自定义属性;如果没有此类属性,则为 null

例外

elementattributeTypenull

attributeType 不是从 Attribute 派生的。

找到多个请求的属性。

无法加载自定义属性类型。

示例

下面的代码示例定义自定义参数 Attribute 类,并将自定义属性应用于派生类和派生类的基的方法。 该示例演示如何使用 GetCustomAttribute 该方法返回属性。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

注解

如果 element 表示派生类型的方法中的参数,则返回值包括应用于重写基方法中相同参数的可继承自定义属性。

适用于

.NET 7 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1