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);
Console.WriteLine();
// pause
Console.ReadLine();
// reflect method information
MethodInfo[] minfo = type1.GetMethods();
// iterate through methods
foreach (MethodInfo m in minfo)
{
Console.WriteLine(m);
}
Console.WriteLine();
}
}
}
下一個例子將展示動態得到對象有可能接觸的每個構造器的信息。類似與上面的例子,我們將返回一個包含每個構造器的信息ConstructorInfo對象。
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);
Console.WriteLine();
// pause
Console.ReadLine();
// reflect constructors
ConstructorInfo[] cinfo = type1.GetConstructors();
// iterate through constructors
foreach (ConstructorInfo c in cinfo)
{
Console.WriteLine(c);
}
}
}
}
最后一部分,也許是reflection名字空間中最激動人心的部分,是在運行時動態調用類方法。有兩種方法,首先,我們將建立一個數組來存儲參數,這些參數被構造器用來建造對象。第二,一個System.Object對象將對抗CreateInstance方法的對象。以得到想得到對象的例子。最后,當我們有了對象的資料,我們能夠調用任何使用MethodParm數組的方法。下面是代碼:
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();
// dynamic creation and invocation
// instantiate the Reflect object, passing
// a value of 1 to the constructor
object[] oConstructParms = new object[] {1};
object obj = Activator.CreateInstance(type1, oConstructParms);
// invoke method of reflect object
object[] oMethodParms = new object[] {17};
int intResult = (int)type1.InvokeMember("AMethod", BindingFlags.Default |
BindingFlags.InvokeMethod, null, obj, oMethodParms);
Console.WriteLine("Result of calling AMethod on {0} is {1}",
type1.Name, intResult);
// pause
Console.ReadLine();
}
}
}
這篇文章闡述了.net Reflaction的基礎,在下一部分,我將和大家討論進一步的話題,比如,動態發布中間語言,旗幟綁定,和中間語言原則。
文章來源于領測軟件測試網 http://www.kjueaiud.com/