System.Attribute.GetCustomAttributes 方法 (Assembly, Type, Boolean)

方法描述

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

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

public static Attribute[] GetCustomAttributes(
	Assembly element,
	Type attributeType,
	bool inherit
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
element System-Reflection-Assembly 一个从 Assembly 类派生的对象,该类描述可重用模块集合。
attributeType System-Type 要搜索的自定义特性的类型,即基类型。
inherit System-Boolean 此参数被忽略,并且不会影响此方法的操作。
返回值 System.Attribute[] 一个 Attribute 数组,包含应用于 element 的 attributeType 类型的自定义特性;如果不存在此类自定义特性,则为空数组。

提示和注释

注意

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

System.Attribute.GetCustomAttributes 方法 (Assembly, Type, Boolean)例子

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

using System;
using System.Reflection;

[assembly: AssemblyTitle("CustAttrs1CS")]
[assembly: AssemblyDescription("GetCustomAttributes() Demo")]
[assembly: AssemblyCompany("Microsoft")]

namespace CustAttrs1CS {
    class DemoClass {
        static void Main(string[] args) {
            Type clsType = typeof(DemoClass);
            // Get the Assembly type to access its metadata.
            Assembly assy = clsType.Assembly;

            // Iterate through the attributes for the assembly.
            foreach(Attribute attr in Attribute.GetCustomAttributes(assy)) {
                // Check for the AssemblyTitle attribute.
                if (attr.GetType() == typeof(AssemblyTitleAttribute))
                    Console.WriteLine("Assembly title is \"{0}\".",
                        ((AssemblyTitleAttribute)attr).Title);

                // Check for the AssemblyDescription attribute.
                else if (attr.GetType() == 
                    typeof(AssemblyDescriptionAttribute))
                    Console.WriteLine("Assembly description is \"{0}\".",
                        ((AssemblyDescriptionAttribute)attr).Description);

                // Check for the AssemblyCompany attribute.
                else if (attr.GetType() == typeof(AssemblyCompanyAttribute))
                    Console.WriteLine("Assembly company is {0}.",
                        ((AssemblyCompanyAttribute)attr).Company);
            }
        }
    }
}

/*
 * Output:
 * Assembly company is Microsoft.
 * Assembly description is "GetCustomAttributes() Demo".
 * Assembly title is "CustAttrs1CS".
 */

异常

异常 异常描述
ArgumentNullException element 或 attributeType 为 null。
ArgumentException attributeType 不从 Attribute 派生。

命名空间

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 系统要求。