2

.NET知识梳理——6.lambda

 2 years ago
source link: https://www.cnblogs.com/Olive116/p/12362203.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1. lambda

1.1        匿名方法lambda表达式

Lambda表达式

Lambda是一个匿名方法,实例化委托的一个参数,编译的时候会产生一个密封类,同时增加一个方法。

Lambda表达式的演化

过程如下:

public delegate void ShowInfo(string name, int age);

1.1.1  .NET Framework 1.0

ShowInfo showInfo = new ShowInfo(GetInfo);

showInfo.Invoke("Olive", 16);

1.1.2  .NET Framework 2.0 匿名方法,delegate关键字

showInfo = new ShowInfo(delegate (string name, int age) {

                Console.WriteLine($"2.0:Age is {age},Name is {name}");

            showInfo.Invoke("墨遥", 30);

1.1.3  .NET Framework 3.0 去掉delegete关键字,增加一个箭头

showInfo = new ShowInfo((string name, int age) => {

                Console.WriteLine($"3.0:Age is {age},Name is {name}");

            showInfo.Invoke("XF", 116);

            showInfo = new ShowInfo((name, age) =>//省略参数类型,编译器的语法糖,根据委托推算,编译时有类型

                Console.WriteLine($"语法糖:Age is {age},Name is {name}");

            showInfo.Invoke("HY", 20);

showInfo = new ShowInfo((name, age) => Console.WriteLine($"语法糖:Age is {age},Name is {name}   如果方法体只有一行,可以去掉大括号"));

            showInfo("遥", 21);

            showInfo=(name,age)=>Console.WriteLine($"语法糖:Age is {age},Name is {name}   可以省略new 委托 ");

            showInfo("哈哈", 18);

1.2        匿名类 var 扩展方法

1.2.1 匿名类 var

.NET Framework 3.0 出现匿名类var。如下所示:

var person = new { Id = 1, Name = "Olive", Age = 16 };

//匿名类属性只能在创建时赋值,不能修改属性值

1.2.2 扩展方法

扩展方法,静态类中的静态方法,第一个参数前加this 修饰

    public static class ExtendMethod

        public static void ShowInfo(this Person p)

            Console.WriteLine($"Person Info is Id={p.Id},Name={p.Name},Age={p.Age}");

调用如下:

  Person p = new Person() { Id = 116, Name = "Olive", Age = 30 };

            p.ShowInfo();//ShowInfo即为扩展方法,Person本身并无此方法。

扩展方法调用,很像实例方法,就像扩展了Person的逻辑

扩展方法的使用场景:

  1. 第三方的类,不适合修改源码,可以通过扩展方法增加逻辑
  2. 适合组件式开发的扩展(.NetCore),定义接口或者类,是按照最小需求,但是在开发的时候又经常需要一些方法,就通过扩展方法
  3. 扩展一些常见操作(会污染基础类型,一般少为object  没有约束的泛型去扩展)               

1.3        Linq to object

Linq To Object 是在Enumerable类,针对IEnumerable数据(指的是内存数据)进行的一些列的封装。

Where:把对数据过滤的通用操作完成,把可变的过滤逻辑交给委托

Select:把对数据转化的通用操作完成,把可变的转换逻辑交给委托

OrderBy:排序


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK