表达式树String.IndexOf方法 [英] Expression tree for String.IndexOf method

查看:163
本文介绍了表达式树String.IndexOf方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何构建表达树 string.IndexOf(串,StringComparison.OrdinalIgnoreCase)

How should I construct Expression tree for string.IndexOf("substring", StringComparison.OrdinalIgnoreCase)?

我可以得到它没有第二个参数工作: StringComparison.OrdinalIgnoreCase 。这些是我尝试到目前为止:

I can get it working without the second argument: StringComparison.OrdinalIgnoreCase. These are my attempts so far:

var methodCall = typeof (string).GetMethod("IndexOf", new[] {typeof (string)});
Expression[] parms = new Expression[]{right, Expression.Constant("StringComparison.OrdinalIgnoreCase", typeof (Enum))};
var exp =  Expression.Call(left, methodCall, parms);
return exp;



也试过这样:

Also tried this:

var methodCall = typeof (string).GetMethod(method, new[] {typeof (string)});
Expression[] parms = new Expression[]{right, Expression.Parameter(typeof(Enum) , "StringComparison.OrdinalIgnoreCase")};
var exp =  Expression.Call(left, methodCall, parms);
return exp;

请记住,我可以得到它的工作,如果我忽略 OrdinalIgnoreCase 参数。

Please remember that I can get it working if I ignore the OrdinalIgnoreCase parameter.

感谢

推荐答案

我怀疑。有两个问题。

第一个是你得到法的方式 - 你的询问的为只有一个单一的方法字符串参数,而不是一两个参数:

The first is the way you're getting the method - you're asking for a method with only a single string parameter, instead of one with two parameters:

var methodCall = typeof (string).GetMethod("IndexOf",
                            new[] { typeof (string), typeof(StringComparison) });



第二个是的的你给 - 它应该是常量,而不是字符串的实际值:

The second is the value you're giving - it should be the actual value of the constant, not a string:

Expression[] parms = new Expression[] { right, 
    Expression.Constant(StringComparison.OrdinalIgnoreCase) };



编辑:这是一个完整的工作示例:

Here's a complete working sample:

using System;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        var method = typeof (string).GetMethod("IndexOf",
                new[] { typeof (string), typeof(StringComparison) });

        var left = Expression.Parameter(typeof(string), "left");
        var right = Expression.Parameter(typeof(string), "right");

        Expression[] parms = new Expression[] { right, 
                Expression.Constant(StringComparison.OrdinalIgnoreCase) };

        var call = Expression.Call(left, method, parms);
        var lambda = Expression.Lambda<Func<string, string, int>>
            (call, left, right);

        var compiled = lambda.Compile();
        Console.WriteLine(compiled.Invoke("hello THERE", "lo t"));
    }
}

这篇关于表达式树String.IndexOf方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆