#Define Compiler Directive in C#

Pau*_*els 7 c# compiler-directives

In C, I could declare a compiler directive as follows:

#define MY_NUMBER 10
Run Code Online (Sandbox Code Playgroud)

However, in C#, I only appear to be able to do this:

#define MY_NUMBER
Run Code Online (Sandbox Code Playgroud)

Which is obviously useless in this case.

Is this correct, or am I doing something wrong? If not, can anyone suggest a way of doing this, either at namespace or solution level? I thought of maybe creating a static class, but that seems to be overkill for one value.

Enr*_*lio 6

是的,这是正确的.

以下是MSDN文档中的引用:

预处理指令提供了有条件地跳过源文件部分,报告错误和警告条件以及描述源代码的不同区域的能力.术语"预处理指令"仅用于与C和C++编程语言的一致性.在C#中,没有单独的预处理步骤; 预处理指令作为词法分析阶段的一部分进行处理.

因此,您无法真正定义编译器常量,例如在C和C++中.

相关资源:


小智 5

许多其他答案建议使用public const字段.但请注意,a public const将被编译为引用它的程序集,强制您不仅重新编译它定义的程序集,而且还要重新编译引用它的每个程序集(如果您更改了它的值)const.

如果您不确定该值是否永远不会改变,则public static readonly字段是更好的选择.