简体   繁体   English

C#中的#Define编译器指令

[英]#Define Compiler Directive in C#

In C, I could declare a compiler directive as follows: 在C中,我可以声明一个编译器指令,如下所示:

#define MY_NUMBER 10

However, in C#, I only appear to be able to do this: 但是,在C#中,我似乎只能这样做:

#define MY_NUMBER

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. 我想过可能会创建一个静态类,但这对于一个值来说似乎有些过分。

Yes, it is correct. 是的,这是正确的。

Here's a quote from the MSDN documentation: 以下是MSDN文档中的引用:

The pre-processing directives provide the ability to conditionally skip sections of source files, to report error and warning conditions, and to delineate distinct regions of source code . 预处理指令提供了有条件地跳过源文件部分,报告错误和警告条件以及描述源代码的不同区域的能力 The term "pre-processing directives" is used only for consistency with the C and C++ programming languages. 术语“预处理指令”仅用于与C和C ++编程语言的一致性。 In C#, there is no separate pre-processing step; 在C#中,没有单独的预处理步骤; pre-processing directives are processed as part of the lexical analysis phase. 预处理指令作为词法分析阶段的一部分进行处理。

So you can't really define compiler constants, like in C and C++. 因此,您无法真正定义编译器常量,例如在C和C ++中。

Related resources: 相关资源:

A lot of the other answers suggest using a public const field. 许多其他答案建议使用public const字段。 Note however that a public const will be compiled into assemblies referencing it, forcing you to recompile not only the assembly it is defined in but also every assembly referencing it if you ever change the value of the const . 但请注意, public const将被编译为引用它的程序集,强制您不仅重新编译它定义的程序集,而且还要重新编译引用它的每个程序集(如果您更改了const的值)。

If you are not certain the value will never have to change, a public static readonly field is a better alternative. 如果您不确定该值是否永远不会改变,那么public static readonly字段是更好的选择。

Yes, you're correct. 是的,你是对的。 const and readonly are really your only options. constreadonly确实是你唯一的选择。

You can define a const or a static readonly, and if you want it conditionally you can wrap it in an #if directive 你可以定义一个const或一个静态readonly,如果你有条件地想要它,你可以将它包装在一个#if指令中

#if DEBUG
private const int MY_NUMBER = 10;
#else
private const int MY_NUMBER = 20;
#endif

Use public const 使用公共const


AFAIK, 据我所知,

C# does not use pre-processor defines to perform replacement in code, so you have to use a constant. C#不使用预处理器定义来执行代码替换,因此必须使用常量。

This should do the trick: 这应该做的伎俩:

public const int MY_NUMBER = 10;

You might also like to check enums, like 您可能还想检查枚举,例如

enum Numbers
{
    Nothing = 0,
    Dads = 5,
    My = 10,
    LittleJims = 25
}

So, instead of C's MY_NUMBER, you have Numbers.My. 所以,而不是C的MY_NUMBER,你有Numbers.My。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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