Select Case
語句允許對一個變數進行相對於值列表的測試。每個值都被稱為一個情況(Case
),並為每個選擇情況檢查被開啟/接通變數。
VB.Net中Select Case
語句的語法如下:
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
其中,
Boolean
, Byte
, Char
, Date
, Double
, Decimal
, Integer
, Long
, Object
, SByte
, Short
, Single
, String
, UInteger
, ULong
和 UShort
。Case expressionlist
中的任何子句,則執行該語句。Case
語句的表示式列表中的任何子句,則Case Else
後面的語句將會執行。流程圖
Module decisions
Sub Main()
'local variable definition '
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
執行上面範例程式碼,得到以下結果 -
Well done
Your grade is B