簡體   English   中英

Expression.Call with Any方法拋出異常

[英]Expression.Call with Any method throws exception

我正在使用表達式處理過濾機制,無法弄清楚如何調用任何使用Expression.Call的方法。 下面的例子沒有意義,但說明了我的問題:

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>

你可以通過調用提供typeof(String)參數的anyMethod.MakeGenericMethod 所以你的代碼變成了

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
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM