何時使用型別推斷
基本上,只要有可能,你就可以使用型別推斷。
但是,在組合 Option Infer Off
和 Option Strict Off
時要小心,因為這會導致不希望的執行時行為:
Dim someVar = 5
someVar.GetType.ToString() '--> System.Int32
someVar = "abc"
someVar.GetType.ToString() '--> System.String
匿名型別
匿名型別只能使用 Option Infer On
宣告。
在處理 LINQ 時經常使用它們 :
Dim countryCodes = New List(Of String)
countryCodes.Add("en-US")
countryCodes.Add("en-GB")
countryCodes.Add("de-DE")
countryCodes.Add("de-AT")
Dim q = From code In countryCodes
Let split = code.Split("-"c)
Select New With {.Language = split(0), .Country = split(1)}
-
選項推斷
編譯器將識別匿名型別: -
選項推斷關閉
編譯器將丟擲錯誤(使用Option Strict On
)
或將q
視為型別object
(使用Option Strict Off
)。
這兩種情況都會產生不能使用匿名型別的結果。
雙打/小數
預設情況下,帶小數位的數字變數將被視為 Double
:
Dim aNumber = 44.11 '--> Will be treated as type `Double` by the compiler
如果需要像 Decimal
這樣的其他型別,則需要標記初始化變數的值:
Dim mDecimal = 47.11D '--> Will be treated as type `Decimal` by the compiler