首页 > 代码库 > C# 动态加载(转)
C# 动态加载(转)
原文链接地址:http://blog.csdn.net/lanruoshui/article/details/5090710
原理如下:
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[]);//根据参数直线方法,返回值就是原方法的返回值
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:http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx
1 public class A 2 { 3 public virtual int method () {return 0;} 4 } 5 6 public class B 7 { 8 public virtual int method () {return 1;} 9 } 10 11 class Mymethodinfo 12 { 13 public static int Main() 14 { 15 Console.WriteLine ("/nReflection.MethodInfo"); 16 A MyA = new A(); 17 B MyB = new B(); 18 19 // Get the Type and MethodInfo. 20 Type MyTypea = Type.GetType("A"); 21 MethodInfo Mymethodinfoa = MyTypea.GetMethod("method"); 22 23 Type MyTypeb = Type.GetType("B"); 24 MethodInfo Mymethodinfob = MyTypeb.GetMethod("method"); 25 26 // Get and display the Invoke method. 27 Console.Write("/nFirst method - " + MyTypea.FullName + 28 " returns " + Mymethodinfoa.Invoke(MyA, null)); 29 Console.Write("/nSecond method - " + MyTypeb.FullName + 30 " returns " + Mymethodinfob.Invoke(MyB, null)); 31 return 0; 32 } 33 }
C# 动态加载(转)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。