System.Attribute.IsDefined 方法 (ParameterInfo, Type, Boolean)

方法描述

确定是否将任意自定义特性应用于方法参数。 参数指定方法参数、要搜索的自定义特性的类型以及是否搜索方法参数的祖先。

语法定义(C# System.Attribute.IsDefined 方法 (ParameterInfo, Type, Boolean) 的用法)

public static bool IsDefined(
	ParameterInfo element,
	Type attributeType,
	bool inherit
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
element System-Reflection-ParameterInfo 一个从 ParameterInfo 类派生的对象,该类描述类成员的参数。
attributeType System-Type 要搜索的自定义特性的类型,即基类型。
inherit System-Boolean 如果为 true,则指定还在 element 的祖先中搜索自定义特性。
返回值 System.Boolean 如果类型 attributeType 的某个自定义特性应用于 element,则为 true;否则为 false。

提示和注释

System.Attribute.IsDefined 方法 (ParameterInfo, Type, Boolean)例子

下面的代码示例演示 IsDefined 的用法,采用 ParameterInfo 作为参数。

using System;
using System.Reflection;

namespace IsDef5CS 
{
    public class TestClass 
    {
        // Assign a ParamArray attribute to the parameter using the keyword.
        public void Method1(params String[] args)
        {}
    }

    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");
            // Get the ParameterInfo array for the method parameters.
            ParameterInfo[] pInfo = mInfo.GetParameters();
            if (pInfo != null) 
            {
                // See if the ParamArray attribute is defined.
                bool isDef = Attribute.IsDefined(pInfo[0], 
                                                 typeof(ParamArrayAttribute));
                // Display the result.
                Console.WriteLine("The ParamArray attribute {0} defined for " +
                                  "parameter {1} of method {2}.",
                                  isDef ? "is" : "is not",
                                  pInfo[0].Name, 
                                  mInfo.Name);
            }
            else
                Console.WriteLine("The parameters information could " +
                            "not be retrieved for method {0}.", mInfo.Name);
        }
    }
}

/*
 * Output:
 * The ParamArray attribute is defined for parameter args of method Method1.
 */

异常

异常 异常描述
ArgumentNullException element 或 attributeType 为 null。
ArgumentException attributeType 不从 Attribute 派生。
ExecutionEngineException element 不是方法、构造函数或类型。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。