如何根据string生成lambda方法?或者类似实现方法?
public static void Test()
{
var data = new Info { id = 1, name = "test", birthday = DateTime.Now };
string[] props = { "id", "birthday" };//可变
var fn = "(Info info)=>info." + string.Join("+info.", props);
var lambda=???
var str = lambda(data);
}
public class Info
{
public int id { get; set; }
public string name { get; set; }
public DateTime birthday { get; set; }
}
using System.Linq.Expressions;
using System.Linq.Dynamic;
public static void Test() { var data = new Info { id = 1, name = "test", birthday = DateTime.Now }; string[] props = { "id", "birthday" };//可变 //var fn = "info." + string.Join("+info.", props);//注释掉是因为 id 和 birthday 类型无法相加 var fn = "Info.id.ToString()+Info.birthday.ToString()";//这里只是举例,具体可以自己拼写可运行的动态条件 var p = Expression.Parameter(typeof(Info), "Info"); var lambda = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p },typeof(string), fn); var str = lambda.Compile().DynamicInvoke(data) ; }
System.Linq.Dynamic.dll 下载地址:https://github.com/kahanu/System.Linq.Dynamic
Expression<Func<T, bool>> 你需要这个。
大神,能把表达式写出来吗?
Expression<Func<ImportOrder, bool>> expr = i => i.Active == 0这种形式,这是委托的写法,你去了解下委托的3种写法,明白委托是什么了,就很好写了
能为能把实现写出来?
@木龙哥: 这不就是实现?还是你去看看语法吧