我有 C/C++ 背景。我通常在代码中添加大量断言,而在 C 或 C++ 中,没有保证的方法可以消除作为断言参数的子表达式的求值。所以我不得不使用宏。
在 C# 中,我没有那种级别的宏支持。但我有 Conditional
属性。根据我使用 C 和 C++ 的经验,由于副作用,无法消除子表达式。
例如,
[Conditional(DEBUG)]
void func1(int a)
{
// Do something.
}
int func2()
{
// Will this be called?
}
func1(func2());
如果 func2
仍在被调用,我应该像 isDebugMode() && func1(func2())
那样编码。但这是我真正想避免的。所以我想知道 Conditional
属性是否保证消除子表达式。
如果没有,编写调试构建断言的最佳实践是什么?该断言将在发布构建时被完全剥离?
据我所知,这是编译器特定的支持。我想了解Mono编译器的情况。
最佳答案
func2 不会被调用。 C# 语言规范中有规定,因此 Mono 编译器必须按照这些规则行事。
MSDN http://msdn.microsoft.com/en-us/library/aa664622(v=vs.71).aspx :
The attribute Conditional enables the definition of conditional methods. The Conditional attribute indicates a condition by testing a conditional compilation symbol. Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. If the symbol is defined, the call is included; otherwise, the call (including evaluation of the parameters of the call) is omitted.
关于c# - 条件属性是否也消除子表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17966372/