我正忙着优化我的一个应用程序,有什么最简洁的方法可以检查应用程序是否处于DEBUG或RELEASE模式?
在编译时还是运行时进行?在编译时,您可以使用#if DEBUG
。在运行时,您可以使用[Conditional("DEBUG")]
来指示仅应在调试版本中调用的方法,但这是否有用取决于您想在调试和发布版本之间进行的更改类型。
static class Program
{
public static bool IsDebugRelease
{
get
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
}
虽然我倾向于同意itowlson的观点。
就我个人而言,我不喜欢 #if DEBUG
更改布局的方式。我的做法是创建一个条件方法,只有在调试模式下才会被调用,并通过引用传递一个布尔值。
[Conditional("DEBUG")]
private void IsDebugCheck(ref bool isDebug)
{
isDebug = true;
}
public void SomeCallingMethod()
{
bool isDebug = false;
IsDebugCheck(ref isDebug);
//do whatever with isDebug now
}
我倾向于在 AssemblyInfo.cs 文件中添加以下内容:
#if DEBUG
[assembly: AssemblyConfiguration("Debug build")]
#else
[assembly: AssemblyConfiguration("Release build")]
#endif
即使线程已经过时,通过编程方式进行检查可能仍然有用。
测试
if (Debugger.IsAttached)
{
}
在运行时检查调试器是否已附加。IsAttached属性是Debugger类型的静态属性,因此始终提供结果(bool)。
#if DEBUG
预处理器指令目前是在编译时快速剪切一些代码或将其添加到其中的最快方式,但在转换发布和调试编译之间会导致警告,特别是当你在块内定义变量时(至少在注释中)。例如,请检查以下DebugInfo()方法的实现,该方法允许您轻松地将代码信息内联到日志记录工具中:
/// <summary>
/// A wrapper for debugging information in Serilog loggers.
/// Usage: Log.DebugInfo().Information(message)
/// Usage: Log.DebugInfo().Debug(message) etc.
/// </summary>
/// <param name="logger">
/// The Serilog Log to use.
/// </param>
/// <param name="memberName">
/// The name of the class calling the event log.
/// </param>
/// <param name="sourceFilePath">
/// The name of the file hosting the class.
/// </param>
/// <param name="sourceLineNumber">
/// the line in the source code file.
/// </param>
/// <returns>
/// </returns>
public static ILogger DebugInfo(this ILogger logger
#if DEBUG
// DebugInfo gets inline in release mode.
,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
#else
)
#endif
{
return logger
#if DEBUG
.ForContext("MemberName", memberName)
.ForContext("FilePath", Path.GetFileName(sourceFilePath))
.ForContext("LineNumber", sourceLineNumber)
#endif
;
}
}
可以这样调用
Logger.DebugInfo().Warning("Warning message with a parameter in message template style: {Parameter}", _parameter);
为了在日志文件中获得有关调用日志行的类和代码文件的更多信息。
解决方案将包括部分XML注释到条件语句中,但这会使整个内容变得难以理解。
在汉斯的提示之后,是有可能某人在VS之外运行调试版本的。然后,马修提出的静态方法IsDebugMode
是将条件语句的优点包含到一个简单的方法中而不允许它的缺点在代码中蔓延的最直接的方法。