我正在使用Debug.Assert在一个.NET Core 2.0的C#控制台应用程序中,惊讶地发现它只在输出窗口静默显示“DEBUG ASSERTION FAILS”,而没有打断调试器或显示任何消息框。
如何在.NET Core 2.0中恢复这种常见行为?
我正在使用Debug.Assert在一个.NET Core 2.0的C#控制台应用程序中,惊讶地发现它只在输出窗口静默显示“DEBUG ASSERTION FAILS”,而没有打断调试器或显示任何消息框。
如何在.NET Core 2.0中恢复这种常见行为?
如果您不想连接自定义侦听器,最简单的解决方法是使用自定义 Debug
类,如果平台目标不是 Framework,则会替换原始类:
#if !NETFRAMEWORK // this class is active for non-Framework platforms only
using System.Diagnostics;
using SystemDebug = System.Diagnostics.Debug;
namespace MyRootNamespace // so in your project this will hide the original Debug class
{
internal static class Debug
{
[Conditional("DEBUG")] // the call is emitted in Debug build only
internal static void Assert(bool condition, string message = null)
{
if (!condition)
Fail(message);
}
[Conditional("DEBUG")]
internal static void Fail(string message)
{
SystemDebug.WriteLine("Debug failure occurred - " + (message ?? "No message"));
if (!Debugger.IsAttached)
Debugger.Launch(); // a similar dialog, without the message, though
else
Debugger.Break(); // if debugger is already attached, we break here
}
[Conditional("DEBUG")]
internal static void WriteLine(string message) => SystemDebug.WriteLine(message);
// and if you use other methods from Debug, define also them here...
}
}
#endif