[英]c# Pre-processor directive scope
I'm looking to use: 我想用:
#define
and 和
#if
to allow me to simulate potentially absent hardware during unit tests. 允许我在单元测试期间模拟可能缺少的硬件。 What are the rules for using the
#define
statements? 使用
#define
语句有哪些规则?
ie what is its default scope? 即它的默认范围是什么? can I change the scope of the directive?
我可以改变指令的范围吗?
As Chris said, the scope of #define is just the file. 正如克里斯所说,#define的范围只是文件。 (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't!
(值得注意的是,这与“类”不同 - 如果你有一个部分类型,它可能包含两个文件,其中一个有符号定义,其中一个没有!
You can also define a symbol project-wide, but that's done with project properties or a compiler switch rather than being specified in source code. 您还可以在项目范围内定义符号,但这是使用项目属性或编译器开关完成的,而不是在源代码中指定。
从MSDN ,其范围是文件
虽然你不能沿着模拟物体的路线走下去 ,ala Mock.Rhinos ?
Yes as Chris mentioned, its scope is the whole file. 是的,正如克里斯提到的,它的范围是整个文件。 You can use the defined keyword anywhere in the file.
您可以在文件中的任何位置使用已定义的关键字。
ie; 即;
#define something
... some code ...
and in any method, class body or namespace, you could use it like; 在任何方法,类主体或命名空间,你可以使用它;
#if something
... some conditional code ...
#else
... otherwise ...
#endif
The scope of a preprocessor directive starts when it's parsed from the source and persists until directed otherwise. 预处理程序指令的范围从它从源解析后开始,并持续到其他方向。 If you do want to limit the scope of a preprocessor directive, use the "undef" declaration it switch off when your done with it.
如果您确实想限制预处理程序指令的范围,请使用它完成时关闭的“undef”声明。
#include <iostream>
using namespace std ;
int main()
{
#define someString "this is a string"
cout<<someString<<endl;
#undef someString // scope of someString ends here
cout<<someString<<endl; //this causes a compile error
return 0 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.