使用 C#,我想仅在用户指定(debug=true
标志)时打开输出文件(用于调试日志记录)。我尝试了一种在文件打开、写入和关闭时使用条件的方法。问题是这不会编译,因为上下文中不存在调试文件。
我想这是因为定义隐藏在条件中,但我不确定如何设置它。如果我不使用条件,任何预先存在的日志都会被清除,这是我不希望的。
请问正确的设置方法是什么?
这是我的测试代码:
using System;
public class DataProcessor
{
public void process_data(string output_filepath, bool debug=false)
{
debug = true; // manual override for debugging
if (debug == true)
{
System.IO.StreamWriter debug_file = new System.IO.StreamWriter(output_filepath);
}
for (int i=1; i<10; i++)
{
// do some other stuff
if (debug == true)
{
debug_file.WriteLine("output something: " + i);
}
}
// do some other stuff
if (debug == true)
{
debug_file.Close();
}
}
}
public class Program
{
static void Main()
{
DataProcessor data = new DataProcessor();
string output_filepath = "debug_output.txt";
data.process_data(output_filepath);
}
}
错误信息如下:
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved.
conditional_stream_open.cs(20,17): error CS0103: The name 'debug_file' does not exist in the current context
conditional_stream_open.cs(28,13): error CS0103: The name 'debug_file' does not exist in the current context
Tool completed with exit code 1
最佳答案
您正在 if
block 内声明 debug_file
。在该上下文之外将无法访问它。
您需要将声明移至方法的顶部:
System.IO.StreamWriter debug_file = null; // added null here to avoid unassigned variable
然后在 if 语句中:
debug_file = new System.IO.StreamWriter(output_filepath);
关于c# - 如何在 C# 中设置输出文件,仅当调试标志 = true 时才启用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754524/