c# - 条件属性是否也消除子表达式?

标签 c# mono conditional-compilation

我有 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/

相关文章:

if-statement - Ada 中的 end if 语句与其他语言相比有什么优势

c# - Initializer List 和 Constructor 函数调用顺序

c# - AutoMapper,如何保持映射对象之间的引用?

mono - 如何在 Mono 上开发 IronPython 应用程序?

android - MonoDroid Camera.IshutterCalBack

c++ - Visual Studio 在使用 `#ifdef` 时错误地标记非事件代码块

asp.net-mvc-3 - 在 MVC View 中使用条件编译符号

c# - SslStream.DataAvailable 不是有效函数

c# - 找不到 Microsoft.WindowsAzure.Diagnostics 类的类型

visual-studio - 单声道开发和 Visual Studio 兼容性