如何轻松地从编译中排除某些代码行?
我正在开发的软件项目中散布着许多行代码,这些代码是为了调试和实用目的而编写的。在编译代码之前,我想要一种方法来选择是否应将这些代码块包含在我的编译中(不需要导航注释掉的代码)。我该怎么做?
我正在使用 C# 进行编程并使用 Microsoft Visual Studio 2010。
Scattered throughout a software project I am working on are many lines of code that were written for debugging and utility purposes. Before I compile my code, I want a way to select whether or not these blocks of code should be included into my compile (something that won't require navigating the code commenting out). How can I do this?
I'm programming in c# and using Microsoft Visual Studio 2010.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
将属性
[Conditional("DEBUG")]
添加到您只想在调试版本中执行的方法上。请参阅此处了解更多详细信息。Add the attribute
[Conditional("DEBUG")]
onto methods you only want to have execute in your debug build. See here for more detailed information.我建议将您的块包含在
#ifdef SOMETHING
和#endif
中,然后当您想要包含该块时在项目设置中定义SOMETHING
在你的编译中。I would suggest enclosing your blocks in
#ifdef SOMETHING
and#endif
, and then definingSOMETHING
in your project settings when you want to include that block in your compile.您需要预处理器指令或条件编译语句。您可以在此处阅读有关它们的信息。
该链接的一个示例:
仅当在代码顶部定义了 TEST 时才会编译代码。许多开发人员使用#define DEBUG,这样他们就可以启用调试代码,然后只需更改顶部的一行即可再次删除它。
You need preprocessor directives, or conditional compile statements. You can read about them here.
An example from that link:
The code is only compiled if TEST is defined at the top of the code. A lot of developers use #define DEBUG so they can enable debugging code and remove it again just by altering that one line at the top.
考虑使用 Debug 类 来有条件地记录、断言等等。这样做有很多好处。您可以选择在运行时记录(或不记录)。它们限制您(大部分)采取不会改变行为的行动,解决了@STW 的一些(有效)担忧。它们允许使用第三方日志记录工具。
Consider using the Debug class to conditionally log, assert, etc. There are many advantages to this. You can choose to log (or not) at runtime. They limit you to (mostly) non-behavior-changing actions, addressing some of @STW's (valid) concern. They allow the use of third-party logging tools.
如果它们用于调试,那么唯一可接受的解决方案是用以下内容包围此类代码:
这可确保在调试模式下编译时包含该代码,但在发布模式下排除该代码。
If they are for debugging, then the only acceptable solution is to surround such code with:
This ensures that the code is included when you compile in debug mode but excluded in release mode.
您可以使用 预处理器指令 w/ < a href="http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx" rel="nofollow noreferrer">#if
You can use preprocessor directives w/ #if
您可能需要考虑将这些调试功能完全移出类 - 让您的类在“调试”和“发布”模式之间“改变形状”可能会非常令人头痛,并且很难诊断问题。
您可以考虑创建一个单独的“调试”程序集,其中包含所有调试助手 - 然后只需确保您可以将其从解决方案中排除并在没有它的情况下成功构建。
You may want to consider moving these debugging functions out of the classes entirely--having your classes "change shape" between Debug and Release mode can be a real headache and can be difficult to diagnose problems.
You could consider creating a seperate "Debug" assembly which contains all your debugging helpers--then just make sure you can exclude it from the solution and build successfully without it.