如何将 Linq 表达式转换为 Func<> 以使用?

问题描述

我构建了一个表达式树,它似乎产生了一个 Expression<Func<object,bool>> 类型的表达式和一个我认为是我想要的返回类型 bool。但是当我尝试将它编译成 Func<object,bool> 时,我得到以下 System.ArgumentException:

“类型'System.Func`2[System.Object,System.Boolean]'的表达式不能用于返回类型'System.Boolean”

我的最终目标是创建一个返回函数,我可以在我知道属性名称的不同对象上使用该函数并测试该属性是否满足特定条件。我不明白为什么最后一步失败了,因为从异常看来,我确实有预期的 Expression<Func<object,bool>>,我认为它可以与返回类型 bool 一起使用。代码如下:

public delegate Expression ComparisonExpressionDelegate(Expression property,Expression value);
public class ConditionCompiler
{
    public class TestClass
    {
        public string StringProperty1 { get; set; }
        public string StringProperty2 { get; set; }
        public string StringProperty3 { get; set; }
        public int IntProperty1 { get; set; }
        public double DoubleProperty1 { get; set; }
    }
    public static Func<object,bool> test() //This is called
    {
        PropertyInfo property = typeof(TestClass).GetProperty(nameof(TestClass.StringProperty1));
        object value = "1";
        return CompileExpression(property,value);
    }
    public static Func<object,bool> CompileExpression(PropertyInfo property,object value)
    {
        ParameterExpression obj = Expression.Parameter(typeof(object),"obj");
        Expression resultExpression = CreateExpression(property,value);
        Func<object,bool> resultLambda
            = Expression.Lambda<Func<object,bool>>(resultExpression,obj).Compile(); //Issue is here
        return resultLambda;
    }

    public static Expression CreateExpression(PropertyInfo property,"obj");
        bool isgetmethodStatic = property.Getgetmethod().Isstatic;
        UnaryExpression typedTarget = Expression.Convert(obj,property.DeclaringType);
        MemberExpression memberAccess = Expression.Property(isgetmethodStatic ? null : typedTarget,property);
        UnaryExpression BoxedGetter = Expression.TypeAs(memberAccess,typeof(object));
        ConstantExpression valueExpression = Expression.Constant(value);
        ComparisonExpressionDelegate comparisonExpressionDelegate = ToString_Equals_ToString_Expression;
        Expression conditionExpression = comparisonExpressionDelegate(BoxedGetter,valueExpression);
        LambdaExpression conditionExpressionLambda = Expression.Lambda(conditionExpression,obj);
        return conditionExpressionLambda;
    }
    private static ComparisonExpressionDelegate ToString_Equals_ToString_Expression
        = (property,value) => Expression.Equal(
            Expression.Call(
                typeof(string),nameof(String.Compare),null,Expression.Call(property,"ToString",null),value,Expression.Constant(StringComparison.OrdinalIgnoreCase)
                ),Expression.Constant(0)
            );
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)