如何在 C# 中全局定义常量(如 DEBUG)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/436369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a constant globally in C# (like DEBUG)
提问by Victor Rodrigues
I want to compile a project differently, according to a constant defined by #define, like this:
我想根据#define 定义的常量以不同的方式编译项目,如下所示:
#define USE_COMPONENT_X
#if USE_COMPONENT_X
...
#endif
and I can do that in C#. But when I go to another file in the same project, this constant is not defined. Can I in some way define a constant to all the project, like DEBUG is defined so?
我可以在 C# 中做到这一点。但是当我转到同一个项目中的另一个文件时,没有定义这个常量。我可以以某种方式为所有项目定义一个常量,比如 DEBUG 是这样定义的吗?
采纳答案by Jason Diller
You can add the /define compiler switch.
您可以添加 /define 编译器开关。
- Open the project's Property Pages dialog box.
- Click the Configuration Properties folder.
- Click the Build property page.
- Modify the Conditional Compilation Constants property.
- 打开项目的属性页对话框。
- 单击配置属性文件夹。
- 单击构建属性页。
- 修改条件编译常量属性。
回答by polyethene
回答by Reddog
Hopefully I'm not way off topic, but rather than a "constant" perhaps define an interface for the constant's type and then use one of the many dependency injection frameworks to manage the definition, injection and lifetime of your "constant".
希望我不会偏离主题,而不是“常量”,而是为常量的类型定义一个接口,然后使用众多依赖注入框架之一来管理“常量”的定义、注入和生命周期。
回答by EnocNRoll - AnandaGopal Pardue
You may want to go a step further and create different project configurations as variants of the standard Debug and Release project configuration. The Configuration Manager under the build menu will let you accomplish this. Then while you are in the project properties' Build tab you can select the various configurations and set the conditional compilation constants that are appropriate for each configuration. This will save you lots of time when you want to swap back and forth between various permutations of your conditionally compiled code.
您可能想要更进一步,创建不同的项目配置作为标准调试和发布项目配置的变体。构建菜单下的配置管理器将让您完成此操作。然后,当您在项目属性的 Build 选项卡中时,您可以选择各种配置并设置适合每个配置的条件编译常量。当您想要在条件编译代码的各种排列之间来回交换时,这将为您节省大量时间。