问题
In C#, if preprocessor directives are instructions pre-processed before actual compilation then why is it not executed first in this program?
static void Main(string[] args)
{
Program1.display();
Program2 p2 = new Program2();
p2.show();
#if DEBUG
Console.WriteLine("DEBUG from preprocessor directive is working!");
#endif
}
Expected Output:
DEBUG from preprocessor directive is working!
.......(from display())
.......(from show())
But Actual Output:
.......(from display())
.......(from show())
DEBUG from preprocessor directive is working!
回答1:
The output you are expecting is wrong.
Code processed (to be compiled) in DEBUG
mode/configuration
static void Main(string[] args)
{
Program1.display();
Program2 p2 = new Program2();
p2.show();
Console.WriteLine("DEBUG from preprocessor directive is working!");
}
Code processed (to be compiled) in non-DEBUG
mode/configuration
static void Main(string[] args)
{
Program1.display();
Program2 p2 = new Program2();
p2.show();
}
Hope this clears your confusion that preprocessors don't decide execution order.
回答2:
C# Language Specification, Section2.5
The pre-processing directives provide the ability to conditionally skip sections of source files, to report error and warning conditions, and to delineate distinct regions of source code. The term “pre-processing directives” is used only for consistency with the C and C++ programming languages. In C#, there is no separate pre-processing step; pre-processing directives are processed as part of the lexical analysis phase
Pre-processing directives are not tokens and are not part of the syntactic grammar of C#. However, pre-processing directives can be used to include or exclude sequences of tokens and can in that way affect the meaning of a C# program
来源:https://stackoverflow.com/questions/40160048/preprocessor-directives-in-c-sharp