Help with incrementing intergers when looping in C#
I have declared an int e.g. int i;
I have a method that is looped:
public static void NumberUp(int i)
{
i++;
System.Console.WriteLine(i);
...
}
开发者_开发百科
although each time the number is returned, it is always 1. Not 1,2,3 and so on..
I would have imagined that "i" increases by one which each run of the method?
You can pass the variable by reference.
public static void NumberUp(ref int i)
{
i++;
System.Console.WriteLine(i);
...
}
This, however is bad design, as you now have a method with a side effect on the passed in parameter (which the method name doesn't indicate) - something that can catch other programmers by surprise.
It would be a better design to return the incremented value:
public static int NumberUp(ref int i)
{
return i + 1;
}
It's doing that because you're passing it by value. That means the variable within the function is a copy of the original.
If you want changes to reflect back to the original variable, you need to pass it by reference, meaning the variable refers to the original rather than a copy. You can use something like:
public static void NumberUp (ref int i) {
i++;
System.Console.WriteLine(i);
}
It would be better to define NumberUp
like this
public static int NumberUp(int number)
{
System.Console.WriteLine(++number);
return number;
}
Then assign the return value in your loop.
int
is a value type and not a reference type. As such, i
inside NumberUp
is a copy of the parameter you passed in.
If you want the value to be changed outside the method, pass the parameter as reference:
public static void NumberUp(ref int i)
This is reference vs value type. To accomplish what you actually need, you have to pass i
by reference.
The Method is static but this does not automatically mean the parameter is. Maybe use a static int in you class as member.
class x
{ static int i;
Or pass it byRef
精彩评论