How to use #define from another file?

2019-06-18 04:01发布

For example:

define.cs

#define FOO

form1.cs

#if FOO 
  MessageBox.Show("foo is set!");
#else 
  MessageBox.Show("foo is not set!");
#endif

the define.cs are included on same projet that form1.cs but the above condition give: foo is not!

5条回答
戒情不戒烟
2楼-- · 2019-06-18 04:31

According to this MSDN page,

The scope of a symbol created with #define is the file in which it was defined.

查看更多
Animai°情兽
3楼-- · 2019-06-18 04:35

You Can't, The scope of a symbol created with #define is the file in which it was defined.

查看更多
Bombasti
4楼-- · 2019-06-18 04:37

You can't, but what you can do is move the define to the project configuration so that all files in the project can see the definition.

See the instructions in How to define a constant globally in C# (like DEBUG).

查看更多
祖国的老花朵
5楼-- · 2019-06-18 04:39

As others have said, a #define is scoped to a single file.

However, you can define preprocessor variables that are scoped to the entire assembly. To do this you just have to go into the "Build" section of the project's settings and put it in the "Conditional compilation symbols" section. (This is just an easier way to manage the /define compiler switch.) That approach has the added advantage of also letting you define different sets of symbols for different build configurations.

查看更多
虎瘦雄心在
6楼-- · 2019-06-18 04:54

In C#, scope of #define is only limited to file in which it is declared.
To define a symbol visible in all files, one way is to Project->Properties->Build->Conditional Compilation Symbols and specify the symbol "FOO" there.

查看更多
登录 后发表回答