c# Pass params from one routine to another
The easiest way to ask this question would be to show you all through an example - so here I go!
private void exampleVoid(string someString, params string[] someArray_string)
{
// Do some dirty work
for(int i = 0; i < someArray_string.length; i++)
{
Console.WriteLine(someArray_string[i]);
}
// Recall the routine
exampleVoid("some string", someArray_string)
}
When I re-pass the array at the bottom 开发者_StackOverflowof the routine, the data is not properly going through. The length of the array is now 0.
Why is that?
I'm not seeing that behavior at all using the following example:
class Program
{
static void Main( string[] args )
{
Foo( 5, "one", "two", "three" );
Console.ReadLine();
}
static void Foo( int counter, params string[] parms )
{
if( counter <= 0 ) return;
foreach( var str in parms )
{
Console.WriteLine( str );
}
Foo( --counter, parms );
}
}
How are you determining that someArray_string
is empty after the first recursive call? Are you using the debugger? Where are you calling this function and what arguments are you passing into it? Are you actually passing strings as the second...last arguments, i.e., are you passing more than one argument to the method?
Also, you will eventually just crash with a StackOverflowException
because you never return from the function aside from calling it recursively. The calls never stop, could that possibly be the cause of what you assume to be another problem entirely?
How/When are you initializing someArray_string? When do you add anything to that array? From what I can tell, you're simply looping through an empty array and writing its empty element(s) to the console.
You're sure you haven't removed or modified any data from the array inside the method ? Since arrays will be passed by reference.
I've tried the example, and it just works as expected... So, I wonder what the 'heavy processing' is exactly ...
I had faced a similar problem and had to abandon this approach.
The params keyword lets the method take a variable argument list. When you call the method again the "someArray_string" sent into the next call , is received as just one parameter and not an array. On the second call don't you have any value for someArray_string[0] ?
精彩评论