如何获取程序集内的类型
本示例阐释如何检索给定程序集的所有类型。若要浏览程序集的类型,首先需要标识想操作的程序集。在使某对象引用了感兴趣的程序集后,可以在该程序集上调用 GetTypes 方法,它返回包含该程序集内所有类型的一个数组。您可以使用控制逻辑标识该数组中的更具体类型,并使用迭代逻辑分析您的数组,在需要时向用户返回类型信息。检索类型信息的功能对确定可用于给定任务的其他类型很有用,或对标识可为您提供所需功能的现有元素很有用。
![]()
[运行示例] | [查看源代码] |
从特定程序集检索类型时要学习的首要内容是如何标识程序集。本"快速入门"展示检索程序集的两种方法。第一种方法是标识要在程序集内查找的特定对象,并向程序集请求该对象的模块(记住模块是类型和代码的逻辑分组,如 .dll 或 .exe)。第二种方法是使用 Assembly 类的 LoadFrom 方法,为指定模块(如 myapp.exe)加载特定程序集。
// don't forget your using statements using System; using System.Reflection; // ... // Getting an Assembly, method 1. Get the mscorlib assembly // Note that other types such as String, or Int32 would have worked just as well, // since they reside in the same assembly Assembly a = typeof(Object).Module.Assembly; // Getting an Assembly, method 2. Load a particular assembly, using a reference to a // module that is within that assembly. Note that this requires a compiled module for // the reference, and when running in an aspx page, will require a fully qualifed path // to the file, to ensure it is correctly identified Assembly b = Assembly.LoadFrom ("GetTypes.exe"); // note that either of the above methods is viable, depending on the information // you have. Since we know the name of the file which houses all of the base system // objects, we could do the following to replace the first example, just as effectively // (the absolute path may change on your machine) // Assembly a = Assembly.LoadFrom // ("c:/winserv/microsoft.net/framework/v1.0.2230/mscorlib.dll"); |
||
C# | VB |
标识了程序集后,现在可以继续检索类型,将 GetTypes 方法的返回值分配给 Type 对象的数组。现在便可以操作这些类型了。在下面的示例中,您将获取核心运行时库的类型,并分别计算该程序集内不同类型样式的数目(如果需要有关 Foreach (For Each) 语句的更多信息,请参阅如何迭代通过集合主题下的内容)。尽管还可以计算其他成员(如类和枚举)的数目,但在该示例中,将只展示如何计算接口数目。
//Get all the types in the assembly identified in the previous example Type [] types = a.GetTypes (); int numInterfaces = 0; foreach (Type t in types) { //the following line uses a set of methods which identify what //kind of type we are currently querying if (t.IsInterface) { // only print out the names of the Interfaces Console.WriteLine (t.Name + ""); numInterfaces++; } } // write out the totals Console.WriteLine("Out of {0} types in the {1} library:", types.Length, typeof(Object).Module.ToString()); Console.WriteLine ("{0} are interfaces (listed)", types.Length, numInterfaces); |
||
C# | VB |
还可以使用第一个示例中标识的第二种方法检索给定程序集的类型。在下面的示例中,您将注意到它并未使用相同的基结构来依次通过类型,因为您不需要跟踪类型的不同种类。当查看小型程序集时这很适合,如当前运行的应用程序(获取 MSCorLib 的所有类型的列表将得到一个非常大的列表)。
// Get all the types in the assembly identified in the previous example (this assembly) Type [] types2 = b.GetTypes (); Console.WriteLine ("Get all the types from the assembly: '{0}'", b.GetName()); foreach (Type t in types2) { Console.WriteLine (t.FullName); } |
||
C# | VB |