利用反射中的程序集类(Assembly--抽象类)动态加载类库(.dll)或者可执行程序(.exe).
优点:①.可以消除if条件的逻辑判断.②.减少内存资源.③.有利于程序扩展.
缺点...
使用静态方法LoadFrom()加载外部.dll实例.
//Assembly程序集中有三个加载程序集的方法(Load()、LoadFrom()和LoadFile()). private void btnassembly_Click(object sender, EventArgs e) { // object instance = Assembly.LoadFrom(@"D:c#demoC#高级话题myTestdllinDebugmyTestdll.dll").CreateInstance("myTestdll.TestDLL"); Assembly am = Assembly.LoadFrom(@"D:c#demoC#高级话题myTestdllinDebugmyTestdll.dll"); Type type = am.GetType("myTestdll.TestDLL"); //绝对路径,即名称空间.类名. //object obj = Activator.CreateInstance(type);//获取属性. //MethodInfo GetValue = type.GetMethod("mGetValue"); //根据方法名获取MethodInfo对象 object instance = am.CreateInstance("myTestdll.TestDLL");//调用实例方法 //方法名称. 参数. int sum = (int)type.InvokeMember("mGetValue", BindingFlags.Default | BindingFlags.InvokeMethod, null, instance, new object[] {2,3 });//sum=5 }
DLL代码:
namespace myTestdll { public class TestDLL:myClass<int> { public override int mGetValue(int value1, int value2) { return value1 + value2; } } public abstract class myClass<T> where T : struct//约束T只能是值类型(int、decimal、double...). { public T _pvalue; public T PValue { get { return _pvalue; } set { _pvalue = value; } } public abstract T mGetValue(T value1,T value2); } }
调用dll中封装的窗体:
1》新建类库项目--》添加窗体。
2》其他项目加载该dll:
//直接引用封装了窗体的dll来实例化是可以的。 //TCPServerDll_From dll_From = new TCPServerDll_From(); //dll_From.Show(); //反射调用dll中的窗体。 Assembly outerAsm = Assembly.LoadFrom(@"D:C#Demo cp相关TCPDemoTCPServerDllinDebugTCPServerDll.dll"); Type outerForm = outerAsm.GetType("TCPServerDll.TCPServerDll_From", false);//找到指定窗口(格式:名称空间.类名) if (outerForm != null) { Form dll_form = (Activator.CreateInstance(outerForm) as Form); dll_form.MdiParent = this; dll_form.Show();//转换成窗体类,显示 }