原理如下:
1、利用反射進行動态加載和調用.
Assembly assembly=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、調用類型中的某個方法:
需要首先得到此方法
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;
<a href="http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx">http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx</a>