VB.NET预处理器指令

Mar*_*ett 14 vb.net preprocessor

为什么不能#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
Run Code Online (Sandbox Code Playgroud)

但是,手动设置const会:

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

#If Not D Then
   Console.WriteLine("Not D")
#End If
' Outputs: D
Run Code Online (Sandbox Code Playgroud)

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

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

#if !DEBUG
    Console.WriteLine("Not Debug");
#endif
// Outputs: Debug
Run Code Online (Sandbox Code Playgroud)

Mar*_*ett 10

事实证明,并不是所有的VB.NET都被破坏了 - 只是CodeDomProvider(ASP.NET和Snippet编译器都使用它).

给出一个简单的源文件:

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
Run Code Online (Sandbox Code Playgroud)

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

> vbc.exe default.vb /out:out.exe
> out.exe
  Not Debug!
Run Code Online (Sandbox Code Playgroud)

这是有道理的......我没有定义DEBUG,所以它显示"Not Debug!".

> vbc.exe default.vb /out:out.exe /debug:full
> out.exe
  Not Debug!
Run Code Online (Sandbox Code Playgroud)

并且,使用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!
Run Code Online (Sandbox Code Playgroud)

好的,再次 - 这是有道理的.我没有定义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!
Run Code Online (Sandbox Code Playgroud)

嗯......我没有定义DEBUG,但也许它为我定义了它?但如果确实如此,它必须将其定义为"1" - 因为我不能用任何其他值获得该行为.使用CodeDomProvider的ASP.NET 必须以相同的方式定义它.

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

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


现在该源可用,我可以验证它确实将其设置为等于1,如我所料:

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