DynamicInvoke参数数量与预期计数不匹配

时间:2017-02-19 21:34:21

标签: c# dynamic reflection

我试图将Func<..>内的lambda包装成动态并动态调用它,但它会引发有关参数计数的异常。

MCVE

using System;

public class Test
{
    public static void Main()
    {

        // your code goes here
        try {
            dynamic plus = new Func<long, long, long>((a, b) => a + b);
            Type functionType = plus.GetType();
            int arity = functionType.GetGenericArguments().Length - 1;
            Console.WriteLine("Arity {0}", arity);
            long[] parameters = new long[arity];

            long result = plus.DynamicInvoke(parameters);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
} 

例外:Number of parameter does not match expected count.

1 个答案:

答案 0 :(得分:2)

DynamicInvokeobject数组作为参数,而不是long数组。

这应该有效:

var result = plus.DynamicInvoke(parameters.Cast<object>().ToArray());