我正在try 为Eumerable.Any(IEnumerable,Func<;T,bool>;)创建表达式树
实际上,我有一个列表,需要判断该列表是否至少有一个包含"test"的元素
所以看起来很简单:
List<string> strings = new List<string> { "element1", "element2", "element3" };
var test = strings.Any(x => x.Contains("test"));
我正在try 创建表达式树,而GetMethod返回NULL,所以我想我错过了一些东西
以下是一个测试代码:
List<string> strings = new List<string> { "element1", "element2", "element3" };
var testString = "test";
ParameterExpression p = Expression.Parameter(typeof(string), "item");
Delegate predicate = Expression.Lambda(
Expression.Call(
p,
typeof(string).GetMethod("Contains", new[] { typeof(string) }),
Expression.Constant(testString)),
p).Compile();
Type predType = typeof(Func<,>).MakeGenericType(typeof(string), typeof(bool));
// Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
System.Reflection.MethodInfo anyMethod = typeof(Enumerable).GetMethod("Any", new Type[] {typeof(IEnumerable<string>), predType});
Expression anyCall = Expression.Call(
anyMethod,
Expression.Constant(strings),
Expression.Constant(predicate));
// test
Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();
谢谢!