Conditional compilation symbols not being defined

2019-05-03 06:44发布

问题:

I am having trouble getting Visual Studio to behave as I would expect it. I created 2 configuration profiles. One has the symbol FOO defined and the other has the symbol BAR defined. And I have this code:

static class MyClass{
#if FOO
  public static string const MyData="foo defined";
#endif
#if BAR /*yes, I know #elif would work here too.. just trying to be simple*/
  public static string const MyData="bar defined";
#endif
}

and then later in another file I have

 if(MyClass.MyData=="foo defined").....

Well, in my application, I get an error that MyClass.MyData is not defined.

Also, if I have it on the FOO profile and type in something like #error test after the #if FOO then it will have a build error, but if I remove that it will build just fine and when I go to run it I'll get a compilation error that MyClass does not contain a definition for MyData. Also, this is an ASP.Net Web Application.

Can someone help me figure out how to use conditional compilation? It acts as if Visual Studio compiles it properly with the compilation symbols, but whenever the ASP.Net webserver executes it, it recompiles it without any symbols... But that just doesn't make any sense why it would do that..

Edit: It doesn't matter if I use the FOO or BAR profile, neither of them seem to define the MyData symbol as they should.

EDIT2:

Ok, this is important for reproducing!!! Create a new App_Code folder in your solution and then add a .cs file there and then add MyClass to it. This will reproduce the bug working in a blank project. I've actually simplified it down to just

#if !(FOO || BAR)
  #error neither foo or bar defined
#endif

It seems like Visual Studio does not set conditional compile symbols for regular .cs files inside of App_Code

回答1:

Since ASP.NET compiles your code outside of your development environment, it uses its own build configuration. You must set the conditional compilation symbol in your web.config, see link here: Conditional Compilation in ASP.NET 2.0