如何防止 Debug.Assert(...) 显示模式对话框
我有几个使用 Debug.Assert(...) 的库。我认为 Debug.Assert(...) 很好,我仍然希望它们执行,但我不希望它们阻止我的应用程序的执行。理想情况下,我只希望将它们记录在某个地方。
鉴于我无法更改库的代码(并且我仍然想在调试中编译并运行断言),如何防止 Debug.Assert(...) 显示模态对话框?
此外,我想确保主程序在发生 Assert
时继续运行(与“忽略”按钮的行为相同)。
谢谢!
I have a couple of libraries which use Debug.Assert(...)
. I think that the Debug.Assert(...)
are fine and I still want them to execute, but I don't want them to block the execution of my application. Ideally, I would only like them to be logged somewhere.
Given that I can't change the code of the libraries (and that I still want to compile in debug and run the assertion), how do I prevent Debug.Assert(...)
to show a modal dialog?
In addition, I would like to make sure that the main program continues when an Assert
occurs (same behavior as the Ignore button).
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不会推荐它。问题是
Debug.Assert
仅当代码中存在错误时才会被触发。。如果您只是忽略它们或不修复它们,那么您就是在伤害用户。另一方面,如果您为那些不是 bug 的事情触发Debug.Assert
,那么您也会对用户造成伤害(通过减少Debug.Assert 的影响)。话虽如此,您可以禁用它。您需要做的第一件事是从 Debug.Listeners 集合:
然后,添加您自己的集合:
您需要创建一个继承自 TraceListener:
重要的方法是 TraceListener.Fail方法,该方法在
的实现中DefaultTraceListener
是显示消息框的。I wouldn't recommend it. The problem is that
Debug.Assert
is only supposed to be fired when you have bugs in your code. If you just ignore them or don't fix them, then you are doing your users a disservice. If, on the other hand, you're firingDebug.Assert
for things that aren't bugs, then you're also doing your users a disservice (by reducing the impact of Debug.Assert).Having said that, you can disable it. The first thing you need to do is remove the default listener from the Debug.Listeners collection:
Then, add your own instead:
You need to create a class that inherits from TraceListener:
The important method is the TraceListener.Fail method, which in the implementation of
DefaultTraceListener
is what displays the message box.不需要
Debug.Listeners.Clear()
只需添加到您的 .config 中即可:
There is no need for
Debug.Listeners.Clear()
Just add to your .config:
如果你想用一把非常大的锤子敲击东西,Codekas 的答案是正确的。您可以使用应用程序配置文件中的
元素将assertuienabled 属性设置为 false,并可选择为要写入的断言提供日志文件。那么您就不必编写自己的侦听器。您可以在 MSDN 页面 中了解有关断言元素的更多信息。
Codekas answer is correct, if you want to hit things with a really big hammer. You can use the
<assert>
element in your application configuration file to set assertuienabled property to false and optionally give a log file for Asserts to be written to. Then you won't have to write your own listener.You can read more about the assert element at its MSDN page.