標籤:類對象 typedef pat typeof framework for break ice 方式
概述
程式集的反射以及動態建立類對象,是自動化編程常用的到知識原理,比如外掛程式編程、模板設計模式,都可以採用發射機制動態去建立執行個體化對象,實作類別的動態載入。這裡簡單總結下,常用到的Framework反射知識點(泛型和非泛型);.NET架構的三個內建類來使用反射:System.Reflection.Assembly、System.Type和System.Activator;
- System.Reflection.Assembly類描述了.NET的程式集.在.NET中,程式集是登錄區.對於一個典型的Windows程式,程式集被配置為單一的Win32可執行檔,並且帶有特定的附加資訊,使之適應.NET運行環境.程式集也可以配置為Win32的DLL(動態連結程式庫),同樣需要帶有.NET需要的附加資訊。System.Reflection.Assembly類可以在啟動並執行時候取得程式集的資訊.這些資訊包括程式集包含的類型資訊。
- System.Type類描述了類型定義.一個型別宣告可以是一個類,介面,數組,結構體,或者枚舉.在載入了一個類之後,System.Type類可以被用於枚舉該類支援的方法,屬性,事件和介面。
- System.Activator類用於建立一個類的執行個體。
程式集Assembly
程式集的載入和讀取方式
Assembly[] AssbyCustmList = System.AppDomain.CurrentDomain.GetAssemblies();//擷取當前那所有程式集Assembly ResltAss = typeof(IServicePlugin).Assembly;//當前類型所在程式集Assembly tmp = Assembly.LoadFile(filepath);//檔案路徑載入
程式集Type類型
擷取程式集Type類型
Assembly tmp = Assembly.LoadFile(file);//檔案路徑載入Type[] types = tmp.GetTypes();//擷取程式集的所有類型Type[] Items= tmp.GetExportedTypes();//擷取程式集公用類型
判斷程式集的屬性資訊:介面實現、泛型型別
Type t=GetType(); Type[] interfaces = t.GetInterfaces();//擷取該類型上層實現所有介面 foreach( Type theInterface in interfaces ) { if (theInterface.FullName == "WinDemo.Core.Iplugin") { ret = true; break; } } //t.GetTypes().Where(x => x.GetInterfaces().Count(p => p.FullName == "PluginUnitTestProject.IServicePlugin") >0)//(簡寫,功能同上) Type[] interfaces = t.GetInterface("Iplugin");//擷取該類型上層實現介面Iplugin類型
判斷泛型方式:IsGenericType、GetGenericTypeDefinition()和GetGenericArguments()
private IEnumerable<Type> GetHandlerTypes<T>() where T : Command { var handlers = typeof(ICommandHandler<>).Assembly.GetExportedTypes() .Where(x => x.GetInterfaces() .Any(a => a.IsGenericType && a.GetGenericTypeDefinition() == typeof(ICommandHandler<>) )) .Where(h=>h.GetInterfaces() .Any(ii=>ii.GetGenericArguments() .Any(aa=>aa==typeof(T)))).ToList(); return handlers; }
程式的建立
通過程式集的CreateInstance
Assembly tmp = Assembly.LoadFile(filepth);//檔案路徑載入 Type[] types = tmp.GetTypes(); bool ok = false; foreach (Type t in types) { if (IsValidPlugin(t)) { IServicePlugin plugin = (IServicePlugin)tmp.CreateInstance(t.FullName);
//動態載入程式集裡面方法,動態調用
MethodInfo medo = t.GetMethod("InvokeTask");medo.Invoke(serple, null);
} }
通過Activator.CreateInstance
ServicePluginAttribute srevic = null; foreach (Type itm in TypeItemList) { srevic = new ServicePluginAttribute(); var serple = Activator.CreateInstance(itm);
//動態調用程式集裡面的方法
MethodInfo medo = t.GetMethod("InvokeTask");medo.Invoke(serple, null);
}
.NET Framework反射總結