创建类库,并添加新窗体,加入以下方法
public static string setText(string str) { return str; }
编译后把生成的DLL文件放入新项目的bin目录,新项目需要using System.Reflection窗口放入2个button,并添加实现
//通过反射打开Dll窗体 private void button1_Click(object sender, EventArgs e) { //dll命名空间名 string dllName = "DllDemo"; //dll类名 string dllClassName = "DllDemo.Form1"; //载入并创建实例转为Form类型 Form frm = Assembly.Load(dllName).CreateInstance(dllClassName) as Form; frm.ShowDialog(); }
//通过反射调用Dll中的方法 private void button2_Click(object sender, EventArgs e) { //dll文件路径 string dllName = "DllDemo"; //dll类名 string dllClassName = "DllDemo.Form1"; //加载dll文件 var assembly = Assembly.Load(dllName); //获取类 Type type = assembly.GetType(dllClassName); //创建该类型的实例 object obj = Activator.CreateInstance(type); //获取该类的方法 string str = type.InvokeMember("setText", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { textBox1.Text }).ToString(); MessageBox.Show(str); //缩写 string returnStr = Assembly.Load(dllName) .GetType(dllClassName) .InvokeMember( "setText" , BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static , null , null , new object[] { textBox1.Text } //传入方法参数 ) .ToString(); MessageBox.Show(returnStr); }