如何告诉编译器变量是否存在

时间:2017-07-13 11:57:54

标签: c# visual-studio

如何告诉Visual Studio相信变量在需要时将存在。这是我的代码:

            string line;
        bool fileExists = false;
        System.IO.StreamReader fileIn;
        System.IO.StreamWriter fileOut;

        fileIn = new System.IO.StreamReader(inputFile);

        while ((line = fileIn.ReadLine()) != null)
        {
            if (line.Length > 0 && line.Substring(0, 1) == "O")
            {
                _parent.StatusOutput(line);
                if (fileExists)
                {
                    // close the existing file ...
                    fileOut.WriteLine();
                    fileOut.WriteLine();
                    fileOut.WriteLine("%");
                    fileOut.Close();
                }
                // create a new file ...
                fileOut = new System.IO.StreamWriter(outputFolder + @"\" + line);
                fileExists = true;
                fileOut.WriteLine();
                fileOut.WriteLine("%");
                fileOut.WriteLine(line);
            }
            else if (line.Length == 0)
            {
                _parent.StatusOutput("Blank line.");
                if (fileExists) fileOut.WriteLine();
            }
            else if (line.Length > 0 && line == "%")
            {
                _parent.StatusOutput("BO/EOF found.");
                // do nothing ...
            }
            else
            {
                // everything else goes to the new file ...
                if (fileExists) fileOut.WriteLine();
            }
        }    // while ...

        // close the last file ...
        fileOut.WriteLine();
        fileOut.WriteLine();
        fileOut.WriteLine("%");
        fileOut.Close();
        fileIn.Close();

错误是我尝试写入fileOut时。我知道fileOut write会及时存在,但编译器没有。

如何让编译器忽略它?

感谢, 伯尼

2 个答案:

答案 0 :(得分:3)

您可以在声明时将null指定给fileOut,然后检查它是否为空:

    string line;
    System.IO.StreamReader fileIn;
    System.IO.StreamWriter fileOut = null;

    fileIn = new System.IO.StreamReader(inputFile);

    while ((line = fileIn.ReadLine()) != null)
    {
        if (line.Length > 0 && line.Substring(0, 1) == "O")
        {
            _parent.StatusOutput(line);
            if (fileOut != null)
            {
                // close the existing file ...
                fileOut.WriteLine();
                fileOut.WriteLine();
                fileOut.WriteLine("%");
                fileOut.Close();
            }

            // create a new file ...
            fileOut = new System.IO.StreamWriter(outputFolder + @"\" + line);
            fileOut.WriteLine();
            fileOut.WriteLine("%");
            fileOut.WriteLine(line);

答案 1 :(得分:0)

你必须在使用之前进行初始化,就像在fileIn之后移动fileOut初始化一样。

fileIn = new System.IO.StreamReader(inputFile);

fileOut = new System.IO.StreamWriter(outputFolder + @"\" + line);