[英]Anonymous method with a variable number of parameters
I have the following code that creates an instance of an anonymous type having a method as the only member: 我有以下代码创建一个匿名类型的实例,该方法作为唯一成员:
var test = new {
f = new Func<int, int>(x => x)
};
I want to implement a function that sums up all of its parameters, regardless of how many are passed. 我想实现一个函数,它总结了所有参数,无论传递了多少参数。 This is how a normal method would look like:
这是常规方法的样子:
int Sum(params int[] values) {
int res = 0;
foreach(var i in values) res += i;
return res;
}
However, I don´t know if this would work for anonymous methods. 但是,我不知道这是否适用于匿名方法。 I tried out
Func<params int[], int>
, but obviously that won´t compile. 我尝试了
Func<params int[], int>
,但显然不会编译。 Is there any way to write an anonymous method with a variable list of parameters, or at least with optional args? 有没有办法用变量参数列表编写匿名方法,或者至少使用可选的args?
EDIT: What I´d like to achieve is to call the (anonymous) sum-method like this: test.Sum(1, 2, 3, 4)
. 编辑:我想要实现的是调用这样的(匿名)求和方法:
test.Sum(1, 2, 3, 4)
。
In order to achieve this, first you need to declare a delegate: 为了实现这一点,首先需要声明一个委托:
delegate int ParamsDelegate(params int[] args);
And then use it when assigning the method property of your anonymously typed object. 然后在分配匿名类型对象的method属性时使用它。
var test = new {
Sum = new ParamsDelegate(x => x.Sum()) // x is an array
};
Then you have two ways of calling this method: 然后你有两种方法来调用这个方法:
1) int sum = test.Sum(new [] { 1, 2, 3, 4 });
1)
int sum = test.Sum(new [] { 1, 2, 3, 4 });
2) int sum = test.Sum(1, 2, 3, 4);
2)
int sum = test.Sum(1, 2, 3, 4);
One option that comes to my mind is to simply use an array (or any other sort of IEnumerable
) as type-parameter for the function: 我想到的一个选择是简单地使用数组(或任何其他类型的
IEnumerable
)作为函数的类型参数:
f = new Func<IEnumerable<int>, int> ( x => foreach(var i in x) ... )
Simlar to the appraoch of Dmytro (which I prefer more) we´d call it by creating an array: 模拟Dmytro(我更喜欢)的appraoch我们会通过创建一个数组来调用它:
var s = test.f(new[] { 1, 2, 3, 4 });
Essentially your anonymous type does not contain a method, but instead a property of type Func<,>
. 基本上,您的匿名类型不包含方法,而是包含
Func<,>
类型的属性。 C# does not support variadic generics ie you can't have generic with variable number of parameters. C#不支持可变参数泛型,即不能使用可变数量的参数的泛型。 See .
见 。
What you can do instead: 你可以做什么:
Func<,>
. Func<,>
通用参数。 For example: Func<IEnumerable<int>, int>(...)
. Func<IEnumerable<int>, int>(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.