. net断言断言被启用

本文关键字:断言 启用 net | 更新日期: 2023-09-27 17:51:13

如何断言断言在c#中是启用的?

这里有一个Java相关答案的链接,在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
        ;
    }
}

. net断言断言被启用

更新:有一个更简单的解决方案。另一个还在下面供好奇的人观看。

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并基于它执行任何您喜欢的逻辑。