繁体   English   中英

可以嵌套C#预处理程序指令吗?

[英]Can C# preprocessor directives be nested?

我做了一些谷歌搜索,但没有发现任何有关预处理器指令嵌套的肯定声明。 我希望能够做这样的事情:

#if FOO
// do something
#if BAR
// do something when both FOO and BAR are defined
#endif 
#endif

我知道我可以做以下类似的事情,但是只是想知道。

#if FOO && (!BAR)
#elif FOO && BAR
#endif

(编辑)实际上,我的代码中已有一个更复杂的嵌套语句,但是它没有达到我的期望。 因此,我很好奇是否对此有正式的看法。

是的,它们可以嵌套。

#define A
#define B

void Main()
{
#if A
#if B
    Console.WriteLine("A and B");
#else
    Console.WriteLine("A and not B");
#endif
#else
#if B
    Console.WriteLine("B and not A");
#else
    Console.WriteLine("neither A nor B");
#endif
#endif
}

输出:

A and B

这是一个.NET提琴供您尝试。

您可以分别注释掉顶部的两行以获得不同的结果,例如:

#define A
// #define B

输出:

A and not B

这是带有缩进的相同代码,它使内容更清晰,尽管我不会缩进这样的代码。 我认为过度使用这样的条件指令是一种代码味道。

#define A
// #define B

void Main()
{
    #if A
        #if B
            Console.WriteLine("A and B");
        #else
            Console.WriteLine("A and not B");
        #endif
    #else
        #if B
            Console.WriteLine("B and not A");
        #else
            Console.WriteLine("neither A nor B");
        #endif
    #endif
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM