开发者

How to get variable outside loop?

I have this:

 countReader = command7.Exec开发者_高级运维uteReader();
 while (countReader.Read())
 {
    string countName = countReader["count(*)"].ToString();                
 }

How to get string countName outside while loop?


If you want to access a variable outside the while loop you should declare it outside like this

countReader = command7.ExecuteReader();
string countName = String.Empty;

 while (countReader.Read())
 {
  countName = countReader["count(*)"].ToString();                
 }


You could declare it in the outer scope:

countReader = command7.ExecuteReader();
string countName = "";
while (countReader.Read())
{
    countName = countReader["count(*)"].ToString();                
}
// you can use countName here

Note that because you are overwriting its value on each iteration, outside the loop you will get its value from the last iteration or an empty string if the loop didn't execute.


string countName;
countReader = command7.ExecuteReader();
while (countReader.Read())
{
   countName = countReader["count(*)"].ToString();                
}

The scope will mean it is still accessible after the loop is exited.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜