简体   繁体   English

是否可以将Debug.Assert设置为仅引发异常,而不是在C#中弹出窗口?

[英]Can Debug.Assert be set to just throw an exception instead of popping up a window in C#?

I'd like an exception to be thrown and the editor to jump to the place whenever an assertion fails in my C# application. 每当我的C#应用​​程序中的断言失败时,我都想引发一个异常并使编辑器跳到该位置。 But an abort/retry/ignore message box pops up instead. 但是会弹出一个中止/重试/忽略消息框。 Is there a way to control this behaviour? 有没有办法控制这种行为?

Not directly: That is what Debug.Assert does. 不直接:这就是Debug.Assert所做的。 See the documentation 请参阅说明文件

http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.aspx http://msdn.microsoft.com/zh-CN/library/system.diagnostics.debug.aspx

Perhaps you want to use something other than Debug.Assert? 也许您想使用除Debug.Assert之外的其他工具? Such as simply throwing an exception if it can't be handled, or by invoking some application-defined onError handler when desired? 例如,如果无法处理就抛出异常,或者在需要时调用一些应用程序定义的onError处理程序?

Alternatively, you may be able to get what you want by adding a listener and hooking into that listener. 或者,您可以通过添加侦听器并挂接到该侦听器来获得所需的内容。 See the documentation. 请参阅文档。

You could add a custom TraceListener which throws an exception on either of the .Fail() methods: 您可以添加一个自定义的TraceListener,它在.Fail()方法中的任何一个上引发异常:

public class ThrowListener : TextWriterTraceListener
{
    public override void Fail(string message)
    {
        throw new Exception(message);
    }

    public override void Fail(string message, string detailMessage)
    {
        throw new Exception(message);
    }
}

I would probably derive your own Exception type which takes both a message and detailMessage and so it's more obvious where the exception's coming from. 我可能会派生出您自己的同时包含message和detailMessage的Exception类型,因此更明显的是异常来自何处。

You will have to step up the call stack to the .Assert() call as the debugger will likely take you straight to the throw . 您将不得不提高对.Assert()调用的调用堆栈,因为调试器可能会直接将您带到throw

You can add it like this: 您可以这样添加它:

Debug.Listeners.Insert(0, new ThrowListener());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM