First, we need to encapsulate a dll and create a class library under VS2008, the code is as follows: using System; using System.Collections.Generic; using System.Linq; using using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace dll
{ public class addclass { public static Int32 add(Int32 i, Int32 j) { return i + j; } }
}
Compile to generate dll.dll, where the class name is addclass, and the method is add. Next, to call this dll.dll in the main program, you need to copy this dll.dll to the bin\Debug folder of the main program. Dynamic reference dll requires using System.Reflection; This reflection namespace. private void test() { Assembly ass = Assembly.Load("dll"); Load the dll file Type tp = ass. GetType("dll.addclass"); To obtain the class name, you must use namespace + class name Object obj = Activator.CreateInstance(tp); Establish an instance MethodInfo meth = tp. GetMethod("add"); How to get it int t = Convert.ToInt32( meth. Invoke(obj, new Object[]{2, 3}) ); Invoke calling method MessageBox.Show(t.ToString()); }
The above is the method of dynamically calling the dll, you can also use the reference --> method to add a reference (dll.dll) for pre-loading, and match the namespace name of the using dll. to use. In the main program, use int t= addclass.add(2, 3); That's it.
System.Text; namespace dll
{ public class addclass { public static Int32 add(Int32 i, Int32 j) { return i + j; } }
} |