你的处理方式有几个问题。
您正在混合抽象级别。 T 参数为GetAnyExpression<T>
可能与用于实例化的类型参数不同propertyExp.Type
。 T 类型参数在抽象堆栈中离编译时间更近了一步 - 除非您正在调用GetAnyExpression<T>
通过反射,它将在编译时确定 - 但嵌入在表达式中的类型传递为propertyExp
是在运行时确定的。您将谓词传递为Expression
也是一个抽象混合——这是下一点。
您要传递给的谓词GetAnyExpression
应该是委托值,而不是Expression
任何类型,因为你想打电话Enumerable.Any<T>
。如果您尝试调用表达式树版本Any
,那么你应该通过LambdaExpression
相反,您将引用它,并且这是您可能有理由传递比表达式更具体的类型的罕见情况之一,这引出了我的下一点。
一般来说,你应该绕过Expression
价值观。一般而言,在使用表达式树时(这适用于所有类型的编译器,而不仅仅是 LINQ 及其朋友),您应该以一种与您正在使用的节点树的直接组成无关的方式进行操作。你是假设你正在呼唤的Any
on a MemberExpression
,但你实际上并没有需要知道你正在处理一个MemberExpression
,只是一个Expression
类型的一些实例化IEnumerable<>
。对于不熟悉编译器 AST 基础知识的人来说,这是一个常见的错误。弗兰斯·布玛 http://weblogs.asp.net/fbouma/archive/2007/10/03/developing-linq-to-llblgen-pro-day-5.aspx当他第一次开始使用表达式树时,他多次犯同样的错误 - 在特殊情况下思考。一般来说。从中长期来看,您将为自己省去很多麻烦。
现在问题的核心来了(尽管如果您已经解决了第二个问题,也可能是第一个问题,那么您可能会遇到麻烦) - 您需要找到 Any 方法的适当泛型重载,然后使用正确的类型实例化它。反思并不能让你轻松自在。您需要迭代并找到合适的版本。
所以,分解它:你需要找到一个通用方法(Any
)。这是一个执行此操作的实用函数:
static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs,
Type[] argTypes, BindingFlags flags)
{
int typeArity = typeArgs.Length;
var methods = type.GetMethods()
.Where(m => m.Name == name)
.Where(m => m.GetGenericArguments().Length == typeArity)
.Select(m => m.MakeGenericMethod(typeArgs));
return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null);
}
但是,它需要类型参数和正确的参数类型。从你那里得到的propertyExp
Expression
并不完全是微不足道的,因为Expression
可能是一个List<T>
类型,或其他类型,但我们需要找到IEnumerable<T>
实例化并获取其类型参数。我将其封装成几个函数:
static bool IsIEnumerable(Type type)
{
return type.IsGenericType
&& type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}
static Type GetIEnumerableImpl(Type type)
{
// Get IEnumerable implementation. Either type is IEnumerable<T> for some T,
// or it implements IEnumerable<T> for some T. We need to find the interface.
if (IsIEnumerable(type))
return type;
Type[] t = type.FindInterfaces((m, o) => IsIEnumerable(m), null);
Debug.Assert(t.Length == 1);
return t[0];
}
所以,给定任意Type
,我们现在可以拉IEnumerable<T>
实例化它 - 并断言如果不存在(恰好)一个。
完成这项工作后,解决真正的问题并不是太困难。我已将您的方法重命名为 CallAny,并按照建议更改了参数类型:
static Expression CallAny(Expression collection, Delegate predicate)
{
Type cType = GetIEnumerableImpl(collection.Type);
collection = Expression.Convert(collection, cType);
Type elemType = cType.GetGenericArguments()[0];
Type predType = typeof(Func<,>).MakeGenericType(elemType, typeof(bool));
// Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
MethodInfo anyMethod = (MethodInfo)
GetGenericMethod(typeof(Enumerable), "Any", new[] { elemType },
new[] { cType, predType }, BindingFlags.Static);
return Expression.Call(
anyMethod,
collection,
Expression.Constant(predicate));
}
这是一个Main()
例程使用上述所有代码并验证它是否适用于简单的情况:
static void Main()
{
// sample
List<string> strings = new List<string> { "foo", "bar", "baz" };
// Trivial predicate: x => x.StartsWith("b")
ParameterExpression p = Expression.Parameter(typeof(string), "item");
Delegate predicate = Expression.Lambda(
Expression.Call(
p,
typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
Expression.Constant("b")),
p).Compile();
Expression anyCall = CallAny(
Expression.Constant(strings),
predicate);
// now test it.
Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();
Console.WriteLine("Found? {0}", a());
Console.ReadLine();
}