动态Lambda表达式打印HelloWorld

最近在用C#与数据库打交道。开发过程中采用了ORM模型(以前是纯sql玩法,复杂的逻辑用存储过程做)。

为了能通过配置文件动态地查询字段,也就是说需要能这样写:

 db.AsQuery<T>.Select("字段")//伪代码 

通过多方查找终于找到了方案,那就是用动态Lambda表达式树(.net3.5以后的版本支持)。

后来看别人写的ORM代码中,将C#代码转为SQL语句时出采用了表达式树,所以马上提起了学习兴趣。

先写着写一个hello world ,就是动态地拼出一个 x=>Console.WriteLine(x);

1 Action<String> action = x => Console.WriteLine(x);
2 action("hello world");

代码如下:

 1 //参数 x => Console.WriteLine(x) 中 最前面的那个 x
 2             var para = Expression.Parameter(typeof(String), "x");
 3             //找到 onsole.WriteLine(String value) 这个版本
 4             MethodInfo method = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) });
 5             //拼接 Console.WriteLine(x) 方法体
 6             var call = Expression.Call(null, method, para);
 7             //拼接成 x => Console.WriteLine(x) 格式
 8             var lambda = Expression.Lambda<Action<String>>(call, para);
 9             //转换成委托
10             var action = lambda.Compile();
11             action("hello world");

以下为运行的时候看到的效果

先写一个做为入门,慢慢研究。

原文地址:https://www.cnblogs.com/lclblog/p/6679810.html