#define (C# 參考)#define (C# Reference)

您可以使用 #define 來定義符號。You use #define to define a symbol. 當您將符號作為運算式傳遞給 #if 指示詞時,運算式會判斷值為 true,如下列範例所示:When you use the symbol as the expression that's passed to the #if directive, the expression will evaluate to true, as the following example shows:

#define DEBUG

備註Remarks

注意

如果常數值通常是在 C 和 C++ 中進行宣告,您就不能使用 #define 指示詞進行宣告。The #define directive cannot be used to declare constant values as is typically done in C and C++. 在 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.

符號可以用來指定編譯的條件。Symbols can be used to specify conditions for compilation. 您可以使用 #if#elif 來測試符號。You can test for the symbol with either #if or #elif. 您也可以使用 ConditionalAttribute 執行條件式編譯。You can also use the ConditionalAttribute to perform conditional compilation.

您可以定義符號,但不能將值指派給符號。You can define a symbol, but you cannot assign a value to a symbol. 如果您要使用的任何指示並不是前置處理器指示詞,則檔案中必須先出現 #define 指示詞才行。The #define directive must appear in the file before you use any instructions that aren't also preprocessor directives.

您也可以使用 -define 編譯器選項來定義符號。You can also define a symbol with the -define compiler option. 您可以使用 #undef 來取消定義符號。You can undefine a symbol with #undef.

透過 -define#define 所定義的符號不會與相同名稱的變數發生衝突。A symbol that you define with -define or with #define does not conflict with a variable of the same name. 也就是說,您不應將變數名稱傳遞給前置處理器指示詞,而且符號僅能由前置處理器指示詞來評估。That is, a variable name should not be passed to a preprocessor directive and a symbol can only be evaluated by a preprocessor directive.

使用 #define 所建立的符號範圍即為定義符號的檔案。The scope of a symbol that was created by using #define is the file in which the symbol was defined.

如下列範例所示,您必須將 #define 指示詞放在檔案頂端。As the following example shows, you must put #define directives at the top of the file.

#define DEBUG  
//#define TRACE  
#undef TRACE  
  
using System;  
  
public class TestDefine  
{  
    static void Main()  
    {  
#if (DEBUG)  
        Console.WriteLine("Debugging is enabled.");  
#endif  
  
#if (TRACE)  
     Console.WriteLine("Tracing is enabled.");  
#endif  
    }  
}  
// Output:  
// Debugging is enabled.  

如需如何取消定義符號的範例,請參閱 #undefFor an example of how to undefine a symbol, see #undef.

另請參閱See also