VB.Net - 指令



VB.Net 編譯器指令向編譯器提供指令,以便在實際編譯開始之前預處理資訊。所有這些指令都以 # 開頭,並且在一行指令之前只能出現空格字元。這些指令不是語句。

VB.Net 編譯器沒有單獨的預處理器;但是,指令的處理方式就像有一個預處理器一樣。在 VB.Net 中,編譯器指令用於幫助進行條件編譯。與 C 和 C++ 指令不同,它們不用於建立宏。

VB.Net 中的編譯器指令

VB.Net 提供以下編譯器指令集:

  • #Const 指令

  • #ExternalSource 指令

  • #If...Then...#Else 指令

  • #Region 指令

#Const 指令

此指令定義條件編譯常量。此指令的語法如下:

#Const constname = expression

其中,

  • constname − 指定常量的名稱。必填。

  • expression − 它可以是文字、其他條件編譯常量,或包含任何或所有算術或邏輯運算子(除了 Is)的組合。

例如,

#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 指令

此指令有條件地編譯 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
廣告

© . All rights reserved.