How will be object[] params interpreted if they are passed into another procedure with object[] params?
If we have two procedures:
public void MyFirstParamsFunction(params object[] items)
{
//do something
MySecondParamsFunction(items, "test string", 31415)
}
public void MySecondParam开发者_高级运维sFunction(params object[] items)
{
//do something
}
How will second procedure interpret the items
from first? As sole objects, or as one object, that is object[]
?
object[] items
will be interpreted as one object[]
parameter.
This call:
MySecondParamsFunction(items, "test string", 31415);
Will expand to this:
MySecondParamsFunction(new object[] { items, "test string", 31415 });
So you'll have 3 items in your params
array for the call. Your original items
array will be crammed into the first item in the new array.
If you want to just have a flattened parameter list going into the second method, you can append the new items to the old array using something like this:
MySecondParamsFunction(
items.Concat(new object[] { "test string", 31415 }).ToArray());
Or maybe with a nicer extension method:
MySecondParamsFunction(items.Append("test string", 31415));
// ...
public static class ArrayExtensions {
public static T[] Append<T>(this T[] self, params T[] items) {
return self.Concat(items).ToArray();
}
}
If you check it yourself you would have noticed that it is seen as a single object.
So in MySecondParamsFunction
the items
parameter will have length of 3 in this case.
The params keyword is just a bit of syntactic sugar.
Calling MyFirstParamsFunction(1, 2, 3) is the same as MyFirstParamsFunction(new object[] { 1, 2, 3 }). The compiler injects the code to create the array behind your back.
精彩评论