C# 步入委托(一)

   C#的委托是每个程序员需要掌握的知识,它更好的处理了面向对象的开发。但是很多时候学习起来不是那么易入门,所以有必要和大家分享一下委托的知识

   委托就就好比一个代理公司,它只做中间处理,个人和企业不需要知道他是怎么处理的。

   1:定义  

   2:声明

   3:实例化

   4:作为参数传递

   5:使用委托

   这个概念比较抽象,我们还是直接看实例吧

   要做一个计算器

   1包括四种算法 加减乘除

    protected void JiaF(int a, int b)
    {
        Response.Write("+:" + (a + b).ToString() + "<br>");
    }
    protected void JianF(int a, int b)
    {
        Response.Write("-:" + (a - b).ToString() + "<br>");
    }
    protected void ChengF(int a, int b)
    {
        Response.Write("*:" + (a * b).ToString() + "<br>");
    }
    protected void ChuF(int a, int b)
    {
        Response.Write("/:" + (a / b).ToString() + "<br>");
    }

    // 定义委托

   delegate void CountDelegate(int a,int b);

   protected void Page_Load(object sender, EventArgs e)
    {

         CountDelegate countDelegate = new CountDelegate(JiaF);  //声明委托

         countDelegate += new CountDelegate(JianF);
         countDelegate += new CountDelegate(ChengF);
         countDelegate += new CountDelegate(ChuF);

          Count(countDelegate, 15, 5);//调用是用委托的方法

    }

     //是用委托

      protected void Count(CountDelegate countDelegate, int a, int b)
     {
        //计算前的事
        countDelegate(a, b);
        //计算后的事
     }

     //代码完成

    说明:是用委托后我们不需要知道计算的同时还执行了什么东西,我们只需知道要执行什么(加 减 乘 除)种的其中一个就行,委托其实就是替我们做中间逻辑转换的一些事情。是不是挺简单的。。。

原文地址:https://www.cnblogs.com/ajun/p/2733911.html