定义:本质上是一个匿名方法,更简单完成委托初始化,还可以让委托实例化的方法访问局部变量
简单实现委托所需要的函数
//方法
public static void Show(string msg)
{
Console.WriteLine(msg);
}
//委托
Action<string> action=new Action<string>(show);
//匿名方法
Action<string> action=new Action<string>(delegate(string msg)
{
Console.WriteLine(msg);
});
// 去除delegate
Action<string> action=new Action<string>((string msg)=>
{
Console.WriteLine(msg);
});
//一个参数 单个语句
Action<string> action=new Action<string>(msg=>Console.WriteLine(msg));
//无返回值 无参数
Action action=new Action<string>(()=>Console.WriteLine("无"));
// 有返回值 单条语句
Func<string> func=new Func<string>(()=>"无");
//有返回值 多条语句
Func<string> func=new Func<string>(()=>{
Console.WriteLine("无");
return "无";
});
原文:https://www.cnblogs.com/ganph/p/14812799.html