gpt4 book ai didi

c# - 在 C# 中将调试字符串排除在构建之外

转载 作者:行者123 更新时间:2023-12-02 16:06:06 24 4
gpt4 key购买 nike

在编写代码时,我经常在代码中放置调试消息。调试消息由记录器类处理,该类在 Debug模式下将消息输出到文件,并在 Release模式下丢弃它们。

它看起来有点像这样:

class Logger : IDisposable
{
private StreamWriter m_Logger = null;

public void Start(string logFile)
{
m_Logger = new StreamWriter(logFile);
m_Logger.AutoFlush = true;
}

public void Dispose()
{
if (m_Logger != null) m_Logger.Dispose();
}

public void WriteLine(string message)
{
if (m_Logger != null) m_Logger.WriteLine(message);
}
}

实例在启动时创建,并且可以从 Program 类访问。然后我像这样检查调试:

#if DEBUG
Program.Log.Start("app.log");
#endif

这非常有效,因为它在 Debug模式下转储调试信息,而在 Release模式下则不转储调试信息。但是,如果我通过 strings 等实用程序运行发布可执行文件,我仍然可以看到调试字符串。我宁愿将它们完全排除在发布版本之外,以帮助防止逆向工程。

到目前为止我发现的唯一解决方案是将所有调试消息包装在预处理器条件中:

// < some code here >
#if DEBUG
Program.Log.WriteLine("Some debug message.");
#endif
// < more code here >

这非常乏味且丑陋。我的第一个想法是使用某种预处理器宏,但 C# 不支持它们。有没有比我现在使用的解决方案更优雅的解决方案?

最佳答案

要避免在每次 WriteLine 调用上使用 #if-#endif,请尝试使用 ConditionalAttribute在记录器方法本身上:

[Conditional("DEBUG")]
public void WriteLine(string message)
{
if (m_Logger != null) m_Logger.WriteLine(message);
}

如果是发布版本,这将从 MSIL 中排除。

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated with ConditionalAttribute is defined. Applying ConditionalAttribute to an attribute indicates that the attribute should not be emitted to metadata unless the conditional compilation symbol is defined

关于c# - 在 C# 中将调试字符串排除在构建之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016292/

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