作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在研究使用表达式的过滤器机制,但无法弄清楚如何使用 Expression.Call 调用 Any 方法。下面是一个没有意义但说明了我的问题的例子:
var person = new List<String>(new[] { "Peter", "John", "Jim" });
var personQuery = person.AsQueryable();
var anyMethod = typeof(Queryable).GetMethods().FirstOrDefault(method => method.Name == "Any" && method.GetParameters().Count() == 2);
Expression<Func<String, bool>> expr = p => p == "Amy";
// person.Any(person => person == "Amy"
var call = Expression.Call(
anyMethod,
personQuery.Expression,
expr
);
Expression.Call 抛出 ArgumentException:
System.ArgumentException was unhandled
HResult=-2147024809
Message=Method Boolean Any[TSource](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Boolean]]) is a generic method definition.
Source=System.Core
StackTrace:
w System.Linq.Expressions.Expression.ValidateMethodInfo(MethodInfo method)
w System.Linq.Expressions.Expression.ValidateMethodAndGetParameters(Expression instance, MethodInfo method)
w System.Linq.Expressions.Expression.Call(MethodInfo method, Expression arg0, Expression arg1)
w TestConsoleApplication.Program.Main(String[] args) w d:\Users\user\Documents\Visual Studio 2012\Projects\TestConsoleApplication\TestConsoleApplication\Program.cs:wiersz 26
w System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
w System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
w Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
w System.Threading.ThreadHelper.ThreadStart_Context(Object state)
w System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
w System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
w System.Threading.ThreadHelper.ThreadStart()
InnerException:
最佳答案
你的 anyMethod
变量将包含通用方法定义。即 Any<TSource>
您需要将其转换为 Any<String>
在调用它之前。
您可以通过调用 anyMethod.MakeGenericMethod
来完成提供typeof(String)
争论。所以你的代码变成了
var person = new List<String>(new[] { "Peter", "John", "Jim" });
var personQuery = person.AsQueryable();
var anyMethod = typeof(Queryable).GetMethods().FirstOrDefault(method => method.Name == "Any" && method.GetParameters().Count() == 2);
var specificMethod = anyMethod.MakeGenericMethod(typeof(String));//<--Important
Expression<Func<String, bool>> expr = p => p == "Amy";
// person.Any(person => person == "Amy"
var call = Expression.Call(
specificMethod,
personQuery.Expression,
expr
);
关于c# - Expression.Call with Any 方法抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25845477/
我是一名优秀的程序员,十分优秀!