1 回答
TA贡献1780条经验 获得超5个赞
我认为你使用活页夹使事情变得过于复杂。ExpandoObject实现IDictionary<string, object>接口,因此您可以替换x => x.FirstName == "Jonas"为x => x["FirstName"] == "Jonas"哪个应该更容易。另外,您必须重写VisitLambda, 来修改类型参数,否则转换将失败。
这是示例代码:
public class ReplaceToExpandoVisitor<TSource> : ExpressionVisitor
{
private static readonly PropertyInfo ItemProperty = typeof(IDictionary<string, object>).GetProperty("Item");
private readonly ParameterExpression _targetParameter = Expression.Parameter(typeof(ExpandoObject));
protected override Expression VisitLambda<T>(Expression<T> node)
{
var body = this.Visit(node.Body);
var parameters = node.Parameters.Select(this.Visit).Cast<ParameterExpression>();
return Expression.Lambda(body, parameters);
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (node.Type == typeof(TSource))
{
return this._targetParameter;
}
return node;
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Member.MemberType != MemberTypes.Property)
{
throw new NotSupportedException();
}
string memberName = node.Member.Name;
return Expression.Convert(
Expression.Property(
this.Visit(node.Expression),
ItemProperty,
Expression.Constant(memberName)
),
((PropertyInfo)node.Member).PropertyType
);
}
}
用法:
Expression<Func<MyEntity, bool>> exp = x => x.FirstName == "Jonas";
Expression<Func<ExpandoObject, bool>> exp2 = (Expression<Func<ExpandoObject, bool>>) new ReplaceToExpandoVisitor<MyEntity>().Visit(exp);
dynamic obj = new ExpandoObject();
obj.FirstName = "Jonas";
bool result = exp2.Compile().Invoke(obj);
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报