.NET的反射(Reflection)是很是完善和強大的,例若有名的.NET反編譯工具Red Gate's .NET Reflector就是使用了.NET自身的反射機制,這裏有一個比較簡單的實例(使用控制檯程序),看看.NET中如何使用反射。
數組
- using System;
- using System.Reflection;
- namespace Mengliao.CSharp.C13.S02
- {
- class MyClass
- {
- private int count;
- public MyClass(int value)
- {
- count = value;
- }
- public void m1()
- {
- Console.WriteLine("Called method 1.");
- }
- public static int m2(int x)
- {
- return x * x;
- }
- public void m3(int x, double y)
- {
- Console.WriteLine("Called method 3, paramaters: x = {0}, y = {1:E}.", x, y);
- }
- public void m4()
- {
- Console.WriteLine("Called method 4. Count = {0}", count);
- }
- private static string m5(double x) //私有靜態方法,不能直接調用,但能夠綁定到委託
- {
- return Math.Sqrt(x).ToString();
- }
- }
- class Program
- {
- public static void Main()
- {
- //取得MyClass的Type對象,下面的代碼使用Type的靜態方法需指明程序集,做用相同
- //Type t = Type.GetType("Mengliao.CSharp.C13.S02.MyClass, ConsoleApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
- Type t = typeof(MyClass);
- //經過Activator實例化MyClass,供實例方法調用
- object obj = Activator.CreateInstance(t, new object[] { 88 });
- MethodInfo[] methods = t.GetMethods(); //獲取MyClass的全部方法列表
- foreach (MethodInfo nextMethod in methods) //枚舉全部方法
- {
- Console.WriteLine(nextMethod.ToString()); //顯示方法信息
- if (nextMethod.Name == "m1") //方法m1
- {
- nextMethod.Invoke(obj, null); //使用obj對象調用方法m1,無參數
- }
- if (nextMethod.Name == "m2") //方法m2
- {
- //靜態方法,使用null調用方法m2,創建參數數組,傳入10
- Console.WriteLine("Called static method 2, return {0}", nextMethod.Invoke(null, new object[] { 10 }));
- }
- }
- MethodInfo m3Info = t.GetMethod("m3"); //獲取方法m3
- m3Info.Invoke(obj, new object[] { 123, 0.456 }); //調用方法m3,傳入對應的2個參數
- //獲取方法m4,使用obj對象調用方法,無參數
- t.InvokeMember("m4", BindingFlags.InvokeMethod, null, obj, null);
- //創建泛型委託runMe,並綁定MyClass的靜態私有方法m5
- Delegate runMe = Delegate.CreateDelegate(typeof(Func<double, string>), t, "m5");
- Console.WriteLine("Call delegate with m5: Sqrt(2) = {0}", ((Func<double, string>)runMe)(2)); //調用該委託
- Console.ReadLine();
- }
- }
- }
使用反射機制能夠調用各類方法,包括私有的、靜態的等等,程序中的註釋很是詳細,這裏就很少說了。ide