VB.NET 教程_02_常见对象
VB.Net - 字符串
?
在VB.Net中,可以使用字符串作為字符數(shù)組,但是更常見的做法是使用String關(guān)鍵字聲明一個(gè)字符串變量。 string關(guān)鍵字是System.String類的別名。
創(chuàng)建一個(gè)字符串對象
您可以使用以下方法之一創(chuàng)建字符串對象:
-
By assigning a string literal to a String variable?通過指定一個(gè)字符串給一個(gè)字符串變量?
-
By using a String class constructor?通過使用String類構(gòu)造函數(shù)
-
By using the string concatenation operator (+)?通過使用字符串連接運(yùn)算符(+)?
-
By retrieving a property or calling a method that returns a string?通過檢索屬性或調(diào)用返回字符串的方法
-
By calling a formatting method to convert a value or object to its string representation
通過調(diào)用格式化方法將值或?qū)ο筠D(zhuǎn)換為其字符串表示形式
?
下面的例子說明了這一點(diǎn):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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類有以下兩個(gè)屬性:
| 1 | Chars 獲取當(dāng)前String對象中指定位置的Char對象。 |
| 2 | Length 獲取當(dāng)前String對象中的字符數(shù)。 |
?
String類的方法
String類有許多方法可以幫助你處理字符串對象。 下表提供了一些最常用的方法:
| 1 | Public Shared Function Compare ( strA As String, strB As String ) As Integer 比較兩個(gè)指定的字符串對象,并返回一個(gè)整數(shù),指示它們在排序順序中的相對位置。 |
| 2 | Public Shared Function Compare ( strA As String, strB As String, ignoreCase As Boolean ) As Integer 比較兩個(gè)指定的字符串對象,并返回一個(gè)整數(shù),指示它們在排序順序中的相對位置。 但是,如果布爾參數(shù)為true,它將忽略大小寫。 |
| 3 | Public Shared Function Concat ( str0 As String, str1 As String ) As String 連接兩個(gè)字符串對象。 |
| 4 | Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As String 連接三個(gè)字符串對象。 |
| 5 | Public Shared Function Concat ( str0 As String, str1 As String, str2 As String, str3 As String ) As String公共共享函數(shù)Concat(str0 As String,str1 As String,str2 As String,str3 As String)As String 連接四個(gè)字符串對象。 |
| 6 | Public Function Contains ( value As String ) As Boolean 返回一個(gè)值,指示指定的字符串對象是否出現(xiàn)在此字符串中。 |
| 7 | Public Shared Function Copy ( str As String ) As String 創(chuàng)建與指定字符串具有相同值的新String對象。 |
| 8 | pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(), destinationIndex As Integer, count As Integer ) 將指定數(shù)量的字符從字符串對象的指定位置復(fù)制到Unicode字符數(shù)組中的指定位置。 |
| 9 | Public Function EndsWith ( value As String ) As Boolean 確定字符串對象的結(jié)尾是否與指定的字符串匹配。 |
| 10 | Public Function Equals ( value As String ) As Boolean 確定當(dāng)前字符串對象,并指定字符串對象是否具有相同的值。 |
| 11 | Public Shared Function Equals ( a As String, b As String ) As Boolean 確定兩個(gè)指定字符串對象是否具有相同的值。 |
| 12 | Public Shared Function Format ( format As String, arg0 As Object ) As String 將指定字符串中的一個(gè)或多個(gè)格式項(xiàng)替換為指定對象的字符串表示形式。 |
| 13 | Public Function IndexOf ( value As Char ) As Integer 返回當(dāng)前字符串中指定Unicode字符第一次出現(xiàn)的從零開始的索引。 |
| 14 | Public Function IndexOf ( value As String ) As Integer 返回此實(shí)例中指定字符串第一次出現(xiàn)的從零開始的索引。 |
| 15 | Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer 返回此字符串中指定Unicode字符第一次出現(xiàn)的從零開始的索引,從指定的字符位置開始搜索。 |
| 16 | Public Function IndexOf ( value As String, startIndex As Integer ) As Integer 返回此實(shí)例中指定字符串第一次出現(xiàn)的從零開始的索引,開始在指定的字符位置搜索。 |
| 17 | Public Function IndexOfAny ( anyOf As Char() ) As Integer 返回在指定的Unicode字符數(shù)組中的任何字符的此實(shí)例中第一次出現(xiàn)的從零開始的索引。 |
| 18 | Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer 返回在指定的Unicode字符數(shù)組中的任意字符的此實(shí)例中第一次出現(xiàn)的從零開始的索引,開始在指定的字符位置搜索。 |
| 19 | Public Function Insert ( startIndex As Integer, value As String ) As String 返回一個(gè)新字符串,其中指定的字符串插入到當(dāng)前字符串對象中指定的索引位置。 |
| 20 | Public Shared Function IsNullOrEmpty ( value As String ) As Boolean 指示指定的字符串是空還是空字符串。 |
| 21 | Public Shared Function Join ( separator As String, ParamArray value As String() ) As String 連接字符串?dāng)?shù)組的所有元素,使用每個(gè)元素之間指定的分隔符。 |
| 22 | Public Shared Function Join ( separator As String, value As String(), startIndex As Integer, count As Integer ) As String 使用每個(gè)元素之間指定的分隔符連接字符串?dāng)?shù)組的指定元素。 |
| 23 | Public Function LastIndexOf ( value As Char ) As Integer 返回當(dāng)前字符串對象中指定Unicode字符的最后一次出現(xiàn)的從零開始的索引位置。 |
| 24 | Public Function LastIndexOf ( value As String ) As Integer 返回當(dāng)前字符串對象中指定字符串的最后一次出現(xiàn)的從零開始的索引位置。 |
| 25 | Public Function Remove ( startIndex As Integer )As String 刪除當(dāng)前實(shí)例中的所有字符,從指定位置開始,并繼續(xù)到最后一個(gè)位置,并返回字符串。 |
| 26 | Public Function Remove ( startIndex As Integer, count As Integer ) As String 從指定位置開始刪除當(dāng)前字符串中指定數(shù)量的字符,并返回字符串。 |
| 27 | Public Function Replace ( oldChar As Char, newChar As Char ) As String 用指定的Unicode字符替換當(dāng)前字符串對象中指定Unicode字符的所有出現(xiàn),并返回新字符串。 |
| 28 | Public Function Replace ( oldValue As String, newValue As String ) As String 將當(dāng)前字符串對象中指定字符串的所有出現(xiàn)替換為指定的字符串,并返回新字符串。 |
| 29 | Public Function Split ( ParamArray separator As Char() ) As String() 返回一個(gè)字符串?dāng)?shù)組,其中包含當(dāng)前字符串對象中的子字符串,由指定的Unicode字符數(shù)組的元素分隔。 |
| 30 | Public Function Split ( separator As Char(), count As Integer ) As String() 返回一個(gè)字符串?dāng)?shù)組,其中包含當(dāng)前字符串對象中的子字符串,由指定的Unicode字符數(shù)組的元素分隔。 int參數(shù)指定要返回的子字符串的最大數(shù)目。 |
| 31 | Public Function StartsWith ( value As String ) As Boolean 確定此字符串實(shí)例的開頭是否與指定的字符串匹配。 |
| 32 | Public Function ToCharArray As Char() 返回包含當(dāng)前字符串對象中所有字符的Unicode字符數(shù)組。 |
| 33 | Public Function ToCharArray ( startIndex As Integer, length As Integer ) As Char() 返回一個(gè)Unicode字符數(shù)組,其中包含當(dāng)前字符串對象中的所有字符,從指定的索引開始,直到指定的長度。 |
| 34 | Public Function ToLower As String 返回此字符串的轉(zhuǎn)換為小寫的副本。 |
| 35 | Public Function ToUpper As String 返回此字符串的轉(zhuǎn)換為大寫的副本。 |
| 36 | Public Function Trim As String 從當(dāng)前String對象中刪除所有前導(dǎo)和尾部空格字符。 |
上面列出的方法并不詳盡,請?jiān)L問MSDN庫獲取完整的方法列表和String類構(gòu)造函數(shù)。
?
例子:
下面的例子說明了上述一些方法:
?
比較字符串:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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 - 日期和時(shí)間
?
你寫的大部分軟件都需要實(shí)現(xiàn)某種形式的日期功能,返回當(dāng)前日期和時(shí)間。日期是日常生活的一部分,使用它能讓工作變得輕松,不需要太多思考。?VB.Net還提供了強(qiáng)大的日期算術(shù)工具,使操作日期變得容易。
?
日期數(shù)據(jù)類型包含日期值,時(shí)間值或日期和時(shí)間值。 Date的默認(rèn)值為0001年1月1日的0:00:00(午夜)。等效的.NET數(shù)據(jù)類型為System.DateTime。
?
DateTime?結(jié)構(gòu)表示即時(shí)時(shí)間,通常表示為日期和時(shí)間的一天
'Declaration <SerializableAttribute> _ Public Structure DateTime _Implements IComparable, IFormattable, IConvertible, ISerializable, IComparable(Of DateTime), IEquatable(Of DateTime)您還可以從DateAndTime類獲取當(dāng)前日期和時(shí)間。
?
DateAndTime模塊包含日期和時(shí)間操作中使用的過程和屬性。
'Declaration <StandardModuleAttribute> _ Public NotInheritable Class DateAndTime| 注意: DateTime結(jié)構(gòu)和DateAndTime模塊都包含諸如Now和Today之類的屬性,因此初學(xué)者經(jīng)常會(huì)感到困惑。 DateAndTime類屬于Microsoft.VisualBasic命名空間,DateTime結(jié)構(gòu)屬于System命名空間。
|
DateTime結(jié)構(gòu)的屬性和方法
下表列出了一些DateTime結(jié)構(gòu)的常用屬性?:
?
| 1 | Date | Gets the date component of this instance. 獲取此實(shí)例的日期組件。 |
| 2 | Day | Gets the day of the month represented by this instance. 獲取此實(shí)例所代表的月份中的某一天。 |
| 3 | DayOfWeek | Gets the day of the week represented by this instance. 獲取此實(shí)例表示的星期幾。 |
| 4 | DayOfYear | Gets the day of the year represented by this instance. 獲取此實(shí)例表示的一年中的某一天。 |
| 5 | Hour | Gets the hour component of the date represented by this instance. 獲取此實(shí)例表示的日期的小時(shí)組件。 |
| 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 獲取一個(gè)值,該值指示此實(shí)例表示的時(shí)間是基于本地時(shí)間,協(xié)調(diào)世界時(shí)間(UTC)還是兩者都不是。 |
| 7 | Millisecond | Gets the milliseconds component of the date represented by this instance. 獲取此實(shí)例表示的日期的毫秒組件。 |
| 8 | Minute | Gets the minute component of the date represented by this instance. 獲取此實(shí)例表示的日期的分鐘分量。 |
| 9 | Month | Gets the month component of the date represented by this instance. 獲取此實(shí)例表示的日期的月份。 |
| 10 | Now | Gets a?DateTime?object that is set to the current date and time on this computer, expressed as the local time. 獲取在此計(jì)算機(jī)上設(shè)置為當(dāng)前日期和時(shí)間的DateTime對象,以本地時(shí)間表示。 |
| 11 | Second | Gets the seconds component of the date represented by this instance. 獲取此實(shí)例表示的日期的秒組件。 |
| 12 | Ticks | Gets the number of ticks that represent the date and time of this instance. 獲取表示此實(shí)例的日期和時(shí)間的刻度數(shù)。 |
| 13 | TimeOfDay | Gets the time of day for this instance. 獲取此實(shí)例的時(shí)間。 |
| 14 | Today | Gets the current date. 獲取當(dāng)前日期。 |
| 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). 獲取設(shè)置為此計(jì)算機(jī)上當(dāng)前日期和時(shí)間的DateTime對象,以協(xié)調(diào)世界時(shí)(UTC)表示。 |
| 16 | Year | Gets the year component of the date represented by this instance. 獲取此實(shí)例表示的日期的年份組件。 |
?
?
下表列出了DateTime結(jié)構(gòu)的一些常用方法:
| 1 | Public Function Add (value As TimeSpan) As DateTime 返回一個(gè)新的DateTime,將指定的TimeSpan的值添加到此實(shí)例的值。 |
| 2 | Public Function AddDays ( value As Double) As DateTime 返回一個(gè)新的DateTime,該值將指定的天數(shù)添加到此實(shí)例的值中。 |
| 3 | Public Function AddHours (value As Double) As DateTime 返回一個(gè)新的DateTime,該值將指定的小時(shí)數(shù)添加到此實(shí)例的值中。 |
| 4 | Public Function AddMinutes (value As Double) As DateTime 返回一個(gè)新的DateTime,將指定的分鐘數(shù)添加到此實(shí)例的值。 |
| 5 | Public Function AddMonths (months As Integer) As DateTime 返回一個(gè)新的DateTime,將指定的月數(shù)添加到此實(shí)例的值。 |
| 6 | Public Function AddSeconds (value As Double) As DateTime 返回一個(gè)新的DateTime,將指定的秒數(shù)添加到此實(shí)例的值。 |
| 7 | Public Function AddYears (value As Integer ) As DateTime 返回一個(gè)新的DateTime,將指定的年數(shù)添加到此實(shí)例的值。 |
| 8 | Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer 比較兩個(gè)DateTime實(shí)例,并返回一個(gè)整數(shù),指示第一個(gè)實(shí)例是早于,與第二個(gè)實(shí)例相同還是晚于第二個(gè)實(shí)例。 |
| 9 | Public Function CompareTo (value As DateTime) As Integer 將此實(shí)例的值與指定的DateTime值進(jìn)行比較,并返回一個(gè)整數(shù),指示此實(shí)例是早于,等于還是晚于指定的DateTime值。 |
| 10 | Public Function Equals (value As DateTime) As Boolean 返回一個(gè)值,表示此實(shí)例的值是否等于指定的DateTime實(shí)例的值。 |
| 11 | Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean 返回一個(gè)值,指示兩個(gè)DateTime實(shí)例是否具有相同的日期和時(shí)間值。 |
| 12 | Public Overrides Function ToString As String 將當(dāng)前DateTime對象的值轉(zhuǎn)換為其等效字符串表示形式。 |
以上列出的方法并不詳盡,請?jiān)L問微軟的文檔以獲取DateTime結(jié)構(gòu)的方法和屬性的完整列表。
?
創(chuàng)建DateTime對象
您可以通過以下方式之一創(chuàng)建DateTime對象:
-
By calling a DateTime constructor from any of the overloaded DateTime constructors.通過從任何重載的DateTime構(gòu)造函數(shù)調(diào)用DateTime構(gòu)造函數(shù)。
-
By assigning the DateTime object a date and time value returned by a property or method.
通過為DateTime對象分配屬性或方法返回的日期和時(shí)間值。 -
By parsing the string representation of a date and time value.
通過解析日期和時(shí)間值的字符串表示。 -
By calling the DateTime structure's implicit default constructor.
通過調(diào)用DateTime結(jié)構(gòu)的隱式默認(rèn)構(gòu)造函數(shù)。
?
下面的例子說明了這一點(diǎn):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
獲取當(dāng)前日期和時(shí)間:
以下程序演示如何獲取VB.Net中的當(dāng)前日期和時(shí)間:
?
當(dāng)前時(shí)間:
Module dateNtimeSub Main()Console.Write("Current Time: ")Console.WriteLine(Now.ToLongTimeString)Console.ReadKey()End Sub End Module?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Current Time: 11 :05 :32 AM?
當(dāng)前日期:
Module dateNtimeSub Main()Console.WriteLine("Current Date: ")Dim dt As Date = TodayConsole.WriteLine("Today is: {0}", dt)Console.ReadKey()End Sub End Module?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Today is: 12/11/2012 12:00:00 AM?
格式化日期
?
日期字面值應(yīng)該用哈希符號(hào)(##)括起來,并以M / d / yyyy格式指定,例如#12/16/2012#。 否則,您的代碼可能會(huì)更改,具體取決于運(yùn)行應(yīng)用程序的語言環(huán)境。
例如,您為2012年2月6日的日期指定了#2/6/2012#的日期字面值。對于使用mm / dd / yyyy格式的語言環(huán)境,這是正確的。 但是,在使用dd / mm / yyyy格式的語言環(huán)境中,您的文本將編譯為2012年6月2日。如果語言環(huán)境使用另一種格式,例如yyyy / mm / dd,該文字將無效并導(dǎo)致編譯器錯(cuò)誤。
要將Date字面值轉(zhuǎn)換為語言環(huán)境的格式或自定義格式,請使用String類的Format函數(shù),指定預(yù)定義或用戶定義的日期格式。
下面的例子演示了這一點(diǎn)。
?
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
預(yù)定義的日期/時(shí)間格式
下表列出了預(yù)定義的日期和時(shí)間格式名稱。?可以通過這些名稱用作Format函數(shù)的樣式參數(shù):
| General Date, or G | Displays a date and/or time. For example, 1/12/2012 07:07:30 AM 顯示日期和/或時(shí)間。 例如,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. 根據(jù)您當(dāng)前區(qū)域的長日期格式顯示日期。 例如,2012年12月16日星期日 |
| Short Date, or d | Displays a date using your current culture's short date format. For example, 12/12/2012 使用當(dāng)前區(qū)域短日期格式顯示日期。 例如,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 使用您當(dāng)前區(qū)域的長時(shí)間格式顯示時(shí)間; 通常包括小時(shí),分鐘,秒。 例如,01:07:30 AM。. |
| Short Time or t | Displays a time using your current culture's short time format. For example, 11:07 AM 使用當(dāng)前區(qū)域的短時(shí)格式顯示時(shí)間。 例如,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 根據(jù)您當(dāng)前的區(qū)域格式顯示長日期和短時(shí)間。 例如,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 根據(jù)您當(dāng)前的區(qū)域格式顯示長日期和長時(shí)間。 例如,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 根據(jù)您當(dāng)前的區(qū)域格式顯示短日期和短時(shí)間。 例如,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 根據(jù)RFC1123Pattern屬性格式化日期。. |
| s | Formats the date and time as a sortable index. For example, 2012-12-16T12:07:31 將日期和時(shí)間格式化為可排序索引。 例如,2012-12-16T12:07:31。. |
| u | Formats the date and time as a GMT sortable index. For example, 2012-12-16 12:15:31Z 將日期和時(shí)間格式設(shè)置為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 將日期和時(shí)間格式設(shè)置為長日期和長時(shí)間,格式為GMT。 例如,星期日,2012年12月16日下午6:07:31。. |
| Y, y | Formats the date as the year and month. For example, December, 2012 將日期格式設(shè)置為年和月。 例如,2012年12月。. |
?
對于其他格式,如用戶定義的格式,請參閱Microsoft文檔?。
?
屬性和DateAndTime類的方法
下表列出了一些DateAndTime類的常用屬性?:
| 1 | Date | Returns or sets a String value representing the current date according to your system. 返回或設(shè)置根據(jù)系統(tǒng)代表當(dāng)前日期的字符串值。 |
| 2 | Now | Returns a Date value containing the current date and time according to your system. 返回一個(gè)包含根據(jù)系統(tǒng)的當(dāng)前日期和時(shí)間的日期值。 |
| 3 | TimeOfDay | Returns or sets a Date value containing the current time of day according to your system. 返回或設(shè)置根據(jù)你的系統(tǒng)包含當(dāng)天的當(dāng)前時(shí)間的日期值。 |
| 4 | Timer | Returns a Double value representing the number of seconds elapsed since midnight. 返回表示自午夜起經(jīng)過的秒數(shù)為Double值。 |
| 5 | TimeString | Returns or sets a String value representing the current time of day according to your system. 返回或設(shè)置根據(jù)你的系統(tǒng)代表一天的當(dāng)前時(shí)間的字符串值。 |
| 6 | Today | Gets the current date. 獲取當(dāng)前日期。 |
?
下表列出了一些DateAndTime類的常用方法?:
| 1 | Public Shared Function DateAdd (Interval As DateInterval, Number As Double, DateValue As DateTime) As DateTime 返回包含已添加指定時(shí)間間隔的日期和時(shí)間值的Date值。 |
| 2 | Public Shared Function DateAdd (Interval As String,Number As Double,DateValue As Object ) As DateTime 返回包含已添加指定時(shí)間間隔的日期和時(shí)間值的Date值。 |
| 3 | Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime, Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As FirstWeekOfYear ) As Long 返回指定兩個(gè)日期值之間的時(shí)間間隔數(shù)的長整型值。 |
| 4 | Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime, FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As FirstWeekOfYear ) As Integer 返回包含給定Date值的指定組件的整數(shù)值。 |
| 5 | Public Shared Function Day (DateValue As DateTime) As Integer 返回從1到31的整數(shù)值,表示每月的某一天。 |
| 6 | Public Shared Function Hour (TimeValue As DateTime) As Integer 公共共享函數(shù)Hour?(TIMEVALUE為DATETIME)作為整數(shù) ? 返回從0到23的整數(shù)值,表示一天中的小時(shí)。 |
| 7 | Public Shared Function Minute (TimeValue As DateTime) As Integer 返回一個(gè)從0到59的整數(shù)值,表示小時(shí)的分鐘。 |
| 8 | Public Shared Function Month (DateValue As DateTime) As Integer 返回從1到12的整數(shù)值,表示一年中的月份。 |
| 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,代表分鐘的第二個(gè)整數(shù)值。 |
| 11 | Public Overridable Function ToString As String 返回表示當(dāng)前對象的字符串。 |
| 12 | Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As FirstDayOfWeek) As Integer 返回包含表示星期幾的一個(gè)數(shù)的整數(shù)值。 |
| 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表示年份的整數(shù)值。 |
?
上述名單并不詳盡。有關(guān)屬性和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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
7/27/1998 12:00:00 AM 27 7 July?
?
?
VB.Net - 數(shù)組
?
?
數(shù)組存儲(chǔ)相同類型的元素的固定大小順序集合。 數(shù)組用于存儲(chǔ)數(shù)據(jù)集合,但將數(shù)組視為同一類型的變量的集合通常更有用。
?
所有數(shù)組由連續(xù)的內(nèi)存位置組成。 最低地址對應(yīng)于第一個(gè)元素,最高地址對應(yīng)于最后一個(gè)元素。
?
?
?
在VB.Net中創(chuàng)建數(shù)組
要在VB.Net中聲明數(shù)組,可以使用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?
您還可以在聲明數(shù)組時(shí)初始化數(shù)組元素。 例如,
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}?
可以通過使用數(shù)組的索引來存儲(chǔ)和訪問數(shù)組中的元素。 以下程序演示了這一點(diǎn):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
動(dòng)態(tài)數(shù)組
?
動(dòng)態(tài)數(shù)組是可以根據(jù)程序需要進(jìn)行維度和重新定義的數(shù)組。 您可以使用ReDim語句聲明一個(gè)動(dòng)態(tài)數(shù)組。
ReDim語句的語法:
?
ReDim [Preserve] arrayname(subscripts)-
Preserve關(guān)鍵字有助于在調(diào)整現(xiàn)有數(shù)組大小時(shí)保留現(xiàn)有數(shù)組中的數(shù)據(jù)。
-
arrayname是要重新維度的數(shù)組的名稱。
-
subscripts指定新維度。
?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
0 85 1 75 2 90 3 80 4 76 5 92 6 99 7 79 8 75 9 0 10 0?
多維數(shù)組
VB.Net允許多維數(shù)組。多維數(shù)組也被稱為矩形數(shù)組。
?
你可以聲明一個(gè)二維的字符串?dāng)?shù)組:
Dim twoDStringArray(10, 20) As String?
或者,整數(shù)變量的3維數(shù)組:
Dim threeDIntArray(10, 10, 10) As Integer?
下面的程序演示創(chuàng)建和使用二維數(shù)組:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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?
不規(guī)則數(shù)組
Jagged數(shù)組是一個(gè)數(shù)組的數(shù)組。 以下代碼顯示了聲明一個(gè)名為score of Integers的不規(guī)則數(shù)組:
Dim scores As Integer()() = New Integer(5)(){}?
下面的例子說明使用不規(guī)則數(shù)組:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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中所有數(shù)組的基類。 它在系統(tǒng)命名空間中定義。 Array類提供了處理數(shù)組的各種屬性和方法。
?
Array類的屬性
下表提供了一些Array類中最常用的屬性?:
| 1 | IsFixedSize Gets a value indicating whether the Array has a fixed size. 獲取一個(gè)值,指示數(shù)組是否具有固定大小。 |
| 2 | IsReadOnly Gets a value indicating whether the Array is read-only. 獲取一個(gè)值,該值指示Array是否為只讀。 |
| 3 | Length Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. 獲取一個(gè)32位整數(shù),表示數(shù)組所有維度中元素的總數(shù)。 |
| 4 | LongLength Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. 獲取一個(gè)64位整數(shù),表示數(shù)組所有維度中元素的總數(shù)。 |
| 5 | Rank Gets the rank (number of dimensions) of the Array. 獲取數(shù)組的排名(維數(shù))。 |
?
Array類的方法
下表提供了一些最常用的Array類方法:
| 1 | Public Shared Sub Clear (array As Array, index As Integer, length As Integer) 設(shè)置一個(gè)范圍的數(shù)組元素的零,為false,或?yàn)榭?#xff0c;這取決于元素類型。 |
| 2 | Public Shared Sub Copy (sourceArray As Array, destinationArray As Array, length As Integer) 復(fù)制一定范圍內(nèi)由數(shù)組以第一個(gè)元素的元素,并將它們粘貼到起始于第一個(gè)元素另一個(gè)數(shù)組。長度被指定為32位整數(shù)。 |
| 3 | Public Sub CopyTo (array As Array, index As Integer) 將當(dāng)前的一維數(shù)組到指定的一維數(shù)組從指定的目標(biāo)數(shù)組索引處的所有元素。索引被指定為32位整數(shù)。 |
| 4 | Public Function GetLength (dimension As Integer) As Integer 獲取一個(gè)32位整數(shù),它表示數(shù)組的指定維中的元素的數(shù)量。 |
| 5 | Public Function GetLongLength (dimension As Integer) As Long 獲取一個(gè)64位整數(shù),它代表了數(shù)組的指定維中的元素的數(shù)量。 |
| 6 | Public Function GetLowerBound (dimension As Integer) As Integer 獲取下界在數(shù)組中指定的尺寸。 |
| 7 | Public Function GetType As Type 獲取當(dāng)前實(shí)例的類型(從Object繼承)。 |
| 8 | Public Function GetUpperBound (dimension As Integer) As Integer 獲取上限在數(shù)組中指定的尺寸。 |
| 9 | Public Function GetValue (index As Integer) As Object 獲取在一維數(shù)組中指定位置的值。索引被指定為32位整數(shù)。 |
| 10 | Public Shared Function IndexOf (array As Array,value As Object) As Integer 搜索指定的對象,并返回第一次出現(xiàn)的整個(gè)一維數(shù)組中的索引。 |
| 11 | Public Shared Sub Reverse (array As Array) 反轉(zhuǎn)在整個(gè)一維數(shù)組中的元素的順序。 |
| 12 | Public Sub SetValue (value As Object, index As Integer) 在一維陣列中的指定位置設(shè)置一個(gè)值的元素。索引被指定為32位整數(shù)。 |
| 13 | Public Shared Sub Sort (array As Array) 使用排序了IComparable實(shí)現(xiàn)陣列中的每個(gè)元素在整個(gè)一維數(shù)組中的元素。 |
| 14 | Public Overridable Function ToString As String 返回表示當(dāng)前對象(從Object繼承)的字符串。 |
有關(guān)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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
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 - 集合
?
集合類是用于數(shù)據(jù)存儲(chǔ)和檢索的專用類。 這些類提供對堆棧,隊(duì)列,列表和哈希表的支持。 大多數(shù)集合類實(shí)現(xiàn)相同的接口。
?
集合類用于各種目的,例如動(dòng)態(tài)地為元素分配內(nèi)存以及基于索引訪問項(xiàng)目列表等。這些類創(chuàng)建Object類的對象集合,Object類是VB中所有數(shù)據(jù)類型的基類 。
?
各種集合類和它們的用法
以下是System.Collection命名空間的各種常用類。 單擊以下鏈接以檢查其詳細(xì)信息。
?
| ArrayList | It represents ordered collection of an object that can be?indexedindividually. 它表示可以單獨(dú)索引的對象的有序集合。 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. 它基本上是一個(gè)數(shù)組的替代。 但是,與數(shù)組不同,您可以使用索引在指定位置從列表中添加和刪除項(xiàng)目,并且數(shù)組會(huì)自動(dòng)調(diào)整大小。 它還允許動(dòng)態(tài)內(nèi)存分配,添加,搜索和排序列表中的項(xiàng)目。 |
| Hashtable | It uses a?key?to access the elements in the collection. 它使用一個(gè)鍵來訪問集合中的元素。 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. 當(dāng)您需要通過使用鍵訪問元素時(shí)使用散列表,您可以標(biāo)識(shí)有用的鍵值。 散列表中的每個(gè)項(xiàng)都有一個(gè)鍵/值對。 該鍵用于訪問集合中的項(xiàng)目。 |
| SortedList | It uses a?key?as well as an?index?to access the items in a list. 它使用一個(gè)密鑰以及索引來訪問列表中的項(xiàng)目。 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. 排序的列表是數(shù)組和哈希表的組合。它包含可以使用的鍵或索引訪問的項(xiàng)的列表。如果您訪問使用索引的項(xiàng)目,它是一個(gè)?ArrayList,和如果你訪問項(xiàng)目使用一把鑰匙,它是一個(gè)哈希表。項(xiàng)的集合總是按關(guān)鍵值排序的。 |
| Stack | It represents a?last-in, first out?collection of object. 它表示對象的后進(jìn)先出的集合。 ? 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. 當(dāng)您需要項(xiàng)目的最后進(jìn)入,首先訪問時(shí)使用。 當(dāng)您在列表中添加項(xiàng)目時(shí),稱為推送項(xiàng)目,當(dāng)您刪除它時(shí),它被稱為彈出項(xiàng)目。 ? |
| Queue | It represents a?first-in, first out?collection of object. 它表示對象的先進(jìn)先出集合。 ? 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. 當(dāng)您需要項(xiàng)目的先進(jìn)先出訪問時(shí)使用。 當(dāng)您在列表中添加項(xiàng)目時(shí),它被稱為enqueue,當(dāng)您刪除項(xiàng)目時(shí),稱為deque。 |
| BitArray | It represents an array of the?binary representation?using the values 1 and 0. 它表示使用值1和0的二進(jìn)制表示的數(shù)組。 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. 它用于需要存儲(chǔ)位但不提前知道位數(shù)。 您可以通過使用從零開始的整數(shù)索引來訪問BitArray集合中的項(xiàng)目。 |
?
?
?
VB.Net - 函數(shù)
?
過程是一組調(diào)用時(shí)一起執(zhí)行任務(wù)的語句。執(zhí)行該過程之后,控制返回到調(diào)用過程的語句。 VB.Net有兩種類型的程序:
-
Functions
-
Sub procedures or Subs
函數(shù)返回一個(gè)值,而Subs不返回值。
?
定義函數(shù)
函數(shù)語句用于聲明函數(shù)的名稱,參數(shù)和主體。 函數(shù)語句的語法是:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType[Statements] End Function-
Modifiers?修飾符?:指定函數(shù)的訪問級(jí)別;可能的值有:公共,私有,保護(hù),朋友,關(guān)于保護(hù)超載,重載,共享和陰影朋友和信息。
-
FunctionName:表示該函數(shù)的名稱
-
ParameterList?參數(shù)列表?:指定參數(shù)的列表
-
ReturnType?返回類型?:指定變量的函數(shù)返回的數(shù)據(jù)類型
?
示例
以下代碼片段顯示了一個(gè)函數(shù)FindMax,它接受兩個(gè)整數(shù)值,并返回兩個(gè)較大者。
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?
函數(shù)返回值
在VB.Net中,函數(shù)可以通過兩種方式向調(diào)用代碼返回一個(gè)值:
-
通過使用return語句
-
通過將值分配給函數(shù)名
?
下面的例子演示了如何使用FindMax函數(shù):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Max value is : 200?
遞歸函數(shù)
一個(gè)函數(shù)可以調(diào)用自身。 這被稱為遞歸。 以下是使用遞歸函數(shù)計(jì)算給定數(shù)字的階乘的示例:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320?
參數(shù)數(shù)組
?
有時(shí),在聲明函數(shù)或子過程時(shí),您不確定作為參數(shù)傳遞的參數(shù)的數(shù)量。 VB.Net param數(shù)組(或參數(shù)數(shù)組)在這些時(shí)候來幫助。
以下示例演示了這一點(diǎn):
?
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
The sum is: 2938?
傳遞數(shù)組作為函數(shù)參數(shù)
您可以在VB.Net中將數(shù)組作為函數(shù)參數(shù)傳遞。 以下示例演示了這一點(diǎn):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Average value is: 214.4?
?
?
VB.Net - Sub過程(子程序)
?
正如我們在上一章中提到的,Sub過程是不返回任何值的過程。 我們在所有的例子中一直使用Sub過程Main。 到目前為止,我們已經(jīng)在這些教程中編寫控制臺(tái)應(yīng)用程序。 當(dāng)這些應(yīng)用程序開始時(shí),控制轉(zhuǎn)到主子程序,它反過來運(yùn)行構(gòu)成程序主體的任何其他語句。
定義子過程
Sub語句用于聲明子過程的名稱,參數(shù)和主體。 Sub語句的語法是:
[Modifiers] Sub SubName [(ParameterList)] [Statements] End Sub-
Modifiers?修飾符?:指定過程的訪問級(jí)別;可能的值有:Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
-
SubName?子名?:表示該子的名字
-
ParameterList?參數(shù)列表?:指定參數(shù)的列表
示例
?
以下示例演示了子過程CalculatePay,它接受兩個(gè)參數(shù)小時(shí)和工資,并顯示員工的總工資:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Total Pay: $250.00 Total Pay: $800.00 Total Pay: $825.00?
按值傳遞參數(shù)
這是將參數(shù)傳遞給方法的默認(rèn)機(jī)制。 在這種機(jī)制中,當(dāng)調(diào)用方法時(shí),為每個(gè)值參數(shù)創(chuàng)建一個(gè)新的存儲(chǔ)位置。 實(shí)際參數(shù)的值被復(fù)制到它們中。 因此,對方法中的參數(shù)所做的更改對參數(shù)沒有影響。
?
在VB.Net中,可以使用ByVal關(guān)鍵字聲明引用參數(shù)。 下面的例子演示了這個(gè)概念:
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200它表明,雖然它們在函數(shù)內(nèi)部已更改,但值中沒有變化。
?
通過引用傳遞參數(shù)
引用參數(shù)是對變量的存儲(chǔ)器位置的引用。 當(dāng)您通過引用傳遞參數(shù)時(shí),與值參數(shù)不同,不會(huì)為這些參數(shù)創(chuàng)建新的存儲(chǔ)位置。 參考參數(shù)表示與提供給該方法的實(shí)際參數(shù)相同的存儲(chǔ)器位置。
?
在VB.Net中,可以使用ByRef關(guān)鍵字聲明引用參數(shù)。 以下示例演示了這一點(diǎn):
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?
當(dāng)上述代碼被編譯和執(zhí)行時(shí),它產(chǎn)生了以下結(jié)果:
Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 200 After swap, value of b : 100?
?
?
未完待續(xù),下一章節(jié),つづく
?
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的VB.NET 教程_02_常见对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fabric shim安装合约_hype
- 下一篇: String(byte[] bytes,