using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Reflection; using Ical;//引入接口类库 namespace Reflection1 { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void btnReflection_Click(object sender, EventArgs e) { //ICalculator objCal = new CalDLL.Calculator(); //动态加载程序集并创建对象 //ICalculator objCal = // (ICalculator)Assembly.LoadFrom("CalDLL.dll").CreateInstance("CalDLL.Calculator"); //类的程序集下面的DLL. 只需要在命名空间中引用接口库Ical,而不需要引用类库CalDLL. 通过字符串可以找到CalDLL.Calculator ICalculator objCal = (ICalculator)Assembly.Load("CalDLL").CreateInstance("CalDLL.Calculator"); //类的程序集 //通过接口运算完成 int result = objCal.Add(Convert.ToInt32(this.txtNum1.Text.Trim()), Convert.ToInt32(this.txtNum2.Text.Trim())); this.txtResult.Text = result.ToString(); } } }
新建一个类库CalDLL, 下面包含了类 Calculator
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CalDLL { public class Calculator : Ical.ICalculator { public int Add(int a, int b) { return a + b; } public int Sub(int a, int b) { return a - b; } } }
新建一个接口类库Ical, 下面包含了 ICalculator 接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ical { public interface ICalculator { int Add(int a ,int b); int Sub(int a, int b); } }