zoukankan      html  css  js  c++  java
  • 委托的经典用法计算器实例来自王涛《你必须知道的.NET》

    新增的委托类,定义如下:

    public class DelegateEx
      {
        //声明一个委托
        public delegate void CalculateDelegate(Int32 x, Int32 y);

        //委托关联方法1-实现加法-注意两者的《返回值》《参数》必须相同
        public static void Add(Int32 x, Int32 y)
        {
          MessageBox.Show("加法结果:"+(x+y));
        }

        //委托关联方法2-实现减法
        public static void Subtract(Int32 x, Int32 y)
        {
          MessageBox.Show("减法结果:"+(x-y));
        }

        //委托关联方法3-实现乘法-复制上面的
        public static void Multiply(Int32 x, Int32 y)
        {
          MessageBox.Show("乘法结果:" + (x * y));
        }

        //委托关联方法4-实现div法
        public static void Divide(Int32 x, Int32 y)
        {
          MessageBox.Show("整除结果:" + (x / y));
        }
      }

    Form1.cs类实现如下:

      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }

        //定义委托类型变量
        private DelegateEx.CalculateDelegate myDelegate;

        private void button1_Click(object sender, EventArgs e)
        {
          try
          {
            //取加法的两个元
              Int32 x = Convert.ToInt32(textBox1.Text);
              Int32 y = Convert.ToInt32(textBox2.Text);
            //
            myDelegate = new DelegateEx.CalculateDelegate(DelegateEx.Add);
            myDelegate(x,y);
          }
          catch (FormatException fe)
          {         
          }
        }

        private void button2_Click(object sender, EventArgs e)
        {
          try
          {
            //
            int x = Convert.ToInt32(textBox1.Text);
            int y = Convert.ToInt32(textBox2.Text);

            myDelegate = new DelegateEx.CalculateDelegate(DelegateEx.Subtract);
            myDelegate(x, y);
           }
          catch (System.FormatException fe)
          {
          }
        }

        private void button3_Click(object sender, EventArgs e)
        {
          try
          {        //
            int x = Convert.ToInt32(textBox1.Text);
            int y = Convert.ToInt32(textBox2.Text);

            //如何增加委托到委托链
            myDelegate = new DelegateEx.CalculateDelegate(DelegateEx.Add);
            myDelegate += new DelegateEx.CalculateDelegate(DelegateEx.Subtract);
            myDelegate += new DelegateEx.CalculateDelegate(DelegateEx.Multiply);
            myDelegate += new DelegateEx.CalculateDelegate(DelegateEx.Divide);

            //使用方法一样
            myDelegate(x, y);
          }
          catch (FormatException fe)
          {
          }
        }
      }

    解释一下:上面用Convert类转换类型时候,可能有异常,所以捕捉一下,不过我没处理~

  • 相关阅读:
    Spring注入内部的Beans
    Spring基于Setter函数的依赖注入(DI)
    Jenkins中的Job配置里缺少“触发远程构建(例如,使用脚本)”选项的问题解决
    Spring基于构造函数的依赖注入(DI)
    音频中采样位数,采样率,比特率的名词解释(转)
    无损音乐知识收集3(转)
    无损音乐知识收集2(转)
    无损音乐知识收集1(转)
    Spring的依赖注入概述
    Spring的IoC容器概述
  • 原文地址:https://www.cnblogs.com/lizunicon/p/1167489.html
Copyright © 2011-2022 走看看