gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:15:25 26 4
gpt4 key购买 nike

我有 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# Language Specification 中有说明,因此 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com