(精华)2020年8月11日 C#基础知识点 Lambda表达式
public class LambdaShow
{<!-- -->
public delegate void NoReturnNoPara();//无参数无返回值委托
public delegate void NoReturnWithPara(string x, string y);//有参数无返回值委托
public delegate int WithReturnNoPara();
public delegate string WithReturnWithPara(out int x, ref int y);
public void Show()
{<!-- -->
//lambda演变历史
{<!-- -->
Console.WriteLine("***********************.NetFramework1.0****************************");
//.NetFramework1.0/1.1时代
NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
NoReturnWithPara noReturnWithPara = new NoReturnWithPara(this.Study);
noReturnWithPara.Invoke("参数一", "参数二");
}
int i = 10;
{<!-- -->
Console.WriteLine("***********************.NetFramework2.0****************************");
//.NetFramework2.0 匿名方法,增加了一个delgate关键字 可以访问局部变量
NoReturnWithPara noReturnWithPara = new NoReturnWithPara(delegate (string x, string y)
{<!-- -->
Console.WriteLine(i);
Console.WriteLine("我是匿名委托");
});
noReturnWithPara.Invoke("参数一", "参数二");
}
{<!-- -->
Console.WriteLine("***********************.NetFramework3.0****************************");
//.NetFramework3.0 去掉delegate关键字,添加了一个=> goes to
NoReturnWithPara noReturnWithPara = new NoReturnWithPara((string x, string y) =>
{<!-- -->
Console.WriteLine(i);
Console.WriteLine("This is Study");
});
noReturnWithPara.Invoke("元让", "阳光下的微笑");
}
{<!-- -->
NoReturnWithPara noReturnWithPara = new NoReturnWithPara((x, y) => // 通过委托自动推断来的(语法糖)
{<!-- -->
Console.WriteLine(i);
Console.WriteLine("This is Study");
});
noReturnWithPara.Invoke("参数一", "参数二");
}
{<!-- -->
NoReturnWithPara noReturnWithPara = new NoReturnWithPara((x, y) => Console.WriteLine("This is Study")
);
noReturnWithPara.Invoke("参数一", "参数二");
}
{<!-- -->
NoReturnWithPara noReturnWithPara = (x, y) => Console.WriteLine("This is Study");
noReturnWithPara.Invoke("参数一", "参数二");
}
{<!-- -->
Action<string, string> action = (x, y) => Console.WriteLine($"{x}_{y}");
Action<string> action1 = x => Console.WriteLine($"{x}"); // 如果只有一个参数的时候,可以省略小括号
Func<string, string> func = x => "代码男孩";
Func<string> func1 = () => "代码男孩"; //如果有返回值,而且方法体只有一行,可以省略return;
}
// 通过反编译之后,发现Lambda表达式生成在一个名称为<> 密封类中的一个方法;
{<!-- -->
//lambda在多播委托
NoReturnWithPara noReturnWithPara = new NoReturnWithPara(this.Study);
noReturnWithPara += this.Study;
noReturnWithPara += (x, y) =>
{<!-- -->
Console.WriteLine($"{x}_{y}");
};
noReturnWithPara -= this.Study;
noReturnWithPara -= (x, y) => {<!-- --> Console.WriteLine($"{x}_{y}"); }; //lambda表达式在多播委托中不能被移除
noReturnWithPara("哗哗", "便便");
}
}
private void DoNothing()
{<!-- -->
Console.WriteLine("无参数无返回值委托");
}
private void Study(string x, string y)
{<!-- -->
Console.WriteLine("有参数无返回值委托");
}
}