Preprocessor directives in C#

邮差的信 提交于 2021-02-19 07:47:10

问题


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

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