VB.NET 的基礎資料類型(Int32、Double、Boolean、Date、Char、String 等)皆為結構體,擁有豐富的共用方法與屬性。熟練運用它們能讓程式碼更簡潔、更具物件導向風格,減少輔助函式的撰寫。
Dim i As Int32
Dim s As String
Dim ss() As String
Dim by As Byte
Dim d As Double
Dim b As Boolean
Dim da As Date
Dim c As Char
Dim cc() As Char
Int32/Byte)i = Int32.Parse("¥123", Globalization.NumberStyles.AllowCurrencySymbol) ' 123
i = Int32.MaxValue ' 2147483647
i = Int32.MinValue ' -2147483648
by = Byte.Parse("1") ' 1
Double)d = Double.PositiveInfinity ' 正無窮大
d = Double.Epsilon ' 4.94065645841247E-324 (最小正數)
Boolean)s = Boolean.TrueString ' "True"
Date)da = Date.MaxValue ' 9999-12-31 23:59:59
da = Date.MinValue ' 0001-01-01 00:00:00
da = Date.Now ' 當前日期時間
b = Date.IsLeapYear(2004) ' True
i = Date.DaysInMonth(2004, 5) ' 31
Char 共用方法)Char.IsControl(c) ' 控制字元
Char.IsDigit(c) ' 數字
Char.IsLetter(c) ' 字母
Char.IsLetterOrDigit(c) ' 字母或數字
Char.IsLower(c) ' 小寫
Char.IsNumber(c) ' 數字(含 Unicode 數字)
Char.IsPunctuation(c) ' 標點符號
Char.IsSeparator(c) ' 分隔符
Char.IsSurrogate(c) ' 代理對
Char.IsSymbol(c) ' 符號
Char.IsWhiteSpace(c) ' 空白字元
Char.IsUpper(c) ' 大寫
Char.ToLower(c)
Char.ToUpper(c)
String 實例方法)cc = s.ToCharArray() ' 轉字元陣列
sss = s.Split(","c) ' 分割字串
ss = s.Substring(5, 3) ' 取子字串(索引5起長度3)
ss = s.Trim() ' 移除首尾空白
TryParse 避免例外Dim result As Integer
If Int32.TryParse(input, result) Then
' 解析成功,result 為有效值
Else
' 解析失敗,不拋出例外
End If
善用基礎類型的共用方法(Parse/TryParse、IsXxx、MaxValue/MinValue)與實例方法,能大幅減少自訂驗證邏輯,提升程式碼可讀性與效能。建議開發時常查閱 MSDN 文件,發掘更多實用成員如 DateTime.TryParseExact、String.IsNullOrWhiteSpace 等。