如何断言在C#中启用断言?
这样做的目的是防止使用释放类型的程序集,因为在效率无关紧要的情况下,我可能会在所有断言都起作用的情况下运行,因此在某些情况下,首选调试类型的程序集。
使用Debug.Assert(false)
不能令人满意,因为它会创建一个对话框并需要用户交互。知道断言没有“噪声”就可以了。Java解决方案是无噪音的。
编辑:这是从接受的答案下的评论中摘录的。
public static class CompileTimeInformation
{
public static void AssertAssertionsEnabled()
{
// Recall that assertions work only in the debug version of an assembly.
// Thus the assertion that assertions work relies upon detecting that the assembly was compiled as a debug version.
if (IsReleaseTypeAssembly())
throw new ApplicationException("Assertions are not enabled.");
}
public static bool IsReleaseTypeAssembly()
{
return ! IsDebugTypeAssembly();
}
public static bool IsDebugTypeAssembly()
{
return
#if DEBUG
true
#else
false
#endif
;
}
}
更新:有一个更简单的解决方案。另一个仍然出于好奇。
public static bool AreAssertionsEnabled =
#if DEBUG
true
#else
false
#endif
;
看起来很讨厌,但是很简单。
首先让我们看一下Debug.Assert
在非DEBUG版本中消失的原因:
[Conditional("DEBUG"), __DynamicallyInvokable]
public static void Assert(bool condition)
{
TraceInternal.Assert(condition);
}
是[Conditional("DEBUG")]
。这激发了以下解决方案:
public static bool AreAssertionsEnabled = false;
static MyClassName() { MaybeSetEnabled(); /* call deleted in RELEASE builds */ }
[Conditional("DEBUG")]
static void MaybeSetEnabled()
{
AreAssertionsEnabled = true;
}
您可能可以重构它,这样AreAssertionsEnabled
就可以了readonly
。我只是现在想不出办法。
现在,您可以检查布尔值AreAssertionsEnabled
并根据该值执行您喜欢的任何逻辑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句