代码之家  ›  专栏  ›  技术社区  ›  julian bechtold

字符串在c中的Label之后未赋值#

  •  1
  • julian bechtold  · 技术社区  · 6 年前

    我有一个我完全不明白的问题:

    path 已使用。路径在标签前面工作,但在标签后面是未分配的。令我困惑的是,所有其他变量都有效!

    path = @"C:\incidents\jobTransfer";
    File.WriteAllLines(path + incident + "\\result_" + incident + ".txt", resultText.ToArray());
    End:;
    File.WriteAllLines(incident, resultText.ToArray());
    File.WriteAllLines(path + incident + "\\result_" + incident + ".txt", resultText.ToArray()); // issue at path in this line
    

    enter image description here

    我可以在标签后面重新分配变量,但是我总是要编辑两行代码以防更改

    3 回复  |  直到 6 年前
        1
  •  1
  •   Stefan    6 年前

    在你拥有的地方:

    string path;
    

    string path = null;
    

    它解决了你的问题。


    虽然是分配的 null ,路径在标签处未取消分配。

    string path = @"C:\incidents\jobTransfer";
    

    这样,它就被赋值,并且从一开始就有一个有效值。

    看到了吗 this fiddle :


    例子

        string path;
        goto End;
    AnotherLabel:
        path = @"C:\incidents\jobTransfer";
        Console.WriteLine(path);
    End:;
        // issue at path in this line
        Console.WriteLine(path);
    

    修理

        string path = null;
        goto End;
    AnotherLabel:
        path = @"C:\incidents\jobTransfer";
        Console.WriteLine(path);
    End:;
        // no issue at path in this line
        Console.WriteLine(path);
    

    建议

        string path = @"C:\incidents\jobTransfer";
        goto End;
    AnotherLabel:
        Console.WriteLine(path);
    End:;
        // no issue at path in this line
        Console.WriteLine(path);
    

        // don't use labels, due to these kinds of obscurities ;-)
    
        2
  •  0
  •   Ray K    6 年前

    问题很可能是您的标签-这允许代码路径跳转到允许不设置“路径”的“结束”标签。

    2个简单的解决方案:

    • 在“End”标签后面重新分配“path=@”C:\incidents\jobTransfer“;”,您提到的这是有问题的,因为如果更改,您将有两个地方可以编辑代码。(不过,如果在某种配置文件中对其进行参数化,则可以更改一次)。
    • 将标签放在“path”的原始赋值上方,并使用一些条件跳过文件.writeAllines(路径+事件+“\result”+事件+“.txt”,结果文本到数组());“如果不需要。

    一个更好的解决办法是根本不使用标签——这些标签通常是不受欢迎的,而你的问题是其中的一个原因;尽管在每个人都因为使用goto而跳进你的喉咙之前,有一些可以接受的理由 reasons to use it .

        3
  •  -1
  •   RoguePlanetoid    6 年前