最近在学.net core,里面的Lambda表达式比较让人困惑,不信吗?请看下面的代码:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
第一眼,有点晕,是不是觉得像一个字段?其实它是一个静态的方法,现在看不懂没关系,下面带着你使用最简单的代码讲明白它,如果你看得懂,那么下面的内容你可以不用看了。
好了,废话到此结束,下面进入正题
当Lambda表达式、匿名方法和Linq两两搭配使用时,有时候我们都会怀疑自己是不是没学过C#?这是由于我们平时用得比较少。
其实Lambda的本质是匿名方法,Lambda表达式和匿名方法一般都会与委托搭配使用,Lambda使用场景可以总结为下面3点:
(1) 代替方法的大括号{ },特别是在.net core中的源码中看得比较多,不知是不是写源码那个家伙为了装逼,还是为了提高效率
(2) 充当委托实例(相对于一个匿名方法)
(3) 搭配List集合或者数组使用(Linq查询)
下面以例子的方式进行一一讲述
一 当方法体中只有一句代码时,可以 代替方法的大括号{ }
public class Test
{
public void TestMethod1(string param) => Console.WriteLine("TestMethod1:" + param);
}
public class Program
{
public static void Main(string[] args)
{
Test test = new Test();
test.TestMethod1("1");
}
}
上述代码输出:TestMethod1:1
其实上面的Test类中的TestMethod1可以写成我们经常写的形式:
public void TestMethod1(string param){
Console.WriteLine("TestMethod1:" + param);
}
二 充当委托实例
public class Test
{
public void TestMethod1(string param)
{
//其实下面的(param) => { Console.WriteLine("TestMethod1:" + param); }相当于一个匿名方法,赋值给Action委托
Method((param) => { Console.WriteLine("TestMethod1:" + param); })(param);
}
private Action<string> Method(Action<string> action)
{
return action;
}
}
public class Program
{
public static void Main(string[] args)
{
Test test = new Test();
test.TestMethod1("1");
}
}
上述代码输出:TestMethod1:1
其实上面的Test类中的TestMethod1可以写成我们经常写的形式:
public class Test
{
public void TestMethod1(string param)
{
//匿名方法赋值给委托
Action<string> action = delegate (string str) {
Console.WriteLine("TestMethod3:" +str);
};
Action<string> ReturnAction=Method3(action);
ReturnAction(param);
}
private Action<string> Method(Action<string> action)
{
return action;
}
}
三 搭配List或者数组使用(Linq查询),下面以数组进行说明:
public class Test
{
public void TestMethod1(string param) {
string[] array = {"1","2","3","4","5","6" };
//使用Linq的扩展方法查询数组中与param一样的元素进行返回
var result=array.Where(a => a== param);
foreach (var item in result)
{
Console.WriteLine("TestMethod1:"+item);
}
}
}
public class Program
{
public static void Main(string[] args)
{
Test test = new Test();
test.TestMethod1("1");
}
}
上述代码输出:TestMethod1:1
看到这里,你是否会还原文章最前面的方法IHostBuilder了,先自己还原一下,再看我还原的:
public static IHostBuilder CreateHostBuilder(string[] args) {
IHostBuilder bulider = Host.CreateDefaultBuilder(args);
Action<IWebHostBuilder> action = delegate (IWebHostBuilder webBuilder)
{
webBuilder.UseStartup<Startup>();
};
return bulider.ConfigureWebHostDefaults(action);
}
好了,由于水平有限,如有说得不对的,请多多指教