標籤:style blog color 使用 os 檔案
原理如下:
1、利用反射進行動態載入和調用.
Assembly ass=Assembly.LoadFrom(DllPath); //利用dll的路徑載入,同時將此程式集所依賴的程式集載入進來,需後輟名.dll
Assembly.LoadFile 只載入指定檔案,並不會自動載入依賴程式集.Assmbly.Load無需後輟名
2、載入dll後,需要使用dll中某類.
Type type=ass.GetType(“TypeName”);//用類型的命名空間和名稱獲得類型
3、需要執行個體化類型,才可以使用,參數可以人為的指定,也可以無參數,靜態執行個體可以省略
Object obj =Activator.CreateInstance(type,params[]);//利用指定的參數執行個體話類型
4、調用類型中的某個方法:
註:如果是類的靜態方法,可以直接調用,如: string strReturn = (string) type.InvokeMember("GetNewValue",BindingFlags.DeclaredOnly|BindingFlags.Public|BindingFlags.Static|BindingFlags.InvokeMethod,null, null, new object[]{ 12 } );
需要首先得到此方法
MethodInfo mi=type.GetMethod(“MehtodName”);//通過方法名稱獲得方法
5、然後對方法進行調用,多態性利用參數進行控制
mi.Invoke(obj,params[]);//根據參數直線方法,傳回值就是原方法的傳回值
#region 聲明動態載入DLL的參數 object obj=null; byte[] filesByte; Assembly assembly; Type type; MethodInfo timerInitial; MethodInfo timerDispose;#endregion private void LoadDll()//載入DLL { try { filesByte =File.ReadAllBytes(Path.GetDirectoryName(Application.ExecutablePath) +"\\loadDll.dll"); assembly =Assembly.Load(filesByte); type =assembly.GetType("test.loadDll"); obj =System.Activator.CreateInstance(type); timerStart =tp.GetMethod("TimerStart"); timerStop =tp.GetMethod("TimerStop"); if (timerStart != null) { timerStart.Invoke(obj,null); } } catch(Exception) { } }
以下摘自MSDN
public class A{ public virtual int method () {return 0;}}public class B{ public virtual int method () {return 1;}}class Mymethodinfo{ public static int Main() { Console.WriteLine ("\nReflection.MethodInfo"); A MyA = new A(); B MyB = new B(); // Get the Type and MethodInfo. Type MyTypea = Type.GetType("A"); MethodInfo Mymethodinfoa =MyTypea.GetMethod("method"); Type MyTypeb = Type.GetType("B"); MethodInfo Mymethodinfob = MyTypeb.GetMethod("method"); // Get and display the Invoke method. Console.Write("\nFirst method - " + MyTypea.FullName + " returns " + Mymethodinfoa.Invoke(MyA, null)); Console.Write("\nSecond method - " + MyTypeb.FullName + " returns " + Mymethodinfob.Invoke(MyB, null)); return 0; }}