gpt4 book ai didi

c# - 如何告诉编译器变量将存在

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:38 25 4
gpt4 key购买 nike

您如何告诉 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 写入会及时存在,但编译器不存在。

我怎样才能让编译器忽略它?

最佳答案

您可以在声明时将 null 赋值给 fileOut,然后检查它是否不为 null:

    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);

关于c# - 如何告诉编译器变量将存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45079958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com