在C#DLL中替换#ifdefs [英] Replace #ifdefs in C# DLL
问题描述
我有一个C ++ DLL,其中#defines使用like(这些定义是基于构建配置自动定义的,例如Debug,Release等)
I have a C++ DLL which has #defines used like (these defines are automatically defined based on the build configuration, e.g. Debug, Release, etc)
#if defined(CONSTANT)
..
// Some code
#else
// Some other code
我需要在C#dll中使用相同的功能。
如果我在C#dll中定义一些全局常量并使用它们
而不是定义,它是否确定?
eg
I need same functionality in C# dll. Is it ok if I define some global constants in C# dll and use them instead of defines? e.g.
if(Globals.SomeConstant == SOMEVALUE)
// Do this
else
// Do smth else
然后当我要发送DLL时, strong>提前(可能在声明期间作为默认值) SOMEVALUE
到 Globals.SomeConstant
这个工作方式会怎样? (根据我需要的配置)。
Then when I want to ship the DLL I will in advance (probably as a default value during declaration) assign SOMEVALUE
to Globals.SomeConstant
- will this work this way? (Depending on which configuration I need).
我看到一些类似的问题,但他们不是关于DLL。
I saw some similar questions but they weren't about DLLs.
推荐答案
您可以像c ++中一样使用它
You can use it similarly as in c++
您可以在源代码中定义/符号。在visual studio中,这可以使用解决方案资源管理器 - 属性 - 构建条件编译符号
You can define / undefine them in your source code or as a conditional compilation symbol. In visual studio this can be done using Solution Explorer - Properties - Build - conditional compilation symbols
然而,现在人们倾向于使用配置文件为这些常数。这样,您不必重新编译源代码,也不必重新分发它来改变行为。
However, nowadays people tend to use a configuration file for these constants. This way, you don't have to recompile your source code nor redistribute it to change the behaviour.
最简单的方法是通过visual studio解决方案资源管理器 - 属性 - 设置
The most easy method is via visual studio solution explorer - properties - settings
您可以为大多数类型添加设置。布尔值最接近于#define。使用int可以给你两种以上的可能性。看到困难,如果你想能够使用几个值的TimeSpan或URI使用#define。
You can add settings for most types. Booleans come closest to #define. Using an int can give you more than two possibilities. See the difficulties if you wanted to be able to use several values for a TimeSpan or an URI using #define.
使用设置的好处是一个类是
The nice thing about using the settings is that a class is generated for you to easily access the settings.
另一种方法是直接使用 System.Configuration.ConfigurationManager 类。这为您提供了有关配置格式的更多自由。缺点是你必须自己将读取的值转换为合适的类型,包括处理错误,如果值不能被读取。
Another method is to read the config file directly using the System.Configuration.ConfigurationManager class. This gives you more freedom about the format of the configuration. The disadvantage is that you have to convert the read values into proper types yourself, inclusive handling errors if the value can't be read.
总结:配置文件的优点
Summarized: advantages of the config file method:
- b $ b
- 无需重新安装
- 只需更改需要更改的计算机上的配置文件
- / li>
- No need to change source files
- No need to recompile
- No need to re-install
- only change the config file on those machines that need the change
- improved type safety
这篇关于在C#DLL中替换#ifdefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!