s.Length > 0 ) Console.WriteLine( "\n\t\tMod/Fix Log:" ) ;
foreach( Attribute loAtt in laMethodAttributes ) { DefectTrackAttribute loDefectTrack = (DefectTrackAttribute)loAtt ; Console.WriteLine( "\t\t----------------" ) ; Console.WriteLine( "\t\tDefect ID:\t" + loDefectTrack.DefectID ) ; Console.WriteLine( "\t\tDeveloper ID:\t" + loDefectTrack.DeveloperID ) ; Console.WriteLine( "\t\tOrigin:\t\t" + loDefectTrack.Origin ) ; Console.WriteLine( "\t\tComment:\n\t\t" + loDefectTrack.FixComment ) ; } } Console.WriteLine( "\n\n" ) ; } } }
让我们来看一下比较重要的几行代码。DisplayDefectTrack()方法的第一行代码和第二行代码得到了加载指定程序集的一个引用并且得到了包含在该程序集中类型的一个数组。
Assembly loAssembly = Assembly.Load( lcAssembly ) ;
Type[ ] laTypes = loAssembly.GetTypes( ) ;
使用foreach语句在程序集中的每一个类型上迭代。在控制台上输出当前类型的名称,并使用如下的语句查询当前类型,获取有关[DefectTrack]特性的一个数组。
object[ ] laAttributes = loType.GetCustomAttributes( typeof( DefectTrackAttribute ), false ) ;
你需要在GetCustomAttributes方法上指定typeof(DefectTrackAttribute) 参数,以限制仅仅返回你创建的自定义特性。第二个参数false指定是否搜索该成员的继承链以查找这些自定义特性。
使用foreach语句迭代自定义特性数组,并把它们(自定义特性)的值输出到控制台上。你应该认识到第一个foreach语句块会创建一个新的变量,并且对当前的特性作类型转化。
DefectTrackAttribute loDefectTrack = (DefectTrackAttribute)loAtt ;
这一条语句为什么是必须的呢?GetCustomAttributes()方法会返回一个object数组,你为了访问自定义特性的值,所以必须把这些引用转化为它们真正的具体类的引用。转化完以后,你就可以使用这些特性并且可以把特性的值输出到控制台上。
因为你 上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一页
|