将提供给Debug.Assert的前pression在发布版本进行评估?提供给、版本、Assert、Debug

2023-09-05 04:17:45 作者:我的孤独是一座花园

说我有一个相当昂贵的断言:

Say I have a rather expensive assertion:

bool IsCompatible(Object x, Object y) { 
  // do expensive stuff here
}

如果我测试这种说法有:

If I test this assertion with:

Debug.Assert(IsCompatible(x,y));

将相适应在发布执行建立?

Will IsCompatible be executed in release builds?

我的理解是,Debug.Assert的被标记为[条件(DEBUG)],调用它只会发出的调试版本。我在想,这会不会prevent被评估在释放模式虽然,因为方法调用可能有副作用前pression,只有合格的结果来Debug.Assert的不会发射。这是否正确?

My understanding is that Debug.Assert being marked as [Conditional("DEBUG")], calls to it will only be emitted in debug builds. I'm thinking that this won't prevent the expression from being evaluated in release mode though, since the method call may have side effects, only the passing of the result to Debug.Assert wouldn't be emitted. Is that correct?

我应该做的:

#if DEBUG
Debug.Assert(IsCompatible(x,y));
#endif

要确保我不交相适应的成本在释放模式?

To ensure that I don't pay the cost of IsCompatible in release mode?

推荐答案

没有。

Debug.Assert的饰有 [条件(DEBUG)]

在编译器编译调用此方法时,它会删除整个语句,除非 DEBUG 在所调用的项目中定义的。

When the compiler compiles a call to this method, it will remove that entire statement unless DEBUG is defined in the calling project.

 
精彩推荐
图片推荐