Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获得外部循环的变量?_C#_C# 4.0 - Fatal编程技术网

C# 如何获得外部循环的变量?

C# 如何获得外部循环的变量?,c#,c#-4.0,C#,C# 4.0,我有这个: countReader = command7.ExecuteReader(); while (countReader.Read()) { string countName = countReader["count(*)"].ToString(); } 如何在while循环外部获取字符串countName?如果要访问while循环外部的变量,应该像这样在外部声明它 countReader = command7.ExecuteReader

我有这个:

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

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

如果要访问while循环外部的变量,应该像这样在外部声明它

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

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

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

您可以在外部范围中声明它:

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

请注意,因为您在每次迭代中都会覆盖它的值,所以在循环之外,您将从上一次迭代中获得它的值,或者如果循环没有执行,则会得到一个空字符串。

如果我可以建议做些什么的话。将“”更改为String.Empty.+1,以说明如果读取器中有多行,则每个循环上的countName将被覆盖。什么是
“count(*)”
?在我看来,这不是一个有效的列名。你想得到那一列的总和吗?如果没有,你想完成什么?
countReader = command7.ExecuteReader();
string countName = "";
while (countReader.Read())
{
    countName = countReader["count(*)"].ToString();                
}
// you can use countName here