C# 如何在Expression.Call中传递运行时参数变量?
我遗漏了一些琐碎的东西。假设我有这样一种方法:C# 如何在Expression.Call中传递运行时参数变量?,c#,expression-trees,argumentexception,C#,Expression Trees,Argumentexception,我遗漏了一些琐碎的东西。假设我有这样一种方法: abstract class C { public static void M(Type t, params int[] i) { } } 我正在学习表达式树,我需要构建一个委托,用一些预定义的参数调用这个方法。问题是我不知道如何选择正确的重载并传递Expression.Call的参数 我想做到这一点: //I have other overloads for M, hence I need to specify the
abstract class C
{
public static void M(Type t, params int[] i)
{
}
}
我正在学习表达式树,我需要构建一个委托,用一些预定义的参数调用这个方法。问题是我不知道如何选择正确的重载并传递Expression.Call的参数
我想做到这一点:
//I have other overloads for M, hence I need to specify the type of arugments
var methodInfo = typeof(C).GetMethod("M", new Type[] { typeof(Type), typeof(int[]) });
//this is the first argument to method M, not sure if I have chosen the right expression
var typeArgumentExp = Expression.Parameter(someType);
var intArrayArgumentExp = Enumerable.Repeat(Expression.Constant(0), 3);
var combinedArgumentsExp = new Expression[] { typeArgumentExp }.Concat(intArrayArgumentExp);
var call = Expression.Call(methodInfo, combinedArgumentsExp);
在表达式.Call
行,我得到:
中发生类型为“System.ArgumentException”的未处理异常
System.Core.dll
其他信息:为提供的参数数量不正确
调用方法“Void M(System.Type,Int32[])”
我哪里出错了 在运行时,params
关键字不起任何作用。调用C.M(t,1,2,3)
时,编译器将其转换为C.M(t,newint[]{1,2,3})
。在本例中,您正在执行编译器工作的一部分,这是您的责任。您应该显式地创建数组,并使用两个参数调用C.M
。在运行时params
关键字不起任何作用。调用C.M(t,1,2,3)
时,编译器将其转换为C.M(t,newint[]{1,2,3})
。在本例中,您正在执行编译器工作的一部分,这是您的责任。您应该显式地创建数组,并使用两个参数调用C.M
。我这样解决了它(如下所示):
这就是诀窍。感谢hvd的指导。我这样解决了问题(如图所示):
这就是诀窍。谢谢hvd的指导。谢谢你的回答给了我正确的方向谢谢你的回答给了我正确的方向
//I have other overloads for M, hence I need to specify the type of arugments
var methodInfo = typeof(C).GetMethod("M", new Type[] { typeof(Type), typeof(int[]) });
//I fixed this issue where the first argument should be typeof(Type)
var typeArgumentExp = Expression.Parameter(typeof(Type));
var intArrayArgumentExp = Expression.NewArrayInit(typeof(int), Enumerable.Repeat(Expression.Constant(0), 3));
var combinedArgumentsExp = new Expression[] { typeArgumentExp }.Concat(intArrayArgumentExp);
var call = Expression.Call(methodInfo, combinedArgumentsExp);