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 Fiddle 供您尝试。
您可以分别注释掉顶部的两行以获得不同的结果,例如:
#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
}
我进行了一些谷歌搜索,但没有发现任何关于预处理器指令嵌套的正面陈述。我希望能够做这样的事情:
#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 Fiddle 供您尝试。
您可以分别注释掉顶部的两行以获得不同的结果,例如:
#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
}