c# - 如何在 C# 中设置输出文件,仅当调试标志 = true 时才启用?

标签 c# file-io

使用 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/

相关文章:

java - 在 Java 中传递命令行参数来复制文件名

windows - 检测文件是否在 Windows 中打开的编程方法是什么?

c# - 是否可以设计一个 C# 类,在通过反射查询时将其自身标记为正 IsValueType 和正 IsClass?

c# - 使用类从 asp.net 中的数据库填充下拉列表的方法是什么?

c# - 使用值和引用参数类型重载的方法

c# - MVC 5 仅在主页索引上显示布局中的局部 View

c# - 使用运行时文件名 P/调用 native DLL

java - 使用 Commons IO 复制时锁定文件

java - 如果移动了特定文件,如何读取它

java - 在java中不使用数据库来保留项目的历史记录