Does using ConditionalAttribute also remove arguments computation?

一个人想着一个人 提交于 2019-11-28 03:16:20

问题


I tried the following code:

class Magic {
   [Conditional("DEBUG")]
   public static void DoMagic( int stuff )
   {
   }
   public static int ComputeMagic()
   {
      throw new InvalidOperationException();
   }
}
class Program
{
   static void Main(string[] args)
   {
      Magic.DoMagic(Magic.ComputeMagic());
   }
}

and it looks like in Release build the exception is not thrown so not only the call to a method marked with ConditionalAttribute is removed, but also the parameters computation is eliminated.

Is such behavior guaranteed?


回答1:


Yes, argument evaluation is removed when DEBUG is not defined (which is typical in Release builds).

From http://msdn.microsoft.com/en-us/library/aa664622%28v=vs.71%29.aspx:

If the symbol is defined, the call is included; otherwise, the call (including evaluation of the parameters of the call) is omitted.




回答2:


Yes, everything is removed. This can be great for avoiding expensive computations that are only relevant for (say) logging, but it means you need to be careful not to remove necessary side-effects. For example:

Trace(SomethingCritical());

is very different to:

var result = SomethingCritical();
Trace(result);

or in your specific case:

DoMagic(ComputeMagic()); // everything here done only if DEBUG symbol defined

versus

var result = ComputeMagic(); // always done
DoMagic(result); // done only if DEBUG symbol defined

From the specification §17.4.2 (emphasis mine):

If the symbol is defined, the call is included; otherwise, the call (including evaluation of the receiver and parameters of the call) is omitted.



来源:https://stackoverflow.com/questions/21935452/does-using-conditionalattribute-also-remove-arguments-computation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!