为什么.NET的条件属性产生副作用被删除?副作用、属性、条件、NET

2023-09-05 02:57:10 作者:單身的人最怕過節〃

我读了条件属性的今天。根据MSDN:

I read about the Conditional attribute today. According to MSDN:

应用 ConditionalAttribute 来的方法指示编译器的调用方法不应该被编译成Microsoft中间语言(MSIL),除非是与相关的条件编译符号 ConditionalAttribute 定义。

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated with ConditionalAttribute is defined.

确定。这是明显的。因此,调用方法的将不会被编译。但怎么样的副作用?

OK. That's clear. So the call to the method will not be compiled. But what about side effects?

[Conditional("UndefinedCondition")]
static void f1(int x) { Console.WriteLine(x); }

static int a = 0;
static void f2() { f1(++a); }

所以,当 F2 被调用,调用 F1 应该被删除。但是,为什么是 ++一个删除呢?这个简化版,任何意义我!

So when f2 is called, the call to f1 should be removed. But why is ++a removed as well? This does't make any sense to me!

推荐答案

扩大对马克的回答。

这绝对是按设计。了解合理化这一点的最好办法是想想这code注意到的地方。此功能在许多和更清洁的方式,利用了条件编译code的方式。

This is definitely "By Design". The best way to understand the rationalization for this is to think about what this code took the place of. This feature in many, and much cleaner ways, takes the way of conditionally compiled code.

例如,

#if DEBUG
f1(++a);
#endif

或者另一个版本的

Or another version

#define f1(x) ...

在非调试情况下明显有没有副作用。这是[有条件] code相同的行为。我同意这是绝对不明确的,因为第一个例子,但它是明确的,因为第二个。

In the non-debug case there are clearly no side effects. This is same behavior for [Conditional] code. I agree it's definitely not as clear as the first example, but it is as clear as the second one.