While debugging, Visual Studio will keep track of every variable in the current context.
Consider the following piece of code:
void SomeMethod1()
{
int j = 0;
}
void SomeMethod2()
{
int i = 0;
}//Breakpoint on this line.
When the program breaks, the current context is SomeMethod2
. At this point the developer is unable to check what the value of j
would be. This is because int j
is not a variable in the current context.
The actual reason behind OP's described behavior:
Visual Studio checks if the name of the variable exists in the current context and doesn't check if the variable itself exists in the current context.
So if we change the name of variable j
to i
in SomeMethod1
, we can suddenly view its "value". Imagine how weird it would get if i
in SomeMethod2
was a string:
When should you know this?
Whenever you have a piece of code where it's not immediately clear what the current context is. I encountered this problem in the following piece of code:
private double CalculateFast(double d)
{
//Depending on the size of d, either [Method 1] or [Method 2] is faster.
//Run them both and use the answer of the first method to finish.
Tasks.Task.Factory.StartNew(() = >
{
//Method 1
}
//Method 2
return answer;
}
I was debugging Method 2
but I thought I could view the variables of Method 1
as well. But this wasn't the case because Method 1
has its own context.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…