目录

VB.Net - 指令( Directives)

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

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

VB.Net中的编译器指令

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

  • #Const指令

  • #ExternalSource指令

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

  • #Region指令

#Const指令

该指令定义条件编译器常量。 该指令的语法是 -

#Const constname = expression

Where,

  • constname - 指定常量的名称。 需要。

  • expression - 它是文字或其他条件编译器常量,或者包括除Is之外的任何或所有算术或逻辑运算符的组合。

例如,

#Const state = "WEST BENGAL"

Example

以下代码演示了该指令的假设使用 -

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指令的参数是外部文件的路径,第一行的行号以及发生错误的行。

Example

以下代码演示了该指令的假设使用 -

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 ...然后......#Else Directives

该指令有条件地编译所选的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

Example

以下代码演示了该指令的假设使用 -

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
↑回到顶部↑
WIKI教程 @2018