15

为什么不能#IF Not DEBUG像我在 VB.NET 中所期望的那样工作?

#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
4

1 回答 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!

这是有道理的......我没有定义调试,所以它显示“不是调试!”。

> 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,所以它显示“Not 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”——因为我无法使用任何其他值来获得该行为。使用 CodeDomProvider 的 ASP.NET必须以相同的方式定义它

看起来 CodeDomProvider 正在绊倒 VB.NET 的愚蠢的伪逻辑运算符

故事的道德启示?#If Not对于 VB.NET 来说不是一个好主意。


现在该源可用,我可以验证它确实按我的预期将其设置为等于 1:

if (options.IncludeDebugInformation) {
      sb.Append("/D:DEBUG=1 ");
      sb.Append("/debug+ ");
}
于 2009-10-02T20:41:06.700 回答