【C#】委托和Lambda表达式

 

一、方法

Public static void Method1(string name)

{

        Console.WriteLine(string);

}

二、委托

委托就是表示方法的类型。声明委托本质上就是声明一个类。为了减少自定义委托类型,.NET3.5中,包含一组通用的委托,大部分都是泛型委托。

根据方法的返回值类型,将方法分为返回void和有返回值。有返回值的方法用System.Func系列委托表示;返回void的方法用System.Action系列委托表示。

Public static bool GreaterThan(int first,int second)

{

        Return first > second;

}

该方法就可用System.Func系列委托表示,声明委托实例代码如下:

Func<int,int,bool>  comparisonMethod = new Func<int,int,bool>(GreaterThan);

Func委托的最后一个类型总是对应委托的返回类型,这里是bool类型。其他参数类型依次对应于委托参数的类型。

如果不使用System.Func,也可以自己声明委托,效果都是一样的。代码如下:

Public delegate bool GreaterThanDelegate(int first,int second);

GreaterThanDelegate greaterThanDelegate = new GreaterThanDelegate(GreaterThan);

三、Lambda表达式

要创建一个委托对象,需要声明一个方法如GreaterThan,声明一个委托如GreaterThanDelegate,最后在实例化greaterThanDelegate对象。为了简化这个过程,可以使用匿名方法或者Lambda表达式,二者的作用是相同的,只是写法有区别。

Public static bool GreaterThan(int first,int second)

{

        Return first > second;

}
 
Public delegate bool GreaterThanDelegate(int first,int second);

GreaterThanDelegate greaterThanDelegate = new GreaterThanDelegate(GreaterThan);

// BubbleSort方法需要用到Delegate类型的参数

BubbleSort(items, greaterThanDelegate);

使用匿名方法:

BubbleSort(items,

Delegate(int first,int second)

{

        Return first < second;

}

);

使用Lambda表达式:

BubbleSort(items,

(int first,int second) =>

{

return first < second;

}

);

通过这两种写法,可以简化创建委托实例的过程。

 

Lambda表达式分为语句Lambda和表达式Lambda,表达式Lambda更加简洁。

语句lambda由形参列表,后跟Lamnda操作符=>,然后跟一个代码块构成。

跟完整的方法声明相比,语句Lambda可以省略方法名、可访问性、返回类型、甚至可以不指定参数类型。

 

匿名方法必须显式指定参数类型,必须有一个语句块,并在参数列表前添加delegate关键字。

 

四、总结:

完整方法声明➡匿名方法➡语句Lambda➡表达式Lambda是方法的表达方式越来越简化的过程。本质上都是表示一个方法。

posted @ 2020-07-09 13:08  旋转的地球  阅读(405)  评论(0编辑  收藏  举报