表达式树String.IndexOf方法 [英] Expression tree for String.IndexOf method
问题描述
我应该如何构建表达树 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屋!