c#反射-动态加载dll简单例子

假设已有组件ClassLibraryTEST.dll,放置于程序目录下。组件中ClassLibraryTEST命名空间下有TEST类,类中有方法sum。下面示例就是动态加载组件并调用sum方法的简例:

1 static void Main(string[] args)
2         {
3             string dllPath = string.Format("{0}\\ClassLibraryTEST.dll", System.Environment.CurrentDirectory);//dll组件路径
4             Assembly pAss = Assembly.LoadFile(dllPath);//加载组件
5             Type pType = pAss.GetType("ClassLibraryTEST.TEST");//获得类,ClassLibraryTEST命名空间,TEST类名
6             MethodInfo pMtInfo = pType.GetMethod("sum");//获得方法,sum方法名
7             object o = Activator.CreateInstance(pType);//创建类实例
8             int sum = (int)pMtInfo.Invoke(o, new object[] { 1, 2 });//调用方法
9         }

下面是组件代码:

 1 namespace ClassLibraryTEST
 2 {
 3     public class TEST
 4     {
 5         private int a = 0;
 6         private int b = 0;
 7         public string s = "n";
 8         private int Add(int a,int b)
 9         {
10             return a + b;
11         }
12         public int sum(int a, int b)
13         {
14             return a + b;
15         }
16         private string url = "www.123.com";
17     }
18 }

 

转载于:https://www.cnblogs.com/dullfish/p/6093303.html

你可能感兴趣的:(c#反射-动态加载dll简单例子)