关于委托和Lambda表达式的小例子
ET框架的协程锁用到了Expression<Func<int, bool>> expression,网上查询一下是表达式树,联动了解委托和Lambda表达式,写了几个对比小例子增进理解。
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace TestLambda
{
class Program
{
static void Main()
{
Test1();
Test2();
Test3();
Test4();
Test5();
}
//显式声明委托类型,附带string参数
delegate void TestDelegate(string str);
//实例化TestDelegate,理解为创建一个名为testDelegete的指针,绑定一个匿名函数来执行相关代码
static void Test1()
{
TestDelegate testDelegate = delegate (string str) { Console.WriteLine(str); };
testDelegate("Test1:testDelegate"); //通过调用委托实例执行相关代码
}
//Lambda表达式,使用Action无需显式声明委托
static void Test2()
{
Action testAction1 = () => { Console.WriteLine("Test2:testAction"); };
testAction1();
Action<string> testAction2 = (str) => { Console.WriteLine(str); };
testAction2("Test2:testAction<string>1");
testAction2("Test2:testAction<string>2");
}
//Lambda表达式,Action作为参数传递
static void Test3()
{
Action<string> testAction = (str) => { Console.WriteLine(str); };
TestFuc1(testAction);
}
static void TestFuc1(Action<string> testAction)
{
testAction("Test3:testAction");
Console.WriteLine("Test3:TestFuc1");
}
//通过表达式树将表达式作为参数传递,传递参数作为表达式参数
static void Test4()
{
TestFuc2(i => i < 5, 5);
}
static void TestFuc2(Expression<Func<int, bool>> expression, int i)
{
Func<int, bool> deleg = expression.Compile();
Console.WriteLine("Test4:" + expression);
Console.WriteLine($"Test4:deleg({i}) = {deleg(i)}");
}
//通过表达式树将表达式作为参数传递,T作为参数传递给i和s
static void Test5()
{
TestFuc3<int>(i => i.ToString());
TestFuc3<string>(s => s.ToString());
}
static void TestFuc3<T>(Expression<Func<T, string>> expression)
{
Console.WriteLine("Test5:" + expression);
Console.WriteLine("Test5:" + typeof(T).ToString());
}
}
}
//输出结果
//Test1:testDelegate
//Test2:testAction
//Test2:testAction<string>1
//Test2:testAction<string>2
//Test3:testAction
//Test3:TestFuc1
//Test4:i => (i < 5)
//Test4:deleg(5) = False
//Test5:i => i.ToString()
//Test5:System.Int32
//Test5:s => s.ToString()
//Test5:System.String
//相关要点
//Lambda表达式:Action<参数类型> 委托实例名 = (参数,参数)=>{ 执行代码; };
//表达式把定义委托实例再传参数合并
//如果是无参数,参数类型和参数名留空即可:Action<> 委托实例名 = () => { 执行代码; };
//如果需要将一个Lambda表达式作为参数传递,需要使用表达式树定义参数:Expression<Func<T, string>> expression