【发布时间】:2015-04-20 17:30:56
【问题描述】:
使用 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 编译器版本 4.0.30319.1 版权所有 (C) 微软公司。保留所有权利。
conditional_stream_open.cs(20,17):错误 CS0103:当前上下文中不存在名称“debug_file”
conditional_stream_open.cs(28,13):错误 CS0103:当前上下文中不存在名称“debug_file”
工具已完成,退出代码为 1
【问题讨论】: