65.9K
CodeProject 正在变化。 阅读更多。
Home

程序集属性

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.94/5 (12投票s)

2004年2月9日

2分钟阅读

viewsIcon

87787

downloadIcon

1283

以编程方式检查程序集属性。

Sample Image - Attributes.jpg

引言

反射允许您以编程方式检查一个程序集,并获取关于该程序集的信息,包括其中包含的所有对象类型。这些信息包括您已添加到这些类型上的属性。反射对象位于 System.Reflection 命名空间中。

这个演示程序将检查一个程序集并显示定义在该程序集上的所有属性的列表。整个源代码可下载,我将解释它的工作原理。

源代码解释

代码首先检查传递给命令行参数 - 如果没有提供任何参数,或者用户输入 FindAttributes /?,则将调用 Usage() 方法,该方法将显示一个简单的命令行用法摘要。

if (args.Length == 0)
      Usage();
else if((args.Length == 1)&&(args[0] == "/?"))
      Usage();

接下来,我们将命令行参数重新组合成一个字符串。原因是,目录名中通常包含空格,例如“Program Files”,这会被视为两个参数,因为存在空格。因此,我们遍历所有参数,将它们重新拼接成一个字符串,并使用此字符串作为要加载的程序集名称。

foreach(string arg in args)
      {
        if(assemblyName == null)
          assemblyName = arg;
        else
          assemblyName = string.Format("{0} {1}", assemblyName, arg);
      }

然后,我们尝试加载程序集,并使用 GetCustomAttributes() 方法检索该程序集上定义的所有自定义属性。

Assembly a = Assembly.LoadFrom(assemblyName);

// Now find the attributes on the assembly
object[] attributes = a.GetCustomAttributes(true) ;

// If there were any attributes defined...
if(attributes.Length > 0)
   {
      Console.WriteLine("Assembly attributes for '{0}'...", assemblyName);
      // Dump them out...
      foreach(object o in attributes)
           Console.WriteLine("  {0}", o.ToString());
   }

找到的任何属性都会输出到控制台。

您可以使用如下命令行编译器来构建源代码的可执行文件:

>csc FindAttributes.cs

运行程序

当您使用 FindAttributes.exe 文件测试程序时,将显示一个名为 DebuggableAttribute 的属性,如图所示。虽然此属性未指定,但 C# 编译器已将其添加,您会发现大多数可执行文件都具有此属性。

其他说明

您可以根据需要修改代码,以添加任意数量的程序集属性。例如,尝试通过取消注释列表开头的 using 指令之后的行来修改源代码。

  //[assembly: AssemblyTitle("Title")]

重新编译并运行代码后,您将看到列表中添加了另一个属性,即 System.Reflection.AssemblyTitleAttribute

请查阅 Karli Watson 的 Beginning Visual C# [ISBN 1-86100-758-2] 由 Wrox Press 出版,以获取更多信息。

© . All rights reserved.