毫無疑問,集合清單類似于COM(+)的類型庫。清單有在類型庫中不存在的優點。這個超過了這一課的范圍,我們將在這篇文章的第二部分進行講述。被利用.net集合的客戶端程序將要使用清單。因為每個集合包含元數據的許多信息,客戶程序在運行時能夠得到集合的內容。這個過程就叫做reflection.Reflection不僅能夠查詢基礎類,而且運行時能動態調用方法,甚至于輸出能夠直接執行的IL代碼。在你的代碼中有兩種方法來使用reflection,Reflection API 和 System.Reflection 名字空間。System.reflection是極端負責的,它包含將近40個類。在文章的其他部分,我將介紹reflection的基礎,如何用它區查詢集合類,方法,以及運行時調用方法的類型。為了示范在.net中的reflection名字空間,我將用下面的"reflection"類來說明:
// Reflect.cs namespace CSharPReflectionSamples { using System;
/// <summary> /// The reflect class will be used to demonstrate the basics of /// .NET reflection. This class contains private member vars, /// a constructor, a sample method, and sample accessor methods. /// </summary> public class Reflect { // private member variables private int intTest; private string strTest;
// basic method public int AMethod(int intData) { return intData*intData; }
public string S { get { // return member var return strTest; } set { // set member var S = value; } } } }
正如你所看到的那樣,這個類包含一個構造器,一個例子方法,一個例子存取方法(得到和設置)。在System.Reflaction 名字空間核心是一個名為type的類。這個type類型包含許多方法和到許多類信息的一種登錄入口。Type類參考可以靠typeof或者GetType的方法得到。下表列舉了一些類類型的方法,包括示例GetTypeof 和typeof方法的代碼段。 Name Description
GetFields() Returns an array of FieldInfo objects describing the fields in the class.
GetMethods() Returns an array of MethodInfo objects describing the methods of the class.
GetConstructors() Returns all the constructors for an object.
GetInterfaces() Gets all interfacs implemented by the type.
GetMembers() Gets all the members (fields, methods, events, etc.) of the current type.
InvokeMember() Invokes a member of the current type.
BaseType Gets a Type object for the type's immediate base type.
IsAbstract Returns true if the type is abstract.
IsClass Returns true if the type is a class.
IsEnum Returns true if the type is an enum.
IsNestedPublic Returns true if a type is nested within another and is public.
Namespace Retrieves the namespace of the type.
namespace CSharpReflectionSamples { using System; using System.Reflection;
/// <summary> /// Summary description for Client. /// </summary> public class Client { public static void Main() { // the typeof Operator and the GetType method // both return a 'Type' object. Type type1 = typeof(Reflect); Reflect objTest = new Reflect(0); Type type2 = objTest.GetType();
Console.WriteLine("Type of objTest is {0}", type2);