【问题标题】:carry Data from a TRY While Loop?从 TRY While 循环中携带数据?
【发布时间】:2011-07-14 02:40:02
【问题描述】:

考虑一下这个 while 循环,一旦它完成,它就会一直将我的值归零。

counterm 字符串现在在程序结束时为空。我们如何从 while 循环中携带值?

void somefunction() {   
    try {                  
      using (StreamReader sr = new StreamReader("Counter.txt"))
      {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
            string countern = line + "_1";
            string counterm = line + "_2";
            int counter = Convert.ToInt32(line);
            sr.test(counterm);
        }
      }
    }
    catch (Exception e)
    {
        // Let the user know what went wrong.
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
    Thread.Sleep(60000);            
    }
}
public static void test(counterm)
{
        Console.WriteLine(counterm);
        Console.ReadLine();
}

【问题讨论】:

  • 是的,如果 counterm 是在 while 循环之外定义的,那么你不应该在它的前面有“string”。 (我认为其他人在下面提到了这一点,只是把它放在首位......)
  • 我不明白sr.test(); 是什么。你的类是 sr 以及 StreamReader 实例吗?
  • 嗨,您可以忽略 sr.test 我正在尝试其他方法 iv 删除了起始字符串替换了所有提及但仍然无法正常工作的所有代码。

标签: c# while-loop


【解决方案1】:

因为您的 counterm 仅在 while 循环的范围内。

在更高的范围内声明您的变量,以便从 while 循环外部访问它们。

【讨论】:

  • 他实际上是在尝试以单独的方法一起访问它们。
  • 在更高级别的独家新闻中定义并且可以编译,但是当您逐行运行它时,它只会将值恢复为 null,因此不会在测试方法中显示
【解决方案2】:

变量的范围仅在 while 循环内。循环外没有定义。除非您还在全局范围内声明了变量,否则这甚至不应该编译。


来自评论: 那么你的while循环应该是这样的:

while ((line = sr.ReadLine()) != null)
{
    Console.WriteLine(line);
    countern = line + "_1";
    counterm = line + "_2";
    int counter = Convert.ToInt32(line);

    sr.test();    // why `sr`? there is no test-method defined for streamreader.
                  // is your class called `sr` as well?
}

变量仅在它们定义的范围内“存在”。重新定义变量时,您实际上是在创建新变量,而不是写入全局变量。

【讨论】:

  • yer there decliaed 更高的命名空间 ConsoleApplication1 { class Program { string countern="", counterm=""; public static void Main(string[] args) { try {
  • @Ben:更新了答案。请注意,您不应调用 sr.test(),而应调用 test()。
  • @Ben Wilson 我认为你遗漏了一些东西;在您的循环中,您有 string countern = line + "_1";string counterm = line + "_2"; 但假设 countern 和 counterm 在其他地方定义,您需要删除 string;就像上面 Avada Kedavra 示例中的代码一样。
【解决方案3】:

counterm 是循环的局部变量。您的代码也无法编译,因为它不完整,但我的建议是这样的:

string ParseCounters()
{
    string counterm = "";

    ...
    String line;
    while ((line = sr.ReadLine()) != null)
    {
        ...
        counterm = line + "_2"
    }
    ...

    return counterm;

}

public static void test()
{
    Console.WriteLine(ParseCounter());
    Console.ReadLine();
}

【讨论】:

    【解决方案4】:

    因为您是在 while 块内声明变量,所以一旦您退出该块,该变量就会被删除。你必须在更远的地方声明它。

    这是你的整个程序吗?您在那里列出的内容看起来不会编译,因为在 test() 方法中根本没有声明 counterm。

    【讨论】:

    • 不,这只是我的一小部分,但我们一起努力让这件事先发挥作用
    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2015-04-24
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多