gpt4 book ai didi

.net - 为什么 .NET 的条件属性会导致副作用被删除?

转载 作者:行者123 更新时间:2023-12-04 00:25:29 26 4
gpt4 key购买 nike

我读到了 Conditional今天的属性。根据 MSDN:

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.



好的。这很清楚。因此不会编译对该方法的调用。但是副作用呢?
[Conditional("UndefinedCondition")]
static void f1(int x) { Console.WriteLine(x); }

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

所以当 f2被调用,调用 f1应该被删除。但为什么是 ++a也删除了?这对我来说没有任何意义!

最佳答案

扩展马克的答案。

这绝对是“按设计”。理解这种合理化的最好方法是考虑这段代码取代了什么。此功能在许多且更简洁的方式中采用了条件编译代码的方式。

例如,

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

或者其他版本
#define f1(x) ...

在非调试情况下,显然没有副作用。这与 [Conditional] 代码的行为相同。我同意它绝对没有第一个例子那么清楚,但它和第二个例子一样清楚。

关于.net - 为什么 .NET 的条件属性会导致副作用被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/410865/

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