'ref' not working like I think it should
I have the following code which when looking at it while it's running shows that the initial 'myInt' and 'myFloat' do not change their values until the method call returns back. Shouldn't their values change each time they are altered within the called methods since they are passed as 'ref' each time?
class Tester
{
public void Run()
{
int myInt = 42;
float myFloat = 9.685f;
Console.WriteLine("Before starting: \n value of myInt: {0} \n value of myFloat: {1}", myInt, 开发者_如何学PythonmyFloat);
// pass the variables by reference
Multiply( ref myInt, ref myFloat );
Console.WriteLine("After finishing: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
}
private static void Multiply (ref int theInt, ref float theFloat)
{
theInt = theInt * 2;
theFloat = theFloat *2;
Divide( ref theInt, ref theFloat);
}
private static void Divide (ref int theInt, ref float theFloat)
{
theInt = theInt / 3;
theFloat = theFloat / 3;
Add(ref theInt, ref theFloat);
}
public static void Add(ref int theInt, ref float theFloat)
{
theInt = theInt + theInt;
theFloat = theFloat + theFloat;
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
EDIT: Okay, having seen the description in your comments...
If you put a breakpoint in (say) Add
then your watch variables won't change unless you get them to be re-evaluated - which has to be done in the right stack from. When the breakpoint has been hit, go to the Call Stack view, double click on the "Run" method (which doesn't change where you've got to, just which stack frame you're looking at) and you'll see the values update.
It's a debugger anomaly, the values change right away, as per Jon's and jamietre's comments.
You placed a Watch on the expressions myInt
and myFloat
rather than the expressions theInt
and theFloat
, thus you no longer see their values. myInt
and myFloat
do not exist in the current scope.
You can back up in the call stack to observe their values, or place a watch on all four of the expressions you care about.
精彩评论