我眼中的委托

/** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 

    一千读者心中有有一千个哈姆雷特,.Net中的委托也是一样。

    直白点讲委托的话,就是一种以方法为参数的传递方式概念我想是差不多了吧,毕竟概念这东西,只是书面语,没有实例那么容易理解。

    坦白说,我做了近两年的开发,还没有自己定义过委托,如果你说使用过.net框架里面已经封装的那就罢了,因为那是微软封装好的,我也不是大牛,没挖掘理解过。

    好歹是涉足这方面的菜鸟,一些基本功还是需要修炼好。常挤出一些时间来学习是必要的。尤其像微软的东西,知识的更新太频繁了。你永远学不到尽头,只能是不断上下求索(路漫漫其修远兮,吾将上下而求索)。

**** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ***/

使用委托可以概括如下几步:

(1)定义委托  

  =》delegate int DelegateOperation(int firstNum, int secondNum);

(2)定义跟委托相同签名的函数

 =》public int add(int firstNum, int secondNum)

 =》public int minus(int firstNum, int secondNum)

 =》说明:委托与函数的签名相同,此例是返回整型、传递两个整型的参数

(3)声明委托,并将委托指向相同签名的函数

 =》常见写法一:DelegateOperation test =  new DelegateOperation(oper.add);

 =》特殊写法类似二: 委托类型 变量 += new 委托类型(注册的委托方法);

      DelegateOperation test +=  new DelegateOperation(oper.add);

      DelegateOperation test -=  new DelegateOperation(oper.add); 

  委托别人比较勤快,可以执行所谓的委托链(增加、减少委托)

       

(4)执行委托,也就是调用委托指向的方法

 =》firstNum = test(100, 20);

 =》说明:其中变量test指向委托实例,DelegateOperation test = new DelegateOperation(oper.add);

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DeleteTest
{

    delegate int DelegateOperation(int firstNum, int secondNum);

    class Operation
    {
        public int add(int firstNum, int secondNum)
        {
            int result = firstNum + secondNum;
            return result;
        }

 
        public int minus(int firstNum, int secondNum)
        {
            int result = firstNum - secondNum;
            return result;
        }
    }

     class Program
    {
        static void Main(string[] args)
        {
            Operation oper = new Operation();

             //求(100+20) + (100-20)
            int result = 0;
            int firstNum = 0;
            int secondNum = 0; 

            DelegateOperation test = null; 

            //求和
              test = new DelegateOperation(oper.add);
            firstNum = test(100, 20);

            //求差
              test = new DelegateOperation(oper.minus);
            secondNum = test(100, 20);

             //再求和
              result = test(firstNum, secondNum);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/csdbfans/p/3293287.html