VB.Net - 指令

VB.Net编译器指令给出了编译器在实际编译开始之前预处理信息的指令.所有这些指令都以#开头,并且在行上的指令之前只能出现空白字符.这些指令不是语句.

VB.Net编译器没有单独的预处理器;但是,指令的处理就像有一个指令一样.在VB.Net中,编译器指令用于帮助进行条件编译.与C和C ++指令不同,它们不用于创建宏.

VB.Net中的编译器指令

VB.Net提供以下一组编译器指令 :

  • #Const指令

  • #ExternalSource指令

  • #If ...然后......#Else Directives

  • #Region指令

#Const指令

此指令定义条件编译器常量.该指令的语法是 :

#Const constname = expression

其中,

  • constname : 指定常量的名称.必需.

  • 表达式 : 它是文字或其他条件编译器常量,或包含任何或所有算术或逻辑运算符的组合,除了.

例如,

#Const state = "WEST BENGAL"

示例

以下代码演示假设使用指令 :

Module mydirectives
#Const age = True
Sub Main()
   #If age Then
      Console.WriteLine("You are welcome to the Robotics Club")
   #End If
   Console.ReadKey()
End Sub
End Module

当编译并执行上述代码时,它会产生以下结果 :

You are welcome to the Robotics Club

#ExternalSource指令

该指令用于指示源代码的特定行与外部文本之间的映射来源.它仅由编译器使用,调试器对代码编译没有影响.

该指令允许将外部代码文件中的外部代码包含在源代码文件中.

该指令的语法是 :

#ExternalSource( StringLiteral , IntLiteral )
   [ LogicalLine ]
#End ExternalSource

#ExternalSource指令的参数是外部文件的路径,第一行的行号以及发生错误的行.

示例

以下代码演示假设使用该指令 :

Module mydirectives
   Public Class ExternalSourceTester

      Sub TestExternalSource()

      #ExternalSource("c:\vbprogs\directives.vb", 5)
         Console.WriteLine("This is External Code. ")
      #End ExternalSource

      End Sub
   End Class

   Sub Main()
      Dim t As New ExternalSourceTester()
      t.TestExternalSource()
      Console.WriteLine("In Main.")
      Console.ReadKey()

   End Sub

编译并执行上述代码时,会产生以下结果 :

This is External Code.
In Main.

#If ... Then ...#Else Directives

this指令有条件地编译所选的Visual Basic代码块.

该指令的语法是 :

#If expression Then
   statements
[ #ElseIf expression Then
   [ statements ]
...
#ElseIf expression Then
   [ statements ] ]
[ #Else
   [ statements ] ]
#End If

例如,

#Const TargetOS = "Linux"
#If TargetOS = "Windows 7" Then
   ' Windows 7 specific code
#ElseIf TargetOS = "WinXP" Then
   ' Windows XP specific code
#Else
   ' Code for other OS
#End if

示例

以下代码演示假设使用该指令 :

Module mydirectives
#Const classCode = 8

   Sub Main()
   #If classCode = 7 Then
      Console.WriteLine("Exam Questions for Class VII")
   #ElseIf classCode = 8 Then
      Console.WriteLine("Exam Questions for Class VIII")
   #Else
      Console.WriteLine("Exam Questions for Higher Classes")
   #End If
      Console.ReadKey()

   End Sub
End Module

当...的时候上面的代码被编译和执行,它产生以下结果 :

Exam Questions for Class VIII

#Region指令

此指令有助于折叠和隐藏Visual Basic文件中的代码部分.

语法对于这个指令是 :

#Region "identifier_string" 
#End Region

例如,

#Region "StatsFunctions" 
   ' Insert code for the Statistical functions here.
#End Region