使用反射 和接口 做一个计算器

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);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值