gpt4 book ai didi

c# - C# 预处理器指令可以嵌套吗?

转载 作者:行者123 更新时间:2023-12-05 00:58:56 26 4
gpt4 key购买 nike

我进行了一些谷歌搜索,但没有找到任何关于预处理器指令嵌套的正面陈述。我希望能够做这样的事情:

#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
}

关于c# - C# 预处理器指令可以嵌套吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55532710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com