委托—>匿名方法—>Func && Anction—>Lamda诞生—->Lamda异步
委托
public delegate void AddDelegate(int a,int b);
public void Run()
{
AddDelegate add = new AddDelegate(Add);
add(1,5);
}
public void Add(int a,int b)
{
Console.WriteLine(a+b);
}
匿名方法
public delegate int AddDelegate(int a,int b);
public void Run()
{
Test1();
Test2();
}
/// <summary>
/// 第一次进化
/// </summary>
void Test1()
{
AddDelegate add = new AddDelegate(delegate(int a,int b) { return a + b; });
int num = add(1, 5);
Console.WriteLine(num);
}
Func&&Action
/// <summary>
/// 第二次进化
/// </summary>
void Test2()
{
Func<int, int, string> add = new Func<int, int, string>(delegate(int a,int b) { int num = a + b;return "result is:"+num; });
Console.WriteLine(add(10,23));
}
public void Run()
{
Test(ResultOK,ResultError);
}
void Test(Action ok,Action error)
{
if (true)
ok();
else
error();
}
void ResultOK()
{
Console.WriteLine("OK");
}
void ResultError()
{
Console.WriteLine("Error");
}
Lamda诞生
/// <summary>
/// 原始
/// </summary>
void T1()
{
Func<int, int, string> Add = delegate (int a, int b) { int num = a + b; return (a + b).ToString(); };
Console.WriteLine(Add(300, 400));
}
/// <summary>
/// 多参数
/// </summary>
void T2()
{
Func<int, int, string> Add = (int a, int b) => { int num = a + b; return (a + b).ToString(); };
Add = (a, b) => { return (a + b).ToString(); };
Add = (a,b) => (a + b).ToString();
Console.WriteLine(Add(6, 400));
}
/// <summary>
/// 单参数
/// </summary>
void T3()
{
Func<int,int> add= (a) => 10 + a;
add = a => 10 + a;
}
Lamda异步
public void Run()
{
///无返回值的类型,可以直接用Wait代替!!!!!!!!!!
T1().Wait();
}
/// <summary>
/// 异步操作
/// </summary>
/// <returns></returns>
async Task T1()
{
Func<string, Task<string>> func = async t => { await Task.Delay(300); Console.WriteLine(t); return "aa"; };
string data = await func("aaa");
Console.WriteLine(data);
Func<int, int, Task> func1 = async (a, b) => { await Task.Delay(500); Console.WriteLine(a + b); };
func1(10, 20).Wait() ;
}
标签:Lamda,Console,Func,int,void,Add,WriteLine,进化史 From: https://blog.51cto.com/u_11295556/5904995