具有可变数量参数的匿名方法

Him*_*ere 3 c# lambda anonymous-function params

我有以下代码创建一个匿名类型的实例,该方法作为唯一成员:

var test = new { 
    f = new Func<int, int>(x => x)
};
Run Code Online (Sandbox Code Playgroud)

我想实现一个函数,它总结了所有参数,无论传递了多少参数.这是常规方法的样子:

int Sum(params int[] values) { 
    int res = 0;
    foreach(var i in values) res += i;
    return res;
}
Run Code Online (Sandbox Code Playgroud)

但是,我不知道这是否适用于匿名方法.我试过了Func<params int[], int>,但显然不会编译.有没有办法用变量参数列表编写匿名方法,或者至少使用可选的args?

编辑:我想要实现的是调用这样的(匿名)求和方法:test.Sum(1, 2, 3, 4).

Dmy*_*nko 5

为了实现这一点,首先需要声明一个委托:

delegate int ParamsDelegate(params int[] args);
Run Code Online (Sandbox Code Playgroud)

然后在分配匿名类型对象的method属性时使用它.

var test = new {
    Sum = new ParamsDelegate(x => x.Sum()) // x is an array
};
Run Code Online (Sandbox Code Playgroud)

然后你有两种方法来调用这个方法:

1) int sum = test.Sum(new [] { 1, 2, 3, 4 });

2) int sum = test.Sum(1, 2, 3, 4);

  • 嗯,"我想要实现的是调用(匿名)求和方法,如test.Sum(1,2,3,4)" (3认同)
  • `int sum = test.Sum(1,2,3)`也可以 (2认同)