码迷,mamicode.com
首页 > Windows程序 > 详细

C# 委托的学习

时间:2016-10-14 11:50:28      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

    delegate int GetCalculatedValueDelegate(int x, int y);    //定义是个委托实际上就是抽象一类  参数列表形式和返回值相同的函数AddCalculator,SubCalculator这两个该函数的参数形式和返回值的类型就是。
      
    static int AddCalculator(int x, int y)   
    {   
        return x + y;   
    }   
      
    static int SubCalculator(int x, int y)   
    {   
        return x - y;   
    }   
      
    static int Calculator(GetCalculatedValueDelegate del, int x, int y)   //定义一个函数 传入三个参数  第一个参数的类型是一个委托  也就是说委托是一个类型。
    {   
        return del(x, y);  
    }   
      
    static void Main(string[] args)   
    {   
        Console.WriteLine(Calculator(AddCalculator, 10, 20));   
    }   

在上面的例子中,Calculator函数的第一个参数就是一个委托。事实上,Calculator对x和y将会做什么处理,它本身并不知道,如何处理x和y由GetCalculatedValueDelegate来决定。那么在Main方法里,我们将AddCalculator方法作为参数传递给Calculator,表示让Calculator用AddCalculator的逻辑去处理x和y。这也很形象:Calculator说:“我不知道要怎么处理x和y,让del去处理好了!”于是就把x和y扔给了del。

 

 

 

lamada表达式的应用

 

n=>n%2==0;

等价于

delegate(int n){ return n%2==0;}

C# 委托的学习

标签:

原文地址:http://www.cnblogs.com/c-x-a/p/5959745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!