如何获取循环外的变量?

发布于 12-03 09:10 字数 227 浏览 0 评论 0原文

我有这个:

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

如何在 while 循环之外获取字符串 countName?

I have this:

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

How to get string countName outside while loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

数理化全能战士2024-12-10 09:10:02

如果你想访问 while 循环之外的变量,你应该像这样在外面声明它

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

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

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();                
 }
岁月蹉跎了容颜2024-12-10 09:10:02

您可以在外部作用域中声明它:

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

请注意,因为您在每次迭代中都覆盖了它的值,所以在循环之外您将从最后一次迭代中获取它的值,或者如果循环未执行则为空字符串。

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.

失而复得2024-12-10 09:10:02
string countName;
countReader = command7.ExecuteReader();
while (countReader.Read())
{
   countName = countReader["count(*)"].ToString();                
}

该范围意味着退出循环后仍然可以访问它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文