简体   繁体   中英

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

Could I use #define preprocessor directive inside #if and #endif , in C# ?

eg

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

It looks like it works, but I need to be sure. There is a lot written about this, but most of the time in the context of C and not C# - the preprocessor directives a in C# far more limited.

Visual Studio's highlighting seems to support it, but it this really valid according to the language / compiler specs?

The This MSDN page gives the following note:

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.

I need this because using #if !SILVERLIGHT && !__ANDROID__ && !__IOS__ multiple times is difficult to manage.

Of course we could also add SupportsMutex to the "conditional compilation symbols" of a project, but this is more difficult to manage and less transparant.

Yes. Looking at the C# specification a particular example of this usage is given in section 2.5.3 Declaration directives and deemed as valid:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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