I don't understand the usefulness of parameter arrays?
Parameter arrays allow a variable number of arguments to be passed into a method:
static void Method(params int[] array)
{}
But I fail to see their usefulness, since same result could be achieved by specifying a parameter of particular array type:开发者_运维百科
static void Method(int[] array)
{}
So what benefits ( if any ) does parameter array have over value parameter of array type?
thank you
It's just a code readability thing. For example, string.Format:
string value = string.Format("SomeFormatString", param1, param2, param3, param4.... param999);
It could be written like this in a different lifetime:
string value = string.Format("SomeFormatString", new string[] { param1, param2, param3 });
In the end, it's just syntactic sugar to make the code easier to read and easier to understand.
In the second example, the consumer can't call it using
MyType.Method(1, 2, 3)
The benefit is that the compiler creates the array automatically for you:
string coor = String.Concat("x=", x, ", y=", y);
The code that is generated for you is actually:
string coor = String.Concat(new string [] { "x=", x, ", y=", y });
You even get the best of both worlds. If you happen to have your data in an array, you can pass it to a method that has a params
parameter.
I for one much prefer to write
Method(1, 2, 3, 4, 5);
instead of
Method(new int[] { 1, 2, 3, 4, 5} );
It's how they're called.
In the first example, with params, you can call Method(1,2,3,4,5);
In the second example, without params, you have to call it Method(new [] {1,2,3,4,5});
精彩评论