1
我想包分配到动态Func<..>
内的λ和动态调用它,但它会引发有关参数计数异常。DynamicInvoke参数的数量不匹配,期望数
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.
而不是铸造和分配一个全新的阵列,它可能会更好声明'parameters'为对象[]开始与 –
@KevinGosse,我同意。虽然在这种特殊情况下,动态调用委托的成本远高于数组的分配。重点是输入需要是一个'object []'。 –