[英]Why Conditional attribute methods aren't allowed to return other than void
I've recently started to learn C# with a good book and now read about the Conditional
attribute and the #if
compiler directive.我最近开始通过一本好书学习 C#,现在阅读了有关Conditional
属性和#if
编译器指令的内容。
I know the usage of the #if
compiler directive:我知道#if
编译器指令的用法:
#if DEBUG
public void foo(int value)
{ ... }
#endif
and of the Conditional
attribute:和Conditional
属性:
[System.Diagnostics.Conditional("DEBUG")]
public void foo(int value)
{ ... }
I also know that the code that is encased by the #if
... #endif
statements doesn't reach the IL but the Conditional
attribute code does and the calls to that function will be ommited.我也知道被#if
... #endif
语句封装的代码没有到达 IL,但是Conditional
属性代码到达了,并且对该函数的调用将被省略。
My question:我的问题:
Why there is the restriction about the Conditional
attribute usage that functions marked with that attribute have to return void
as written here in the documentation ?为什么对Conditional
属性的使用有限制,即标记有该属性的函数必须返回void
,如文档中所写?
You will get a compilation error in Visual Studio if you apply this attribute to a method that does not return void.如果将此特性应用于不返回 void 的方法,您将在 Visual Studio 中收到编译错误。
I already searched for information but found no explanation.我已经搜索了信息,但没有找到任何解释。
The compiler does not allow it, because if it were allowed, then the semantics of code like below would be undefined, or at best rather hard to understand:编译器不允许它,因为如果它被允许,那么像下面这样的代码的语义将是未定义的,或者充其量是相当难以理解的:
var x = someMethod(foo());
[System.Diagnostics.Conditional("DEBUG")]
public int foo()
{
return 42;
}
The [Conditional("DEBUG")]
attribute on a method means that both the method and any calls to the method are omitted from the compiled code if the DEBUG
symbol is present.方法上的[Conditional("DEBUG")]
属性意味着如果存在DEBUG
符号,则该方法和对该方法的任何调用都将从编译代码中省略。
But if the call to foo()
- which returns a result - disappears from the compiled code, what to pass into someMethod()
?但是,如果对返回结果的foo()
的调用从编译后的代码中消失,那么将什么传递给someMethod()
呢? Or if that call is then also removed, what to assign to x
?或者,如果该调用随后也被删除,那么分配给x
的是什么? How to guarantee that the local x
even has a value, which would normally cause a compile error?如何保证本地x
甚至有一个通常会导致编译错误的值?
The .NET team decided not to go that way, instead they added a compile-time constraint that [Conditional()]
methods must be void
methods. .NET 团队决定不采用这种方式,而是添加了一个编译时约束,即[Conditional()]
方法必须是void
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.