编译C#条件编译符号的时候检查(见例)? [英] Compile time checking of conditional compilation symbols in C# (see example)?

查看:156
本文介绍了编译C#条件编译符号的时候检查(见例)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++,你可以这样做:

In C/C++ you can do something like:

#define IN_USE      (1)
#define NOT_IN_USE (-1)

#define USING( system ) ( 1 / (system) == 1 / IN_USE )

和则:

#define MY_SYSTEM  IN_USE

#if USING( MY_SYSTEM )
    <my_system impl>
#endif

这样的设置方式:


  • 所有条件编译符号已被定义要么IN_USE或NOT_IN_USE。

  • All conditional compilation symbols have to be defined either IN_USE or NOT_IN_USE.

我可以把他们都在一个头文件(或一对夫妇),并轻松地将其开/关和看到什么条件编译符号有。

I can put them all in a single header file (or a couple) and easily turn them on/off and see what conditional compilation symbols there are.

像#A错字如果使用(MYSYSTEM)由编译器捕获因格由0,而不是默默编译出来。

A typo like #if USING( MYSYSTEM ) is caught by the compiler due to div by 0 rather than silently compiling it out.

时有可能做到这一点在C#中?有另一种最佳实践的方式来达到同样的效果?

Is it possible to do this in C#? Is there another best practices way to achieve the same effect?

我在C#中实现您可以通过在项目设置中设定了他们,并用#如果做条件编译,但我讨厌的事实的东西并不一定要明确地定义。这是在项目设置你有调试和跟踪复选框的原因。如果他们不存在,你不知道,你可以打开它们。

I realize in C# you can do conditional compilation by setting them in the project settings and using #if, but I dislike the fact that something doesn't have to be explicitly undefined. This is the reason in the project settings you have the "DEBUG" and "TRACE" checkboxes. If they weren't there, you'd have no idea you could turn them on.

推荐答案

C#不允许预处理给予符号的的,但你可以使用的#define 的#ifdef /#ENDIF 。典型的预处理器符号以
项目属性,而不是在代码中的一个项目的水平确实定义。

C# doesn't allow preprocessor symbols to be given values, but you can use #define and #ifdef/#endif. Typically preprocessor symbols are actually defined at a project level within the project properties rather than in code.

您可能也有兴趣的 ConditionalAttribute 允许通话的装饰来与它的方法如果相关的预处理器符号不存在被省略。 (该方法本身依然建,它只是决定调用是否实际发生或没有。)

You may also be interested in ConditionalAttribute which allows calls to methods decorated with it to be omitted if the relevant preprocessor symbol is not present. (The method itself is still built; it just determines whether calls actually take place or not.)

如果你想实际恒定的值,可以使用常量静态只读字段来代替。

If you want actual constant values, you can use const and static readonly fields instead.

这篇关于编译C#条件编译符号的时候检查(见例)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆