单声道 – Debug.Assert不起作用

我有这个程序:

namespace TodoPlus { using System.Diagnostics; public class LameProg { public LameProg() {} public static void Main(string[] args) { int a = 2; int b = 3; Debug.Assert(a == b, "Bleh"); System.Console.WriteLine("Haha it didn't work"); } } } 

不知何故,Debug.Assert无效。

我正在使用Mono 2.10.5,这是我用来编译和执行的:

$ dmcs LameProg.cs

$ mono ./LameProg.exe

我怎样才能做到这一点? 我希望它与C中的断言宏具有相同的效果,也就是说它应该彻底崩溃程序。 是否可以使用Debug.Assert执行此操作,还是有其他function可以实现此目的?

谢谢。

  1. Debug.Assert用[ConditionalAttribute(“DEBUG”)]注释。 这意味着除非定义了DEBUG预处理程序符号,否则编译器将删除所有调用。 试试这个:

     $ dmcs -d:DEBUG LameProg.cs 
  2. 当一个断言命中时,Mono没有显示像Microsoft的.NET实现那样的对话框。 您需要设置TraceListener ,例如

     $ export MONO_TRACE_LISTENER=Console.Error $ mono LameProg.exe 

Debug.Assert调用通常用于调试版本,并从发布版本中删除。 如果要确保某个条件成立,并且此检查应该存在于发布版本中,请使用if语句并throwexception:

 public static void Main(string[] args) { int a = 2; int b = 3; if (a != b) { throw new Exception("Bleh"); } System.Console.WriteLine("Haha it didn't work"); } 

还有另一个技巧:您可以通过TraceListener添加“立即退出”行为,因为Debug.Assert失败会在跟踪侦听器中触发对Fail()的调用。

你仍然需要-define:DEBUG(和TRACE?)。 我个人希望Assert()调用(在DEBUG版本中)来停止我的程序,转储调试信息并退出。 所以,我就是这样做的:

在我的代码中,我安装了一个自定义跟踪侦听器来转储堆栈并添加对Exit()的调用。 而中提琴! 您对Assert.Fail()有行业标准响应。 例如,您也可以在此处打印时间戳等。

 public class DumpStackTraceListener : TraceListener { public override void Write( string message ) { Console.Write( message ); } public override void WriteLine(string message) { Console.WriteLine( message ); } public override void Fail(string message) { Fail( message, String.Empty ); } public override void Fail(string message1, string message2) { if (null == message2) message2 = String.Empty; Console.WriteLine( "{0}: {1}", message1, message2 ); Console.WriteLine( "Stack Trace:" ); StackTrace trace = new StackTrace( true ); foreach (StackFrame frame in trace.GetFrames()) { MethodBase frameClass = frame.GetMethod(); Console.WriteLine( " {2}.{3} {0}:{1}", frame.GetFileName(), frame.GetFileLineNumber(), frameClass.DeclaringType, frameClass.Name ); } #if DEBUG Console.WriteLine( "Exiting because Fail" ); Environment.Exit( 1 ); #endif } } 

结合致电:

 #if DEBUG Debug.Listeners.Add( new DumpStackTraceListener() ); #endif 

你很高兴去。

我相信你需要两件事:编译器的DEBUG属性和运行时的’trace listener’。 我得到它与合作

 % export MONO_TRACE_LISTENER=Console.Error % mcs -define:DEBUG -debug Prog.cs % mono Prog.exe 

这仍然没有像我预期的那样在断言失败时立即退出,但至少它打印出一些东西。