#if, #else, #endif in C# source code
I've got a sample code from MSDN and I've found code syntax I've never seen before:
namespace Mvc3RemoteVal.Controllers
{
public class HomeController : Controller
{
IUserDB _repository;
#if InMemDB
public HomeController() : this(InMemoryDB.Instance) { }
#else
public HomeController() : this(new EF_UserRepository()) { }
#endif
public HomeController(IUserDB repository)
{
_repository = repository;
}
[...]
}
What are thos开发者_如何学JAVAe #if
, #else
, #endif
?
And what is #if InMemDB
?
What is InMemDB
? A variable?
Those are called preprocessor directives and exist since .NET 1.0. They allow you to define different compilation directives such as InMemDB
and the compiler will evaluate or not the block if this variable has been defined. The documentation of the #if directive provides a more in-depth overview.
In order to define a variable you could use the /define compiler option or use the Conditional compilation symbols in the Build tab of the properties of the project in Visual Studio:
These are not new features for Framework 4
this are features you can use for development stage and testing: you can declare:
#Define something
and then
#if something
all the code that is in that "if" will be executed. all the code that isn't, won't.
精彩评论