26

I think this is a simple question so I assume I'm missing something obvious. I don't really ever use preprocessor directives but I was looking at someone's code which did and thought it was something I should be familiar with.

So I looked at the msdn example here it has the code:

#define DEBUG
// ...
#if DEBUG
    Console.WriteLine("Debug version");
#endif

My two questions are:

  • in the example above why do they define DEBUG? I was under the impression that was set if you compile in debug v. release mode?
  • looking at the other example which has #define MYTEST and then writes to the console dependent on if it 'defined', but how does this differ from just using a variable? What am I missing here?
4

7 回答 7

18

我实际上建议使用条件属性而不是内联 #if 语句。

[Conditional("DEBUG")]
private void DeleteTempProcessFiles()
{
}

这不仅更简洁,而且更易于阅读,因为您最终不会在代码中包含#if、#else。这种风格在正常代码编辑和逻辑流程错误期间都不太容易出错。

于 2010-11-19T05:56:10.350 回答
9

通常,可选/条件编译符号将由构建脚本提供。#define除了非常调试的代码(如果你明白我的意思的话) ,这是非常罕见的。

重新使用变量;我经常使用这样的条件来处理必须在不同运行时(mono、cf、silverlight 等)上运行的代码。一个变量是不够的,因为无法针对错误的平台编译代码(缺少类型/方法等)。

在给出的示例中,我可能只会使用Debug.WriteLine; 因为这是用 装饰的,如果在构建时没有定义[Conditional("DEBUG")],所有对它的调用都会被自动删除。DEBUG

于 2010-11-19T05:41:10.963 回答
5

在上面的例子中,他们为什么要定义 DEBUG?如果您在调试 v. 发布模式下编译,我的印象是?

可能是因为它是示例代码。它旨在展示#ifdef和朋友如何工作。我不希望您在源文件中定义这样的符号,除非它是为了快速测试。

查看另一个具有“#define MYTEST”的示例,然后根据它是否“定义”写入控制台,但这与仅使用变量有何不同?我在这里想念什么?

如果 MYTEST 没有在编译时定义,编译器实际上不会在#ifand#endif块之间发出代码。因此,得到的 IL 会更小。

另外,请注意,这些不是C# 中的预处理器指令。

于 2010-11-19T05:32:08.197 回答
4

If you use variable all your code is compiled, when you use preprocessor directives only part of code included in executable/dll.

于 2010-11-19T05:28:29.067 回答
4

我想举一个我在项目中使用预处理器指令的例子。

我的程序在磁盘上创建了很多中间文件。仅当我的项目处于发布模式时,我才使用#DEBUG 指令删除这些文件,否则我保留这些文件,以便我们可以查看这些中间文件并确定里面发生了什么。

当我的应用程序在生产服务器上运行时,我以发布模式构建项目,以便在处理完成后删除这些文件。

#if (DEBUG==false)
    deleteTempFiles()
#endif
于 2010-11-19T05:45:52.883 回答
2

我有一些代码在使用 Mono 环境而不是 CLR 时需要不同的处理 - 因此我的一些模块中有 Mono 指令。我认为这是一个比调试更好的例子

于 2010-11-19T05:37:31.063 回答
1

我已经用它做了很多事情。我只在调试版本中需要的调试消息;清理临时文件;包括诊断功能或操作。

于 2014-03-14T15:22:25.280 回答