在 C# 中的 #if 中使用 #define 预处理器指令是否有效

Is it valid to use the #define preprocessor directive inside an #if in C#

我可以在 C# 中的 #if#endif 中使用 #define preprocessor directive 吗?

例如

#if !SILVERLIGHT && !__ANDROID__ && !__IOS__ 
#define SupportsMutex
#endif

看起来可行,但我需要确定一下。有很多关于此的文章,但大部分时间是在 C 而不是 C# 的上下文中 - C# 中的预处理器指令 a 更为有限。

Visual Studio 的突出显示似乎支持它,但根据语言/编译器规范,这真的有效吗?

This MSDN page给出了以下注释:

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

我需要这个,因为多次使用 #if !SILVERLIGHT && !__ANDROID__ && !__IOS__ 很难管理。

当然我们也可以在一个项目的"conditional compilation symbols"中加上SupportsMutex,但是这样比较难管理,也不太透明。

是的。查看 C# specification 此用法的特定示例在 2.5.3 声明指令 部分中给出并被视为有效:

#define Enterprise
#if Professional || Enterprise  
   #define Advanced
#endif 
namespace Megacorp.Data 
{
    #if Advanced    
    class PivotTable {...}  
    #endif 
}