在Expression中使用string.Compare(a,b)

Chu*_*age 1 c# expression expression-trees

从昨天起我一直在教自己表达树,我在比较两个字符串值时遇到了问题.我已经使这个测试用例失败并出现错误:

No method 'Compare' on type 'System.String' is compatible with the supplied arguments.

在运行时失败了 left = Expression.Call(

Type type = typeof(string);
Expression left, right;
left = Expression.Constant("1", type);
right = Expression.Constant("2", type);
// fails at run-time on the next statement
left = Expression.Call(
    typeof(string),
    "Compare",
    new Type[] { type, type },
    new Expression[] { left, right });
right = Expression.Constant(0, typeof(int));
Run Code Online (Sandbox Code Playgroud)

我将在a中使用结果左右Expression.Equal, LessThan, LessThanOrEqual, GreaterThan or GreaterThanOrEqual.这就是Compare方法的原因.

我确信它很简单,我把我的代码简化为这个简单的测试用例.谁知道我哪里出错了?

Jon*_*eet 11

这是您的Expression.Call代码中的问题:

new Type[] { type, type },
Run Code Online (Sandbox Code Playgroud)

那是试图调用string.Compare<string, string>- 它们是通用参数,而不是普通参数的类型.鉴于它是一种非泛型方法,请在此处使用null.

简短但完整的计划:

using System;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        var left = Expression.Constant("1", typeof(string));
        var right = Expression.Constant("2", typeof(string));
        var compare = Expression.Call(typeof(string),
                                      "Compare",
                                      null,
                                      new[] { left, right });
        var compiled = Expression.Lambda<Func<int>>(compare).Compile();
        Console.WriteLine(compiled());
    }
}
Run Code Online (Sandbox Code Playgroud)