Attribute.GetCustomAttribute Method

Definition

Retrieves a custom attribute of a specified type applied to an assembly, module, type member, or method parameter.

Overloads

GetCustomAttribute(ParameterInfo, Type, Boolean)

Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.

GetCustomAttribute(MemberInfo, Type, Boolean)

Retrieves a custom attribute applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

GetCustomAttribute(Assembly, Type, Boolean)

Retrieves a custom attribute applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttribute(Module, Type, Boolean)

Retrieves a custom attribute applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.

GetCustomAttribute(Module, Type)

Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for.

GetCustomAttribute(MemberInfo, Type)

Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.

GetCustomAttribute(Assembly, Type)

Retrieves a custom attribute applied to a specified assembly. Parameters specify the assembly and the type of the custom attribute to search for.

GetCustomAttribute(ParameterInfo, Type)

Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.

GetCustomAttribute(ParameterInfo, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter.

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);

Parameters

element
ParameterInfo

An object derived from the ParameterInfo class that describes a parameter of a member of a class.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

inherit
Boolean

If true, specifies to also search the ancestors of element for custom attributes.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

A custom attribute type cannot be loaded.

Examples

The following code example defines a custom parameter Attribute class and applies the custom attribute to a method in a derived class and the base of the derived class. The example shows the use of the GetCustomAttribute method to return the attributes.

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

Remarks

If element represents a parameter in a method of a derived type, the return value includes the inheritable custom attributes applied to the same parameter in the overridden base methods.

Applies to

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

GetCustomAttribute(MemberInfo, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member.

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);

Parameters

element
MemberInfo

An object derived from the MemberInfo class that describes a constructor, event, field, method, or property member of a class.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

inherit
Boolean

If true, specifies to also search the ancestors of element for custom attributes.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

element is not a constructor, method, property, event, type, or field.

More than one of the requested attributes was found.

A custom attribute type cannot be loaded.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking a MemberInfo as a parameter.

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

Remarks

备注

Starting with the .NET Framework version 2.0, this method returns security attributes on types, methods, and constructors if the attributes are stored in the new metadata format. Assemblies compiled with version 2.0 or later use the new format. Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. See Emitting Declarative Security Attributes.

Applies to

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

GetCustomAttribute(Assembly, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

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);

Parameters

element
Assembly

An object derived from the Assembly class that describes a reusable collection of modules.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

inherit
Boolean

This parameter is ignored, and does not affect the operation of this method.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking an Assembly as a parameter.

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

Remarks

备注

Starting with the .NET Framework version 2.0, this method returns security attributes if the attributes are stored in the new metadata format. Assemblies compiled with version 2.0 or later use the new format. Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. See Emitting Declarative Security Attributes.

Applies to

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

GetCustomAttribute(Module, Type, Boolean)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option.

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);

Parameters

element
Module

An object derived from the Module class that describes a portable executable file.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

inherit
Boolean

This parameter is ignored, and does not affect the operation of this method.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking a Module as a parameter.

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

Applies to

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

GetCustomAttribute(Module, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for.

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

Parameters

element
Module

An object derived from the Module class that describes a portable executable file.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking a Module as a parameter.

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

Applies to

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

GetCustomAttribute(MemberInfo, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.

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

Parameters

element
MemberInfo

An object derived from the MemberInfo class that describes a constructor, event, field, method, or property member of a class.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

element is not a constructor, method, property, event, type, or field.

More than one of the requested attributes was found.

A custom attribute type cannot be loaded.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking a MemberInfo as a parameter.

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

Remarks

A match is determined in the same way described in the Return Value section of Type.IsAssignableFrom.

备注

Starting with the .NET Framework version 2.0, this method returns security attributes on types, methods, and constructors if the attributes are stored in the new metadata format. Assemblies compiled with version 2.0 or later use the new format. Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. See Emitting Declarative Security Attributes.

Applies to

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

GetCustomAttribute(Assembly, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a specified assembly. Parameters specify the assembly and the type of the custom attribute to search for.

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

Parameters

element
Assembly

An object derived from the Assembly class that describes a reusable collection of modules.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

Examples

The following code example illustrates the use of the GetCustomAttribute method taking an Assembly as a parameter.

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

Remarks

Use the GetCustomAttributes method if you expect more than one value to be returned, or AmbiguousMatchException will be thrown.

备注

Starting with the .NET Framework version 2.0, this method returns security attributes if the attributes are stored in the new metadata format. Assemblies compiled with version 2.0 or later use the new format. Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. See Emitting Declarative Security Attributes.

Applies to

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

GetCustomAttribute(ParameterInfo, Type)

Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs
Source:
Attribute.CoreCLR.cs

Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.

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

Parameters

element
ParameterInfo

An object derived from the ParameterInfo class that describes a parameter of a member of a class.

attributeType
Type

The type, or a base type, of the custom attribute to search for.

Returns

A reference to the single custom attribute of type attributeType that is applied to element, or null if there is no such attribute.

Exceptions

element or attributeType is null.

attributeType is not derived from Attribute.

More than one of the requested attributes was found.

A custom attribute type cannot be loaded.

Examples

The following code example defines a custom parameter Attribute class and applies the custom attribute to a method in a derived class and the base of the derived class. The example shows the use of the GetCustomAttribute method to return the attributes.

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

Remarks

If element represents a parameter in a method of a derived type, the return value includes the inheritable custom attributes applied to the same parameter in the overridden base methods.

Applies to

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