Sorry for the extreme newbie question, but I couldn't find the answer elsewhere and haven't actually ever done anything like this myself (go figure -- I guess that happens when your company uses t开发者_如何学运维he production environment for testing).
It would be nice if Visual Studio offered some mechanism for specifying that certain segments of code (e.g., logging) should only be included in the Debug build. Does this exist? I'm interested in methods for this in both C# and VB.NET, and on VS 2005, in case that matters.
There are several ways.
To mark a specific section of your code to only be included in Debug builds, you can do this in C#:
#if DEBUG
code that will only compile for Debug
#endif
If you want to avoid this, you can tag methods with an attribute:
[Conditional("DEBUG")]
public void Log(String message) { ... }
In this case, calls to this method will be automagically stripped out of your compiled code if you're not compiling for Debug. There are limitations to this. For instance, if you use ref
or out
parameters, or return values, then you can't use this.
You can read more about the #if directive here: C# Preprocessor Directives, and the attribute here: ConditionalAttribute.
We're doing this in AssemblyInfo.cs:
#if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
So that works for C#.
精彩评论