为什么在.NET Core中Debug.Assert不会中断或显示消息框?

3

我正在使用Debug.Assert在一个.NET Core 2.0的C#控制台应用程序中,惊讶地发现它只在输出窗口静默显示“DEBUG ASSERTION FAILS”,而没有打断调试器或显示任何消息框。

如何在.NET Core 2.0中恢复这种常见行为?


这就是它的预期功能https://msdn.microsoft.com/en-us/library/kssw4w7z(v=vs.110).aspx。很失望,我们编写了自己的断言来调用Debuger.Launch。 - pm100
2个回答

3

如果您不想连接自定义侦听器,最简单的解决方法是使用自定义 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

3
这里有一个GitHub问题:Debug.Assert(false)与完整的CLR相比表现不一致
dotnet团队正在等待更多社区的关注:
设计合适的xplat机制和正确的配置选项并不是我想在没有更多社区参与和输入的情况下开始的事情。
为了恢复这种行为,我们可以像pm100那样编写自己的assert。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接