是否有办法将List
作为参数传递给params
参数?假设我有这样的方法:
void Foo(params int[] numbers)
{
// ...
}
这样我就可以通过传递一个由逗号分隔的int
或int
数组来调用它:
int[] numbers = new int[] { 1, 5, 3 };
Foo(numbers);
Foo(1, 5, 3);
我想知道是否还有一种方法可以将List
作为参数传递(无需将其转换为数组)。例如:
List<int> numbersList = new List<int>(numbers);
// This won't compile:
Foo(numbersList);
答案 0 :(得分:5)
可悲的是,这就是答案。不,那里没有。并非没有将其转换为数组(例如使用.ToArray()
)。
答案 1 :(得分:3)
您可能希望更改<form action='http://myhost.elasticbeanstalk.com/API/Beta/Register' method = 'post' enctype='application/json'>
Email: *<br>
<input type='text' name='Email' style='width: 500px;' value='{"Email":"test@gmail.com"}'><br>
<br>
(Fields denoted with * are mandatory)
<br>
<input type='submit' value='Apply' style='float: right;'>
</form>
以接受Foo
以外的其他内容来执行此操作。
params int[]
这样您就可以传入void Foo(IEnumerable<int> numbers) {
}
或int[]
要允许这两种方式,您可以这样做:
List<int>
答案 2 :(得分:0)
如果能够更改现有代码,您可以始终创建一个接受List的重载并将其传递给params方法。
void Foo(params int[] numbers)
{
// ...
}
void Foo(IList<int> numbers) => Foo(numbers.ToArray());