Omitting code: Any difference between Conditional Attribute and pre-processing directive?

匆匆过客 提交于 2019-12-12 04:08:37

问题


I am wondering what the difference is between

#define MYSYMBOL

#if MYSYMBOL
public void foo () {

    // ...
}
#endif

and

#define MYSYMBOL

[Conditional("MYSYMBOL")]
public void foo () {

    // ...
}

?

Maybe it's obvious but if someone could give me a hint in the right direction I would be thankful :)


回答1:


They are different.

Using #if removes the enclosed code altogether, so any code that calls the method won't compile because the method has disappeared. You can also wrap any amount of code this way, not just a single whole method.

Using [Conditional] means the method won't be called at runtime, but calls to it will still compile ( but the calls will not be emitted in the IL code ). Also, this way, the method must return void and not have any out or ref parameters.




回答2:


Yes, there's a big difference: with the #if directive, the method is not compiled at all; it's just not there in the compiled code. With the Conditional attribute, the method is compiled, but whether it's called or not depends on the symbols in the client code. If the symbol is not defined in the calling code, the call site is removed, and the method is not called.

This is useful, for instance, for library code that will be called or not based on whether or not the DEBUG symbol is defined. An example is the Debug.Print method: it will be called only if your project is compiled with the DEBUG symbol, but the method is still there in System.dll whether or not the symbol is defined.



来源:https://stackoverflow.com/questions/10969841/omitting-code-any-difference-between-conditional-attribute-and-pre-processing-d

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