问题
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