C# 如果设置了这个变量,为什么不设置它?
C# Why isn't this variable set if it's set?
请帮忙。由于我缺乏编程知识,无法解决它。
public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
StreamWriter OutPath;
try
{
OutPath = new StreamWriter(path, rewrite);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
for(int i = 0; i < NumberOfWords; i++)
{
try
{
OutPath.Write(NumberOfWords[i]);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
OutPath.Close();
}
您的问题是您实际上在 try-catch 中设置了 OutPath 变量。这意味着您的变量仅在 try-catch 的范围内设置。试试这个
public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
StreamWriter OutPath;
try
{
OutPath = new StreamWriter(path, rewrite);
for(int i = 0; i < NumberOfWords; i++)
{
try
{
OutPath.Write(NumberOfWords[i]);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
OutPath.Close();
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
请帮忙。由于我缺乏编程知识,无法解决它。
public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
StreamWriter OutPath;
try
{
OutPath = new StreamWriter(path, rewrite);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
for(int i = 0; i < NumberOfWords; i++)
{
try
{
OutPath.Write(NumberOfWords[i]);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
OutPath.Close();
}
您的问题是您实际上在 try-catch 中设置了 OutPath 变量。这意味着您的变量仅在 try-catch 的范围内设置。试试这个
public static void FileOutput(string path, bool rewrite, List<int> NumberOfWords)
{
StreamWriter OutPath;
try
{
OutPath = new StreamWriter(path, rewrite);
for(int i = 0; i < NumberOfWords; i++)
{
try
{
OutPath.Write(NumberOfWords[i]);
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}
OutPath.Close();
}
catch(IOException e)
{
Console.WriteLine(e.Message);
}
}