System.Reflection.MemberInfo.GetCustomAttributes 方法 (Boolean)

方法描述

在派生类中重写时,返回应用于此成员的所有自定义特性的数组。

语法定义(C# System.Reflection.MemberInfo.GetCustomAttributes 方法 (Boolean) 的用法)

public abstract Object[] GetCustomAttributes(
	bool inherit
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
inherit System-Boolean 搜索此成员的继承链以查找这些特性,则为 true;否则为 false。属性和事件中忽略此参数,请参见“备注”。
返回值 System.Object[] 一个包含应用于此成员的所有自定义特性的数组,在未定义任何特性时为包含零个元素的数组。

提示和注释

此方法忽略属性和事件的 inherit 参数。 若要搜索用于属性和事件上的特性的继承链,请使用 Attribute.GetCustomAttributes 方法的适当重载。

注意

在 .NET Framework 2.0 版中,如果方法、构造函数和类型的安全特性是采用新的元数据格式存储的,则此方法将返回这些特性。 用 2.0 版编译的程序集使用此格式。 动态程序集和用 .NET Framework 的早期版本编译的程序集使用旧的 XML 格式。 请参见发出声明性安全特性。

System.Reflection.MemberInfo.GetCustomAttributes 方法 (Boolean)例子

下面的示例定义一个自定义特性并将其与 MyClass.MyMethod 相关联,然后在运行时检索该特性,并显示结果。

using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name
    {
        get
        {
            return myName;
        }
    }
}

// Define a class that has the custom attribute associated with one of its members.
public class MyClass1
{
    [MyAttribute("This is an example attribute.")]
    public void MyMethod(int i)
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes
{
    public static void Main()
    {
        try
        {
            // Get the type of MyClass1.
            Type myType = typeof(MyClass1);
            // Get the members associated with MyClass1.
            MemberInfo[] myMembers = myType.GetMembers();

            // Display the attributes for each of the members of MyClass1.
            for(int i = 0; i < myMembers.Length; i++)
            {
                Object[] myAttributes = myMembers[i].GetCustomAttributes(true);
                if(myAttributes.Length > 0)
                {
                    Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]);
                    for(int j = 0; j < myAttributes.Length; j++)
                        Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("An exception occurred: {0}", e.Message);
        }
    }
}

异常

异常 异常描述
InvalidOperationException 该成员属于加载到仅反射上下文的类型。 请参见如何:将程序集加载到仅反射上下文中。
TypeLoadException 未能加载自定义特性类型。

命名空间

namespace: System.Reflection

程序集: 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 系统要求。