params 参数修饰符为调用者提供了将多个参数传递给方法的快捷语法。有两种方法可以调用带有params 参数的方法:
1) 使用参数类型的数组调用,此时params关键字无效,数组直接传递给方法:
object[] array = new[] { "1", "2" };
// Foo receives the 'array' argument directly.
Foo( array );
2) 或者,使用扩展的参数列表调用,在这种情况下,编译器会自动将参数列表包装在一个临时数组中并将其传递给方法:
// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );
// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );
要将对象数组传递给带有“params object[]”参数的方法,您可以:
1) 手动创建一个包装器数组并将其直接传递给方法,如lassevk 所述:
Foo( new object[] { array } ); // Equivalent to calling convention 1.
2) 或者,将参数转换为object,如Adam 所述,在这种情况下,编译器将为您创建包装器数组:
Foo( (object)array ); // Equivalent to calling convention 2.
但是,如果该方法的目标是处理多个对象数组,则使用显式“params object[][]”参数声明它可能更容易。这将允许您将多个数组作为参数传递:
void Foo( params object[][] arrays ) {
foreach( object[] array in arrays ) {
// process array
}
}
...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );
// Equivalent to:
object[][] arrays = new[] {
new[] { "1", "2" },
new[] { "3", "4" }
};
Foo( arrays );
编辑:Raymond Chen 在a new post 中描述了这种行为以及它与 C# 规范的关系。