需要数组的可变参数函数的设计决策是什么?
我很好奇,希望有人能对此有所了解 - 但为什么采用“params”的 C# 函数必须是一个数组?
我知道参数列表中的对象被输入到一个数组中,但是如果有人想创建一个接受未定义数量的数组对象的可变参数函数怎么办?
以这个函数为例...
private Int32 Sum(params Int32[] numbers)
{
return numbers.Sum(); // Using LINQ here to sum
}
非常简单,它可以接受不同数量的数字 - 例如...
Int32 x = Sum(1);
Int32 y = Sum(1, 2);
Int32 z = Sum(1, 2, 3);
现在假设我想创建一个函数,它接受不同数量的整数数组并对所有数字。 据我所知,我必须考虑拳击......
private Int32 SumArrays(params Object[] numbers)
{
Int32 total = 0;
foreach (Object o in numbers)
{
Int32[] array = (Int32[])o;
total += array.Sum();
}
return total;
}
然后可以像......
Int32[] arr1 = new Int32[] { 1, 2, 3 };
Int32[] arr2 = new Int32[] { 1, 2, 3, 4 };
Int32[] arr3 = new Int32[] { 1, 2, 3, 4, 5 };
Int32 x = SumArrays((Object)arr1, (Object)arr2);
Int32 y = SumArrays((Object)arr1, (Object)arr2, (Object)arr3);
这背后的原因是什么? 为什么不将其实现为单个非数组变量? 比如params Int32
?
I am curious and hopefully someone can shed somelight on this - but why do the C# functions that take 'params' have to be an array?
I get that the objects in the parameters list are entered into an array but what if someone wants to create a variadic function that takes in an undefined number of array objects?
Take this function for example...
private Int32 Sum(params Int32[] numbers)
{
return numbers.Sum(); // Using LINQ here to sum
}
Pretty straight forward, it can take in a different amount of numbers - for example...
Int32 x = Sum(1);
Int32 y = Sum(1, 2);
Int32 z = Sum(1, 2, 3);
Now lets say I want to create a function that takes in a different amount of Integer arrays and sums up all the numbers. As far as I am aware I would have to consider boxing...
private Int32 SumArrays(params Object[] numbers)
{
Int32 total = 0;
foreach (Object o in numbers)
{
Int32[] array = (Int32[])o;
total += array.Sum();
}
return total;
}
Which could then be used like...
Int32[] arr1 = new Int32[] { 1, 2, 3 };
Int32[] arr2 = new Int32[] { 1, 2, 3, 4 };
Int32[] arr3 = new Int32[] { 1, 2, 3, 4, 5 };
Int32 x = SumArrays((Object)arr1, (Object)arr2);
Int32 y = SumArrays((Object)arr1, (Object)arr2, (Object)arr3);
What was the reasoning behind this? Why wasn't this ever implemented as just a single non array variable? Such as params Int32
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该功能已经存在,无需诉诸装箱:
您只需将其添加为数组的数组即可。
The functionality is already there, no need to resort to boxing:
You just need to add it an array of arrays.
参数被卷入单个对象中,并且可以容纳集合的最低级别对象是数组。 如果您想要一个接受可变数量的 int 数组的函数,那么应该将其声明为接受 int 数组的数组。
The params get rolled into a single object, and the lowest-level object that can hold a collection is an array. If you want a function that takes a variable number of arrays of ints, then it should be declared as taking an array of int arrays.