在C#中反射的知識和Type類一塊兒運用得很緊密。要說反射的運用方向,其實MVC就是利用了反射的知識。另外,若是你想作插件,反射的知識也是必不可少的。
c#
Do類:ide
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestDll { public class Do { public string Name; public event Action CallBack; public Do() { } public Do(String name , Int32 age) { this.Name = name; this.Age = age; } public Int32 Age { get; set; } public void DoSomeThing() { Console.WriteLine("Do.DoSomeThing(沒有參數) 執行操做!"); } public void DoSomeThing( string mask ) { Console.WriteLine("Do.DoSomeThing(有參數) 執行操做!{0}", mask); } } }
關於控制檯測試程序:函數
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using TestDll; namespace TestReflect { class Program { static void Main(string[] args) { Assembly _assembly = Assembly.Load("TestDll");//加載程序集,並解析裏面的matedata Type _ty = _assembly.GetType("TestDll.Do"); //------實例化篇 object _ob = Activator.CreateInstance(_ty);//實例化一個對象 , 至關於New object _obOverride = Activator.CreateInstance(_ty, "Ainy", 27);//實例化一個有參數的重載構造函數 /////////////////////////////////////////////////////////////////////////////// //這個_ob(Object)實際上就是Do Do _testDo = _ob as Do; _testDo.DoSomeThing(); /////////////////////////////////////////////////////////////////////////////// foreach(MethodInfo _methodItem in _ty.GetMethods()) { Console.WriteLine("方法 : {0}" , _methodItem.Name); } //------方法篇 MethodInfo _hasParm = _ty.GetMethod("DoSomeThing", new Type[] { typeof(String) });//獲得一個有String參數的方法 :DoSomeThing //執行方法 : DoSomeThing(有參數的) _hasParm.Invoke(_ob, new object[] { "Aonaufly" }); MethodInfo _noParm = _ty.GetMethod("DoSomeThing",new Type[]{});//獲取不帶參數的方法 _noParm.Invoke(_ob,new Object[]{});//執行無參數的方法 //------字段篇 FieldInfo _name = _ty.GetField("Name"); _name.SetValue(_ob, "Aonaufly1"); //------屬性篇 PropertyInfo _age = _ty.GetProperty("Age"); _age.SetValue(_ob, 18); Console.ReadKey(); } } }
須要指出的問題:
測試
1:類庫的DLL,PDB文件要拷貝到程序集的Bin文件中。PDB文件可以讓程序進入調試。this
2:Assembly.Load("TestDll")spa
實際是加載程序集(並解析matedata數據)。程序集即爲:插件
3:_assembly.GetType("TestDll.Do")3d
家在Do類,以便調用
調試
好了,看看執行結果:對象