【问题标题】:How to pass runtime argument variable in Expression.Call? [duplicate]如何在 Expression.Call 中传递运行时参数变量? [复制]
【发布时间】:2013-04-26 15:42:04
【问题描述】:

我在这里遗漏了一些琐碎的事情。假设我有这样的方法:

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

Expression.Call 行我得到:

“System.ArgumentException”类型的未处理异常发生在 System.Core.dll

附加信息:提供的参数数量不正确 调用方法 'Void M(System.Type, Int32[])'

我哪里做错了?

【问题讨论】:

    标签: c# expression-trees argumentexception


    【解决方案1】:

    params 关键字在运行时不执行任何操作。当您调用C.M(t, 1, 2, 3) 时,编译器会将其转换为C.M(t, new int[] { 1, 2, 3 })。在这种情况下,您正在执行编译器的部分工作,这是您的职责之一。您应该显式创建数组,并使用两个参数调用C.M

    【讨论】:

    • 感谢您的回答给了我正确的方向
    【解决方案2】:

    我是这样解决的(这里显示Calling (params object[]) with Expression[]):

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

    Expression.NewArrayInit 可以解决问题。感谢 hvd 的指导。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多