VB.NET 教程_02_常见对象
VB.Net - 字符串
?
在VB.Net中,可以使用字符串作為字符數組,但是更常見的做法是使用String關鍵字聲明一個字符串變量。 string關鍵字是System.String類的別名。
創建一個字符串對象
您可以使用以下方法之一創建字符串對象:
-
By assigning a string literal to a String variable?通過指定一個字符串給一個字符串變量?
-
By using a String class constructor?通過使用String類構造函數
-
By using the string concatenation operator (+)?通過使用字符串連接運算符(+)?
-
By retrieving a property or calling a method that returns a string?通過檢索屬性或調用返回字符串的方法
-
By calling a formatting method to convert a value or object to its string representation
通過調用格式化方法將值或對象轉換為其字符串表示形式
?
下面的例子說明了這一點:
Module stringsSub Main()Dim fname, lname, fullname, greetings As Stringfname = "Rowan"lname = "Atkinson"fullname = fname + " " + lnameConsole.WriteLine("Full Name: {0}", fullname)'by using string constructorDim letters As Char() = {"H", "e", "l", "l", "o"}greetings = New String(letters)Console.WriteLine("Greetings: {0}", greetings)'methods returning StringDim sarray() As String = {"Hello", "From", "Tutorials", "Point"}Dim message As String = String.Join(" ", sarray)Console.WriteLine("Message: {0}", message)'formatting method to convert a value Dim waiting As DateTime = New DateTime(2012, 12, 12, 17, 58, 1)Dim chat As String = String.Format("Message sent at {0:t} on {0:D}", waiting)Console.WriteLine("Message: {0}", chat)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Full Name: Rowan Atkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, December 12, 2012?
String類的屬性
String類有以下兩個屬性:
| 1 | Chars 獲取當前String對象中指定位置的Char對象。 |
| 2 | Length 獲取當前String對象中的字符數。 |
?
String類的方法
String類有許多方法可以幫助你處理字符串對象。 下表提供了一些最常用的方法:
| 1 | Public Shared Function Compare ( strA As String, strB As String ) As Integer 比較兩個指定的字符串對象,并返回一個整數,指示它們在排序順序中的相對位置。 |
| 2 | Public Shared Function Compare ( strA As String, strB As String, ignoreCase As Boolean ) As Integer 比較兩個指定的字符串對象,并返回一個整數,指示它們在排序順序中的相對位置。 但是,如果布爾參數為true,它將忽略大小寫。 |
| 3 | Public Shared Function Concat ( str0 As String, str1 As String ) As String 連接兩個字符串對象。 |
| 4 | Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As String 連接三個字符串對象。 |
| 5 | Public Shared Function Concat ( str0 As String, str1 As String, str2 As String, str3 As String ) As String公共共享函數Concat(str0 As String,str1 As String,str2 As String,str3 As String)As String 連接四個字符串對象。 |
| 6 | Public Function Contains ( value As String ) As Boolean 返回一個值,指示指定的字符串對象是否出現在此字符串中。 |
| 7 | Public Shared Function Copy ( str As String ) As String 創建與指定字符串具有相同值的新String對象。 |
| 8 | pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Integer ) 將指定數量的字符從字符串對象的指定位置復制到Unicode字符數組中的指定位置。 |
| 9 | Public Function EndsWith ( value As String ) As Boolean 確定字符串對象的結尾是否與指定的字符串匹配。 |
| 10 | Public Function Equals ( value As String ) As Boolean 確定當前字符串對象,并指定字符串對象是否具有相同的值。 |
| 11 | Public Shared Function Equals ( a As String, b As String ) As Boolean 確定兩個指定字符串對象是否具有相同的值。 |
| 12 | Public Shared Function Format ( format As String, arg0 As Object ) As String 將指定字符串中的一個或多個格式項替換為指定對象的字符串表示形式。 |
| 13 | Public Function IndexOf ( value As Char ) As Integer 返回當前字符串中指定Unicode字符第一次出現的從零開始的索引。 |
| 14 | Public Function IndexOf ( value As String ) As Integer 返回此實例中指定字符串第一次出現的從零開始的索引。 |
| 15 | Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer 返回此字符串中指定Unicode字符第一次出現的從零開始的索引,從指定的字符位置開始搜索。 |
| 16 | Public Function IndexOf ( value As String, startIndex As Integer ) As Integer 返回此實例中指定字符串第一次出現的從零開始的索引,開始在指定的字符位置搜索。 |
| 17 | Public Function IndexOfAny ( anyOf As Char() ) As Integer 返回在指定的Unicode字符數組中的任何字符的此實例中第一次出現的從零開始的索引。 |
| 18 | Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer 返回在指定的Unicode字符數組中的任意字符的此實例中第一次出現的從零開始的索引,開始在指定的字符位置搜索。 |
| 19 | Public Function Insert ( startIndex As Integer, value As String ) As String 返回一個新字符串,其中指定的字符串插入到當前字符串對象中指定的索引位置。 |
| 20 | Public Shared Function IsNullOrEmpty ( value As String ) As Boolean 指示指定的字符串是空還是空字符串。 |
| 21 | Public Shared Function Join ( separator As String, ParamArray value As String() ) As String 連接字符串數組的所有元素,使用每個元素之間指定的分隔符。 |
| 22 | Public Shared Function Join ( separator As String, value As String(), startIndex As Integer, count As Integer ) As String 使用每個元素之間指定的分隔符連接字符串數組的指定元素。 |
| 23 | Public Function LastIndexOf ( value As Char ) As Integer 返回當前字符串對象中指定Unicode字符的最后一次出現的從零開始的索引位置。 |
| 24 | Public Function LastIndexOf ( value As String ) As Integer 返回當前字符串對象中指定字符串的最后一次出現的從零開始的索引位置。 |
| 25 | Public Function Remove ( startIndex As Integer )As String 刪除當前實例中的所有字符,從指定位置開始,并繼續到最后一個位置,并返回字符串。 |
| 26 | Public Function Remove ( startIndex As Integer, count As Integer ) As String 從指定位置開始刪除當前字符串中指定數量的字符,并返回字符串。 |
| 27 | Public Function Replace ( oldChar As Char, newChar As Char ) As String 用指定的Unicode字符替換當前字符串對象中指定Unicode字符的所有出現,并返回新字符串。 |
| 28 | Public Function Replace ( oldValue As String, newValue As String ) As String 將當前字符串對象中指定字符串的所有出現替換為指定的字符串,并返回新字符串。 |
| 29 | Public Function Split ( ParamArray separator As Char() ) As String() 返回一個字符串數組,其中包含當前字符串對象中的子字符串,由指定的Unicode字符數組的元素分隔。 |
| 30 | Public Function Split ( separator As Char(), count As Integer ) As String() 返回一個字符串數組,其中包含當前字符串對象中的子字符串,由指定的Unicode字符數組的元素分隔。 int參數指定要返回的子字符串的最大數目。 |
| 31 | Public Function StartsWith ( value As String ) As Boolean 確定此字符串實例的開頭是否與指定的字符串匹配。 |
| 32 | Public Function ToCharArray As Char() 返回包含當前字符串對象中所有字符的Unicode字符數組。 |
| 33 | Public Function ToCharArray ( startIndex As Integer, length As Integer ) As Char() 返回一個Unicode字符數組,其中包含當前字符串對象中的所有字符,從指定的索引開始,直到指定的長度。 |
| 34 | Public Function ToLower As String 返回此字符串的轉換為小寫的副本。 |
| 35 | Public Function ToUpper As String 返回此字符串的轉換為大寫的副本。 |
| 36 | Public Function Trim As String 從當前String對象中刪除所有前導和尾部空格字符。 |
上面列出的方法并不詳盡,請訪問MSDN庫獲取完整的方法列表和String類構造函數。
?
例子:
下面的例子說明了上述一些方法:
?
比較字符串:
Module stringsSub Main()Dim str1, str2 As Stringstr1 = "This is test"str2 = "This is text"If (String.Compare(str1, str2) = 0) ThenConsole.WriteLine(str1 + " and " + str2 +" are equal.")ElseConsole.WriteLine(str1 + " and " + str2 +" are not equal.")End IfConsole.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
This is test and This is text are not equal.?
字符串包含字符串:
Module stringsSub Main()Dim str1 As Stringstr1 = "This is test"If (str1.Contains("test")) ThenConsole.WriteLine("The sequence 'test' was found.")End IfConsole.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
The sequence 'test' was found.?
獲取的子字符串:
Module stringsSub Main()Dim str As Stringstr = "Last night I dreamt of San Pedro"Console.WriteLine(str)Dim substr As String = str.Substring(23)Console.WriteLine(substr)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Last night I dreamt of San Pedro San Pedro.?
加入字符串:
Module stringsSub Main()Dim strarray As String() = {"Down the way where the nights are gay","And the sun shines daily on the mountain top","I took a trip on a sailing ship","And when I reached Jamaica","I made a stop"}Dim str As String = String.Join(vbCrLf, strarray)Console.WriteLine(str)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop?
?
?
VB.Net - 日期和時間
?
你寫的大部分軟件都需要實現某種形式的日期功能,返回當前日期和時間。日期是日常生活的一部分,使用它能讓工作變得輕松,不需要太多思考。?VB.Net還提供了強大的日期算術工具,使操作日期變得容易。
?
日期數據類型包含日期值,時間值或日期和時間值。 Date的默認值為0001年1月1日的0:00:00(午夜)。等效的.NET數據類型為System.DateTime。
?
DateTime?結構表示即時時間,通常表示為日期和時間的一天
'Declaration <SerializableAttribute> _ Public Structure DateTime _Implements IComparable, IFormattable, IConvertible, ISerializable, IComparable(Of DateTime), IEquatable(Of DateTime)您還可以從DateAndTime類獲取當前日期和時間。
?
DateAndTime模塊包含日期和時間操作中使用的過程和屬性。
'Declaration <StandardModuleAttribute> _ Public NotInheritable Class DateAndTime| 注意: DateTime結構和DateAndTime模塊都包含諸如Now和Today之類的屬性,因此初學者經常會感到困惑。 DateAndTime類屬于Microsoft.VisualBasic命名空間,DateTime結構屬于System命名空間。
|
DateTime結構的屬性和方法
下表列出了一些DateTime結構的常用屬性?:
?
| 1 | Date | Gets the date component of this instance. 獲取此實例的日期組件。 |
| 2 | Day | Gets the day of the month represented by this instance. 獲取此實例所代表的月份中的某一天。 |
| 3 | DayOfWeek | Gets the day of the week represented by this instance. 獲取此實例表示的星期幾。 |
| 4 | DayOfYear | Gets the day of the year represented by this instance. 獲取此實例表示的一年中的某一天。 |
| 5 | Hour | Gets the hour component of the date represented by this instance. 獲取此實例表示的日期的小時組件。 |
| 6 | Kind | Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.G 獲取一個值,該值指示此實例表示的時間是基于本地時間,協調世界時間(UTC)還是兩者都不是。 |
| 7 | Millisecond | Gets the milliseconds component of the date represented by this instance. 獲取此實例表示的日期的毫秒組件。 |
| 8 | Minute | Gets the minute component of the date represented by this instance. 獲取此實例表示的日期的分鐘分量。 |
| 9 | Month | Gets the month component of the date represented by this instance. 獲取此實例表示的日期的月份。 |
| 10 | Now | Gets a?DateTime?object that is set to the current date and time on this computer, expressed as the local time. 獲取在此計算機上設置為當前日期和時間的DateTime對象,以本地時間表示。 |
| 11 | Second | Gets the seconds component of the date represented by this instance. 獲取此實例表示的日期的秒組件。 |
| 12 | Ticks | Gets the number of ticks that represent the date and time of this instance. 獲取表示此實例的日期和時間的刻度數。 |
| 13 | TimeOfDay | Gets the time of day for this instance. 獲取此實例的時間。 |
| 14 | Today | Gets the current date. 獲取當前日期。 |
| 15 | UtcNow | Gets a?DateTime?object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC). 獲取設置為此計算機上當前日期和時間的DateTime對象,以協調世界時(UTC)表示。 |
| 16 | Year | Gets the year component of the date represented by this instance. 獲取此實例表示的日期的年份組件。 |
?
?
下表列出了DateTime結構的一些常用方法:
| 1 | Public Function Add (value As TimeSpan) As DateTime 返回一個新的DateTime,將指定的TimeSpan的值添加到此實例的值。 |
| 2 | Public Function AddDays ( value As Double) As DateTime 返回一個新的DateTime,該值將指定的天數添加到此實例的值中。 |
| 3 | Public Function AddHours (value As Double) As DateTime 返回一個新的DateTime,該值將指定的小時數添加到此實例的值中。 |
| 4 | Public Function AddMinutes (value As Double) As DateTime 返回一個新的DateTime,將指定的分鐘數添加到此實例的值。 |
| 5 | Public Function AddMonths (months As Integer) As DateTime 返回一個新的DateTime,將指定的月數添加到此實例的值。 |
| 6 | Public Function AddSeconds (value As Double) As DateTime 返回一個新的DateTime,將指定的秒數添加到此實例的值。 |
| 7 | Public Function AddYears (value As Integer ) As DateTime 返回一個新的DateTime,將指定的年數添加到此實例的值。 |
| 8 | Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer 比較兩個DateTime實例,并返回一個整數,指示第一個實例是早于,與第二個實例相同還是晚于第二個實例。 |
| 9 | Public Function CompareTo (value As DateTime) As Integer 將此實例的值與指定的DateTime值進行比較,并返回一個整數,指示此實例是早于,等于還是晚于指定的DateTime值。 |
| 10 | Public Function Equals (value As DateTime) As Boolean 返回一個值,表示此實例的值是否等于指定的DateTime實例的值。 |
| 11 | Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean 返回一個值,指示兩個DateTime實例是否具有相同的日期和時間值。 |
| 12 | Public Overrides Function ToString As String 將當前DateTime對象的值轉換為其等效字符串表示形式。 |
以上列出的方法并不詳盡,請訪問微軟的文檔以獲取DateTime結構的方法和屬性的完整列表。
?
創建DateTime對象
您可以通過以下方式之一創建DateTime對象:
-
By calling a DateTime constructor from any of the overloaded DateTime constructors.通過從任何重載的DateTime構造函數調用DateTime構造函數。
-
By assigning the DateTime object a date and time value returned by a property or method.
通過為DateTime對象分配屬性或方法返回的日期和時間值。 -
By parsing the string representation of a date and time value.
通過解析日期和時間值的字符串表示。 -
By calling the DateTime structure's implicit default constructor.
通過調用DateTime結構的隱式默認構造函數。
?
下面的例子說明了這一點:
Module Module1Sub Main()'DateTime constructor: parameters year, month, day, hour, min, secDim date1 As New Date(2012, 12, 16, 12, 0, 0)'initializes a new DateTime valueDim date2 As Date = #12/16/2012 12:00:52 AM#'using propertiesDim date3 As Date = Date.NowDim date4 As Date = Date.UtcNowDim date5 As Date = Date.TodayConsole.WriteLine(date1)Console.WriteLine(date2)Console.WriteLine(date3)Console.WriteLine(date4)Console.WriteLine(date5)Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
12/16/2012 12:00:00 PM 12/16/2012 12:00:52 PM 12/12/2012 10:22:50 PM 12/12/2012 12:00:00 PM?
獲取當前日期和時間:
以下程序演示如何獲取VB.Net中的當前日期和時間:
?
當前時間:
Module dateNtimeSub Main()Console.Write("Current Time: ")Console.WriteLine(Now.ToLongTimeString)Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Current Time: 11 :05 :32 AM?
當前日期:
Module dateNtimeSub Main()Console.WriteLine("Current Date: ")Dim dt As Date = TodayConsole.WriteLine("Today is: {0}", dt)Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Today is: 12/11/2012 12:00:00 AM?
格式化日期
?
日期字面值應該用哈希符號(##)括起來,并以M / d / yyyy格式指定,例如#12/16/2012#。 否則,您的代碼可能會更改,具體取決于運行應用程序的語言環境。
例如,您為2012年2月6日的日期指定了#2/6/2012#的日期字面值。對于使用mm / dd / yyyy格式的語言環境,這是正確的。 但是,在使用dd / mm / yyyy格式的語言環境中,您的文本將編譯為2012年6月2日。如果語言環境使用另一種格式,例如yyyy / mm / dd,該文字將無效并導致編譯器錯誤。
要將Date字面值轉換為語言環境的格式或自定義格式,請使用String類的Format函數,指定預定義或用戶定義的日期格式。
下面的例子演示了這一點。
?
Module dateNtimeSub Main()Console.WriteLine("India Wins Freedom: ")Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0)' Use format specifiers to control the date display.Console.WriteLine(" Format 'd:' " & independenceDay.ToString("d"))Console.WriteLine(" Format 'D:' " & independenceDay.ToString("D"))Console.WriteLine(" Format 't:' " & independenceDay.ToString("t"))Console.WriteLine(" Format 'T:' " & independenceDay.ToString("T"))Console.WriteLine(" Format 'f:' " & independenceDay.ToString("f"))Console.WriteLine(" Format 'F:' " & independenceDay.ToString("F"))Console.WriteLine(" Format 'g:' " & independenceDay.ToString("g"))Console.WriteLine(" Format 'G:' " & independenceDay.ToString("G"))Console.WriteLine(" Format 'M:' " & independenceDay.ToString("M"))Console.WriteLine(" Format 'R:' " & independenceDay.ToString("R"))Console.WriteLine(" Format 'y:' " & independenceDay.ToString("y"))Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
India Wins Freedom: Format 'd:' 8/15/1947 Format 'D:' Friday, August 15, 1947 Format 't:' 12:00 AM Format 'T:' 12:00:00 AM Format 'f:' Friday, August 15, 1947 12:00 AM Format 'F:' Friday, August 15, 1947 12:00:00 AM Format 'g:' 8/15/1947 12:00 AM Format 'G:' 8/15/1947 12:00:00 AM Format 'M:' 8/15/1947 August 15 Format 'R:' Fri, 15 August 1947 00:00:00 GMT Format 'y:' August, 1947?
預定義的日期/時間格式
下表列出了預定義的日期和時間格式名稱。?可以通過這些名稱用作Format函數的樣式參數:
| General Date, or G | Displays a date and/or time. For example, 1/12/2012 07:07:30 AM 顯示日期和/或時間。 例如,1/12/2012 07:07:30 AM。. |
| Long Date,Medium Date, or D | Displays a date according to your current culture's long date format. For example, Sunday, December 16,2012. 根據您當前區域的長日期格式顯示日期。 例如,2012年12月16日星期日 |
| Short Date, or d | Displays a date using your current culture's short date format. For example, 12/12/2012 使用當前區域短日期格式顯示日期。 例如,12/12/2012。. |
| Long Time,Medium Time, orT | Displays a time using your current culture's long time format; typically includes hours, minutes, seconds. For example, 01:07:30 AM 使用您當前區域的長時間格式顯示時間; 通常包括小時,分鐘,秒。 例如,01:07:30 AM。. |
| Short Time or t | Displays a time using your current culture's short time format. For example, 11:07 AM 使用當前區域的短時格式顯示時間。 例如,11:07 AM。. |
| f | Displays the long date and short time according to your current culture's format. For example, Sunday, December 16, 2012 12:15 AM 根據您當前的區域格式顯示長日期和短時間。 例如,2012年12月16日星期日上午12:15。. |
| F | Displays the long date and long time according to your current culture's format. For example, Sunday, December 16, 2012 12:15:31 AM 根據您當前的區域格式顯示長日期和長時間。 例如,2012年12月16日星期日12:15:31 AM。. |
| g | Displays the short date and short time according to your current culture's format. For example, 12/16/2012 12:15 AM 根據您當前的區域格式顯示短日期和短時間。 例如,12/16/2012 12:15 AM。. |
| M, m | Displays the month and the day of a date. For example, December 16 顯示日期的月份和日期。 例如,12月16日。. |
| R, r | Formats the date according to the RFC1123Pattern property 根據RFC1123Pattern屬性格式化日期。. |
| s | Formats the date and time as a sortable index. For example, 2012-12-16T12:07:31 將日期和時間格式化為可排序索引。 例如,2012-12-16T12:07:31。. |
| u | Formats the date and time as a GMT sortable index. For example, 2012-12-16 12:15:31Z 將日期和時間格式設置為GMT可排序索引。 例如,2012-12-16 12:15:31Z。. |
| U | Formats the date and time with the long date and long time as GMT. For example, Sunday, December 16, 2012 6:07:31 PM 將日期和時間格式設置為長日期和長時間,格式為GMT。 例如,星期日,2012年12月16日下午6:07:31。. |
| Y, y | Formats the date as the year and month. For example, December, 2012 將日期格式設置為年和月。 例如,2012年12月。. |
?
對于其他格式,如用戶定義的格式,請參閱Microsoft文檔?。
?
屬性和DateAndTime類的方法
下表列出了一些DateAndTime類的常用屬性?:
| 1 | Date | Returns or sets a String value representing the current date according to your system. 返回或設置根據系統代表當前日期的字符串值。 |
| 2 | Now | Returns a Date value containing the current date and time according to your system. 返回一個包含根據系統的當前日期和時間的日期值。 |
| 3 | TimeOfDay | Returns or sets a Date value containing the current time of day according to your system. 返回或設置根據你的系統包含當天的當前時間的日期值。 |
| 4 | Timer | Returns a Double value representing the number of seconds elapsed since midnight. 返回表示自午夜起經過的秒數為Double值。 |
| 5 | TimeString | Returns or sets a String value representing the current time of day according to your system. 返回或設置根據你的系統代表一天的當前時間的字符串值。 |
| 6 | Today | Gets the current date. 獲取當前日期。 |
?
下表列出了一些DateAndTime類的常用方法?:
| 1 | Public Shared Function DateAdd (Interval As DateInterval, Number As Double, DateValue As DateTime) As DateTime 返回包含已添加指定時間間隔的日期和時間值的Date值。 |
| 2 | Public Shared Function DateAdd (Interval As String,Number As Double,DateValue As Object ) As DateTime 返回包含已添加指定時間間隔的日期和時間值的Date值。 |
| 3 | Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As FirstWeekOfYear ) As Long 返回指定兩個日期值之間的時間間隔數的長整型值。 |
| 4 | Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As FirstWeekOfYear ) As Integer 返回包含給定Date值的指定組件的整數值。 |
| 5 | Public Shared Function Day (DateValue As DateTime) As Integer 返回從1到31的整數值,表示每月的某一天。 |
| 6 | Public Shared Function Hour (TimeValue As DateTime) As Integer 公共共享函數Hour?(TIMEVALUE為DATETIME)作為整數 ? 返回從0到23的整數值,表示一天中的小時。 |
| 7 | Public Shared Function Minute (TimeValue As DateTime) As Integer 返回一個從0到59的整數值,表示小時的分鐘。 |
| 8 | Public Shared Function Month (DateValue As DateTime) As Integer 返回從1到12的整數值,表示一年中的月份。 |
| 9 | Public Shared Function MonthName (Month As Integer, Abbreviate As Boolean) As String 返回包含指定月份的名稱的字符串值。 |
| 10 | Public Shared Function Second (TimeValue As DateTime) As Integer 返回從0到59,代表分鐘的第二個整數值。 |
| 11 | Public Overridable Function ToString As String 返回表示當前對象的字符串。 |
| 12 | Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As FirstDayOfWeek) As Integer 返回包含表示星期幾的一個數的整數值。 |
| 13 | Public Shared Function WeekdayName (Weekday As Integer, Abbreviate As Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As String 返回包含指定工作日名稱的字符串值。 |
| 14 | Public Shared Function Year (DateValue As DateTime) As Integer 返回從1到9999表示年份的整數值。 |
?
上述名單并不詳盡。有關屬性和DateAndTime類的方法的完整列表,請參閱微軟的文檔。
下面的程序演示其中的一些方法:
Module Module1Sub Main()Dim birthday As DateDim bday As IntegerDim month As IntegerDim monthname As String' Assign a date using standard short format.birthday = #7/27/1998#bday = Microsoft.VisualBasic.DateAndTime.Day(birthday)month = Microsoft.VisualBasic.DateAndTime.Month(birthday)monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month)Console.WriteLine(birthday)Console.WriteLine(bday)Console.WriteLine(month)Console.WriteLine(monthname)Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
7/27/1998 12:00:00 AM 27 7 July?
?
?
VB.Net - 數組
?
?
數組存儲相同類型的元素的固定大小順序集合。 數組用于存儲數據集合,但將數組視為同一類型的變量的集合通常更有用。
?
所有數組由連續的內存位置組成。 最低地址對應于第一個元素,最高地址對應于最后一個元素。
?
?
?
在VB.Net中創建數組
要在VB.Net中聲明數組,可以使用Dim語句。 例如,
Dim intData(30) ' an array of 31 elements Dim strData(20) As String ' an array of 21 strings Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers Dim ranges(10, 100) 'a two dimensional array?
您還可以在聲明數組時初始化數組元素。 例如,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32} Dim names() As String = {"Karthik", "Sandhya", _ "Shivangi", "Ashwitha", "Somnath"} Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}?
可以通過使用數組的索引來存儲和訪問數組中的元素。 以下程序演示了這一點:
Module arrayAplSub Main()Dim n(10) As Integer ' n is an array of 11 integers 'Dim i, j As Integer' initialize elements of array n ' For i = 0 To 10n(i) = i + 100 ' set element at location i to i + 100 Next i' output each array element's value 'For j = 0 To 10Console.WriteLine("Element({0}) = {1}", j, n(j))Next jConsole.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Element(0) = 100 Element(1) = 101 Element(2) = 102 Element(3) = 103 Element(4) = 104 Element(5) = 105 Element(6) = 106 Element(7) = 107 Element(8) = 108 Element(9) = 109 Element(10) = 110?
動態數組
?
動態數組是可以根據程序需要進行維度和重新定義的數組。 您可以使用ReDim語句聲明一個動態數組。
ReDim語句的語法:
?
ReDim [Preserve] arrayname(subscripts)-
Preserve關鍵字有助于在調整現有數組大小時保留現有數組中的數據。
-
arrayname是要重新維度的數組的名稱。
-
subscripts指定新維度。
?
當上述代碼被編譯和執行時,它產生了以下結果:
0 85 1 75 2 90 3 80 4 76 5 92 6 99 7 79 8 75 9 0 10 0?
多維數組
VB.Net允許多維數組。多維數組也被稱為矩形數組。
?
你可以聲明一個二維的字符串數組:
Dim twoDStringArray(10, 20) As String?
或者,整數變量的3維數組:
Dim threeDIntArray(10, 10, 10) As Integer?
下面的程序演示創建和使用二維數組:
Module arrayAplSub Main()' an array with 5 rows and 2 columnsDim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}Dim i, j As Integer' output each array element's value 'For i = 0 To 4For j = 0 To 1Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))Next jNext iConsole.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
a[0,0]: 0 a[0,1]: 0 a[1,0]: 1 a[1,1]: 2 a[2,0]: 2 a[2,1]: 4 a[3,0]: 3 a[3,1]: 6 a[4,0]: 4 a[4,1]: 8?
不規則數組
Jagged數組是一個數組的數組。 以下代碼顯示了聲明一個名為score of Integers的不規則數組:
Dim scores As Integer()() = New Integer(5)(){}?
下面的例子說明使用不規則數組:
Module arrayAplSub Main()'a jagged array of 5 array of integersDim a As Integer()() = New Integer(4)() {}a(0) = New Integer() {0, 0}a(1) = New Integer() {1, 2}a(2) = New Integer() {2, 4}a(3) = New Integer() {3, 6}a(4) = New Integer() {4, 8}Dim i, j As Integer' output each array element's value For i = 0 To 4For j = 0 To 1Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))Next jNext iConsole.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8?
Array類
Array類是VB.Net中所有數組的基類。 它在系統命名空間中定義。 Array類提供了處理數組的各種屬性和方法。
?
Array類的屬性
下表提供了一些Array類中最常用的屬性?:
| 1 | IsFixedSize Gets a value indicating whether the Array has a fixed size. 獲取一個值,指示數組是否具有固定大小。 |
| 2 | IsReadOnly Gets a value indicating whether the Array is read-only. 獲取一個值,該值指示Array是否為只讀。 |
| 3 | Length Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. 獲取一個32位整數,表示數組所有維度中元素的總數。 |
| 4 | LongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. 獲取一個64位整數,表示數組所有維度中元素的總數。 |
| 5 | Rank Gets the rank (number of dimensions) of the Array. 獲取數組的排名(維數)。 |
?
Array類的方法
下表提供了一些最常用的Array類方法:
| 1 | Public Shared Sub Clear (array As Array, index As Integer, length As Integer) 設置一個范圍的數組元素的零,為false,或為空,這取決于元素類型。 |
| 2 | Public Shared Sub Copy (sourceArray As Array, destinationArray As Array, length As Integer) 復制一定范圍內由數組以第一個元素的元素,并將它們粘貼到起始于第一個元素另一個數組。長度被指定為32位整數。 |
| 3 | Public Sub CopyTo (array As Array, index As Integer) 將當前的一維數組到指定的一維數組從指定的目標數組索引處的所有元素。索引被指定為32位整數。 |
| 4 | Public Function GetLength (dimension As Integer) As Integer 獲取一個32位整數,它表示數組的指定維中的元素的數量。 |
| 5 | Public Function GetLongLength (dimension As Integer) As Long 獲取一個64位整數,它代表了數組的指定維中的元素的數量。 |
| 6 | Public Function GetLowerBound (dimension As Integer) As Integer 獲取下界在數組中指定的尺寸。 |
| 7 | Public Function GetType As Type 獲取當前實例的類型(從Object繼承)。 |
| 8 | Public Function GetUpperBound (dimension As Integer) As Integer 獲取上限在數組中指定的尺寸。 |
| 9 | Public Function GetValue (index As Integer) As Object 獲取在一維數組中指定位置的值。索引被指定為32位整數。 |
| 10 | Public Shared Function IndexOf (array As Array,value As Object) As Integer 搜索指定的對象,并返回第一次出現的整個一維數組中的索引。 |
| 11 | Public Shared Sub Reverse (array As Array) 反轉在整個一維數組中的元素的順序。 |
| 12 | Public Sub SetValue (value As Object, index As Integer) 在一維陣列中的指定位置設置一個值的元素。索引被指定為32位整數。 |
| 13 | Public Shared Sub Sort (array As Array) 使用排序了IComparable實現陣列中的每個元素在整個一維數組中的元素。 |
| 14 | Public Overridable Function ToString As String 返回表示當前對象(從Object繼承)的字符串。 |
有關Array類屬性和方法的完整列表,請參閱Microsoft文檔。
?
示例
下面的程序演示使用的一些Array類的方法:
?
Module arrayAplSub Main()Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}Dim temp As Integer() = listDim i As IntegerConsole.Write("Original Array: ")For Each i In listConsole.Write("{0} ", i)Next iConsole.WriteLine()' reverse the arrayArray.Reverse(temp)Console.Write("Reversed Array: ")For Each i In tempConsole.Write("{0} ", i)Next iConsole.WriteLine()'sort the arrayArray.Sort(list)Console.Write("Sorted Array: ")For Each i In listConsole.Write("{0} ", i)Next iConsole.WriteLine()Console.ReadKey()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Original Array: 34 72 13 44 25 30 10 Reversed Array: 10 30 25 44 13 72 34 Sorted Array: 10 13 25 30 34 44 72?
?
VB.Net - 集合
?
集合類是用于數據存儲和檢索的專用類。 這些類提供對堆棧,隊列,列表和哈希表的支持。 大多數集合類實現相同的接口。
?
集合類用于各種目的,例如動態地為元素分配內存以及基于索引訪問項目列表等。這些類創建Object類的對象集合,Object類是VB中所有數據類型的基類 。
?
各種集合類和它們的用法
以下是System.Collection命名空間的各種常用類。 單擊以下鏈接以檢查其詳細信息。
?
| ArrayList | It represents ordered collection of an object that can be?indexedindividually. 它表示可以單獨索引的對象的有序集合。 It is basically an alternative to an array. However, unlike array, you can add and remove items from a list at a specified position using anindex?and the array resizes itself automatically. It also allows dynamic memory allocation, add, search and sort items in the list. 它基本上是一個數組的替代。 但是,與數組不同,您可以使用索引在指定位置從列表中添加和刪除項目,并且數組會自動調整大小。 它還允許動態內存分配,添加,搜索和排序列表中的項目。 |
| Hashtable | It uses a?key?to access the elements in the collection. 它使用一個鍵來訪問集合中的元素。 A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a?key/value?pair. The key is used to access the items in the collection. 當您需要通過使用鍵訪問元素時使用散列表,您可以標識有用的鍵值。 散列表中的每個項都有一個鍵/值對。 該鍵用于訪問集合中的項目。 |
| SortedList | It uses a?key?as well as an?index?to access the items in a list. 它使用一個密鑰以及索引來訪問列表中的項目。 A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value. 排序的列表是數組和哈希表的組合。它包含可以使用的鍵或索引訪問的項的列表。如果您訪問使用索引的項目,它是一個?ArrayList,和如果你訪問項目使用一把鑰匙,它是一個哈希表。項的集合總是按關鍵值排序的。 |
| Stack | It represents a?last-in, first out?collection of object. 它表示對象的后進先出的集合。 ? It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called?pushing?the item, and when you remove it, it is calledpopping?the item. 當您需要項目的最后進入,首先訪問時使用。 當您在列表中添加項目時,稱為推送項目,當您刪除它時,它被稱為彈出項目。 ? |
| Queue | It represents a?first-in, first out?collection of object. 它表示對象的先進先出集合。 ? It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called?enqueue, and when you remove an item, it is called?deque. 當您需要項目的先進先出訪問時使用。 當您在列表中添加項目時,它被稱為enqueue,當您刪除項目時,稱為deque。 |
| BitArray | It represents an array of the?binary representation?using the values 1 and 0. 它表示使用值1和0的二進制表示的數組。 It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an?integer index, which starts from zero. 它用于需要存儲位但不提前知道位數。 您可以通過使用從零開始的整數索引來訪問BitArray集合中的項目。 |
?
?
?
VB.Net - 函數
?
過程是一組調用時一起執行任務的語句。執行該過程之后,控制返回到調用過程的語句。 VB.Net有兩種類型的程序:
-
Functions
-
Sub procedures or Subs
函數返回一個值,而Subs不返回值。
?
定義函數
函數語句用于聲明函數的名稱,參數和主體。 函數語句的語法是:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType[Statements] End Function-
Modifiers?修飾符?:指定函數的訪問級別;可能的值有:公共,私有,保護,朋友,關于保護超載,重載,共享和陰影朋友和信息。
-
FunctionName:表示該函數的名稱
-
ParameterList?參數列表?:指定參數的列表
-
ReturnType?返回類型?:指定變量的函數返回的數據類型
?
示例
以下代碼片段顯示了一個函數FindMax,它接受兩個整數值,并返回兩個較大者。
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer' local variable declaration */Dim result As IntegerIf (num1 > num2) Thenresult = num1Elseresult = num2End IfFindMax = result End Function?
函數返回值
在VB.Net中,函數可以通過兩種方式向調用代碼返回一個值:
-
通過使用return語句
-
通過將值分配給函數名
?
下面的例子演示了如何使用FindMax函數:
Module myfunctionsFunction FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer' local variable declaration */Dim result As IntegerIf (num1 > num2) Thenresult = num1Elseresult = num2End IfFindMax = resultEnd FunctionSub Main()Dim a As Integer = 100Dim b As Integer = 200Dim res As Integerres = FindMax(a, b)Console.WriteLine("Max value is : {0}", res)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Max value is : 200?
遞歸函數
一個函數可以調用自身。 這被稱為遞歸。 以下是使用遞歸函數計算給定數字的階乘的示例:
Module myfunctionsFunction factorial(ByVal num As Integer) As Integer' local variable declaration */Dim result As IntegerIf (num = 1) ThenReturn 1Elseresult = factorial(num - 1) * numReturn resultEnd IfEnd FunctionSub Main()'calling the factorial methodConsole.WriteLine("Factorial of 6 is : {0}", factorial(6))Console.WriteLine("Factorial of 7 is : {0}", factorial(7))Console.WriteLine("Factorial of 8 is : {0}", factorial(8))Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320?
參數數組
?
有時,在聲明函數或子過程時,您不確定作為參數傳遞的參數的數量。 VB.Net param數組(或參數數組)在這些時候來幫助。
以下示例演示了這一點:
?
Module myparamfuncFunction AddElements(ParamArray arr As Integer()) As IntegerDim sum As Integer = 0Dim i As Integer = 0For Each i In arrsum += iNext iReturn sumEnd FunctionSub Main()Dim sum As Integersum = AddElements(512, 720, 250, 567, 889)Console.WriteLine("The sum is: {0}", sum)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
The sum is: 2938?
傳遞數組作為函數參數
您可以在VB.Net中將數組作為函數參數傳遞。 以下示例演示了這一點:
Module arrayParameterFunction getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double'local variablesDim i As IntegerDim avg As DoubleDim sum As Integer = 0For i = 0 To size - 1sum += arr(i)Next iavg = sum / sizeReturn avgEnd FunctionSub Main()' an int array with 5 elements 'Dim balance As Integer() = {1000, 2, 3, 17, 50}Dim avg As Double'pass pointer to the array as an argument avg = getAverage(balance, 5)' output the returned value 'Console.WriteLine("Average value is: {0} ", avg)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Average value is: 214.4?
?
?
VB.Net - Sub過程(子程序)
?
正如我們在上一章中提到的,Sub過程是不返回任何值的過程。 我們在所有的例子中一直使用Sub過程Main。 到目前為止,我們已經在這些教程中編寫控制臺應用程序。 當這些應用程序開始時,控制轉到主子程序,它反過來運行構成程序主體的任何其他語句。
定義子過程
Sub語句用于聲明子過程的名稱,參數和主體。 Sub語句的語法是:
[Modifiers] Sub SubName [(ParameterList)] [Statements] End Sub-
Modifiers?修飾符?:指定過程的訪問級別;可能的值有:Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
-
SubName?子名?:表示該子的名字
-
ParameterList?參數列表?:指定參數的列表
示例
?
以下示例演示了子過程CalculatePay,它接受兩個參數小時和工資,并顯示員工的總工資:
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)'local variable declarationDim pay As Doublepay = hours * wageConsole.WriteLine("Total Pay: {0:C}", pay)End SubSub Main()'calling the CalculatePay Sub ProcedureCalculatePay(25, 10)CalculatePay(40, 20)CalculatePay(30, 27.5)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Total Pay: $250.00 Total Pay: $800.00 Total Pay: $825.00?
按值傳遞參數
這是將參數傳遞給方法的默認機制。 在這種機制中,當調用方法時,為每個值參數創建一個新的存儲位置。 實際參數的值被復制到它們中。 因此,對方法中的參數所做的更改對參數沒有影響。
?
在VB.Net中,可以使用ByVal關鍵字聲明引用參數。 下面的例子演示了這個概念:
Module paramByvalSub swap(ByVal x As Integer, ByVal y As Integer)Dim temp As Integertemp = x ' save the value of x x = y ' put y into x y = temp 'put temp into y End SubSub Main()' local variable definition Dim a As Integer = 100Dim b As Integer = 200Console.WriteLine("Before swap, value of a : {0}", a)Console.WriteLine("Before swap, value of b : {0}", b)' calling a function to swap the values 'swap(a, b)Console.WriteLine("After swap, value of a : {0}", a)Console.WriteLine("After swap, value of b : {0}", b)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200它表明,雖然它們在函數內部已更改,但值中沒有變化。
?
通過引用傳遞參數
引用參數是對變量的存儲器位置的引用。 當您通過引用傳遞參數時,與值參數不同,不會為這些參數創建新的存儲位置。 參考參數表示與提供給該方法的實際參數相同的存儲器位置。
?
在VB.Net中,可以使用ByRef關鍵字聲明引用參數。 以下示例演示了這一點:
Module paramByrefSub swap(ByRef x As Integer, ByRef y As Integer)Dim temp As Integertemp = x ' save the value of x x = y ' put y into x y = temp 'put temp into y End SubSub Main()' local variable definition Dim a As Integer = 100Dim b As Integer = 200Console.WriteLine("Before swap, value of a : {0}", a)Console.WriteLine("Before swap, value of b : {0}", b)' calling a function to swap the values 'swap(a, b)Console.WriteLine("After swap, value of a : {0}", a)Console.WriteLine("After swap, value of b : {0}", b)Console.ReadLine()End Sub End Module?
當上述代碼被編譯和執行時,它產生了以下結果:
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100?
?
?
未完待續,下一章節,つづく
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的VB.NET 教程_02_常见对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fabric shim安装合约_hype
- 下一篇: asp.net ajax控件工具集 Au