gpt4 book ai didi

c# - Expression.Call with Any 方法抛出异常

转载 作者:太空狗 更新时间:2023-10-29 22:30:58 25 4
gpt4 key购买 nike

我正在研究使用表达式的过滤器机制,但无法弄清楚如何使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com