简体   繁体   中英

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?

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. (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.

#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 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM