问题
I'm New to C# and I'm trying to reach the value of MAX from the while so i can use it outside but i can't...anyone have some ideas !!! Thanks In Advance
while (Condition)
{
Double MAX = somecode.....
.....
}
Console.WriteLine("The OPTIMAL Value : " + MAX);
回答1:
Declare MAX before you start the while loop. The way you have it you can only access within the while.
Double MAX = 0;
while (Condition)
{
MAX = somecode.....
.....
}
Console.WriteLine("The OPTIMAL Value : " + MAX);
回答2:
You must declare the variable BEFORE the loop.
Double MAX;
while (Condition)
{
MAX = somecode....
}
Console.WriteLine("The OPTIMAL Value : " + MAX);
回答3:
It would seem the underlying problem is understanding how scope works. A google search for "C# how scope works" (or similar) might prove helpful.
I found one that's quite simple and easy to understand: http://www.codecandle.com/Articles/191/Csharp/Variables/Variable-scope/codedetail.aspx
So as many others have mentioned you'll need to declare your variable outside your inner scope in order to have access to the changes.
Some pseudo code
// declare variable;
{
// change variable;
}
// use changed variable
回答4:
Declare MAX as a variable outside of the loop for example change the variable name also don't use reserved words as variable names
var dMax = default(double);//this is equivalent to writing Double dMax = 0 when debugginb it will give you this value 0.0
while (Condition)
{
dMax = somecode.....
}
Console.WriteLine("The OPTIMAL Value : " + dMax);
来源:https://stackoverflow.com/questions/15593540/access-variable-inside-while-loop-from-outside-c