VB.NET 预处理指令

15

为什么在VB.NET中,#IF Not DEBUG不按照我期望的方式工作?

#If DEBUG Then
   Console.WriteLine("Debug")
#End If

#If Not DEBUG Then
   Console.WriteLine("Not Debug")
#End If

#If DEBUG = False Then
   Console.WriteLine("Not Debug")
#End If
' Outputs: Debug, Not Debug

然而,手动设置的const则可以:

#Const D = True
#If D Then
   Console.WriteLine("D")
#End If

#If Not D Then
   Console.WriteLine("Not D")
#End If
' Outputs: D

当然,C#也有预期的行为:

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

#if !DEBUG
    Console.WriteLine("Not Debug");
#endif
// Outputs: Debug

对我来说运行得很好,第一个在调试模式下只显示“Debug”,在发布模式下则显示“Not Debug”和“Not Debug”。你确定你的项目设置中没有什么奇怪的问题吗? - Steven Robbins
嗯...我已经尝试过在现有的ASP.NET项目中使用VS2008,还有Snippet Compiler。我会尝试创建一个新的控制台项目,看看会发生什么。 - Mark Brackett
这是我尝试的新控制台应用程序。 - Steven Robbins
啊,一个新的控制台应用程序按预期工作。现在我真的很困惑.... - Mark Brackett
奇怪。确定没有人在项目的预处理器设置中搞过什么吗? - Steven Robbins
这是一个ASP.NET网站项目,因此它是按需编译的。Snippet Compiler也受到影响...我能想到的唯一可能是与Microsoft.VisualBasic.VBCodeProvider有关的问题(据我所知,ASP.NET和Snippet Compiler都使用它而不是vbc.exe)。进一步调查正在进行中... - Mark Brackett
1个回答

10

事实证明,并非VB.NET全部有问题,只有CodeDomProvider存在问题(ASP.NET和Snippet Compiler都使用该提供程序)。

给定一个简单的源文件:

Imports System
Public Module Module1
    Sub Main()
       #If DEBUG Then
          Console.WriteLine("Debug!")
       #End If

       #If Not DEBUG Then
          Console.WriteLine("Not Debug!")
       #End If
    End Sub
End Module

使用vbc.exe版本9.0.30729.1 (.NET FX 3.5)进行编译:

> vbc.exe default.vb /out:out.exe
> out.exe
  Not Debug!

这很有道理...我没有定义 DEBUG,所以它显示“非调试版本!”。

> vbc.exe default.vb /out:out.exe /debug:full
> out.exe
  Not Debug!

同时,使用CodeDomProvider:

Using p = CodeDomProvider.CreateProvider("VisualBasic")
   Dim params As New CompilerParameters() With { _
      .GenerateExecutable = True, _
      .OutputAssembly = "out.exe" _
   }
   p.CompileAssemblyFromFile(params, "Default.vb")
End Using

> out.exe
Not Debug!

好的,再解释一下 - 那很有道理。我没有定义 DEBUG,所以显示“非调试”。但是,如果我包含调试符号呢?

Using p = CodeDomProvider.CreateProvider("VisualBasic")
   Dim params As New CompilerParameters() With { _
      .IncludeDebugInformation = True, _
      .GenerateExecutable = True, _
      .OutputAssembly = "C:\Users\brackett\Desktop\out.exe" _
   }
   p.CompileAssemblyFromFile(params, "Default.vb")
End Using

> out.exe
Debug!
Not Debug!

嗯...我没有定义DEBUG,但也许它为我定义了?但是如果它这样做了,它肯定将其定义为"1" - 因为我无法通过任何其他值来获取该行为。ASP.NET 使用 CodeDomProvider,必须以相同的方式进行定义

看起来CodeDomProvider在VB.NET的愚蠢的伪逻辑运算符上出问题了。

故事的寓意?对于VB.NET来说,#If Not不是一个好主意。


现在该源代码已经可用,我可以验证它实际上将其设置为1,就像我所预期的那样:

if (options.IncludeDebugInformation) {
      sb.Append("/D:DEBUG=1 ");
      sb.Append("/debug+ ");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接