我需要编译一个lambda表达式,传递一个生成运行时的对象。这是我到目前为止的代码。
一个例子:
var anonType = new { Name = "Florida" }.GetType();
var myObj = Activator.CreateInstance(anonType, "Florida");
var expression = Expression.Parameter(myObj.GetType(), "Name");
var property = Expression.Property(expression, "Name");
var rule = new Rule("Name", "NotEqual", "Florida");
ExpressionType tBinary;
if (!Enum.TryParse(rule.Operator, out tBinary)) return;
var propertyType = myObj.GetType().GetProperty(rule.MemberName).PropertyType;
var right = Expression.Constant(Convert.ChangeType(rule.TargetValue, propertyType));
var result = Expression.MakeBinary(tBinary, property, right);
var expr = Expression.Lambda<Func<Type, bool>>(result, expression).Compile();
var isValid = expr(anonType);
我在尝试编译Lambda表达式时遇到错误。
Additional information: ParameterExpression of type '<>f__AnonymousType0`1[System.String]' cannot be used for delegate parameter of type 'System.Type'
答案 0 :(得分:2)
不确定您想要实现的目标,但会回答您的直接问题。您可以在这种情况下编译lambda:
// create Func<AnonymousType, bool>
var func = typeof(Func<,>).MakeGenericType(anonType,typeof(bool));
// compile
var expr = Expression.Lambda(func, result, expression).Compile();
// invoke
var isValid = expr.DynamicInvoke(new { Name = "NotFlorida" });