Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6 ppt

50 479 0
Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P6 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

End Sub Going from a hexadecim al value t o a Long value is m ore com plicated for a couple of reasons. First , t here is no built - in funct ion. Second, hexadecim al num bers need to be converted on a charact er- by-charact er basis t hat reflect s the ch ar act er’s posit ion in t he hexadecim al num ber. Th is t ask is furt her com plicat ed by that fact that charact ers go outside t he decim al range of 0 through 9 t o t he hexadecim al range of 0 t hrough F. The following sam ple perfor m s a check t o verify that t he hexadecim al st ring value doesn’t exceed t he m axim um Long value. The hex representat ion for t he m axim um Long value is 7FFFFFFFFFFFFFFF. Aft er perform ing a bound check for t he m ax im um hexadecim al value, t he Convert Hex ToLng pr ocedure st art s a loop t hat it erat es t hrough successive charact ers in t he hexadecim al num ber. St art ing at the far right charact er, t he loop evaluates each ch aract er. The evaluat ion m ultiplies t he hex charact er’s decim al value by a power of 16. The pow ers range in value from 0 for the far right charact er t o up to 15 for t he sixt eent h hex charact er ( if t here is one) . When the Convert HexToLng procedur e finish es looping t hrough the charact ers in the hexadecim al num ber, t he pr ocedur e presents a m essage box wit h t he decim al value of t he hexadecim al num ber in Text Box1. Private Sub Button4_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button4.Click ’Call program to convert a hexadecimal number to ’a Long number. ConvertHexToLng() End Sub Sub ConvertHexToLng() ’Assign TextBox1 contents to hexStr. ’Dim strValue As String = TextBox1.Text Dim hexStr As String = TextBox1.Text ’If hexStr greater than 7FFFFFFFFFFFFFFF, then abort. Dim hexchars As Integer = Len(hexStr) If (hexchars = 16 And hexStr.Chars(0) > “7”) Or _ hexchars > 16 Then MsgBox(“Hex values beyond 7FFFFFFFFFFFFFFF “ & _ “generate an exception. Enter a smaller “ & _ “hex value.”) Exit Sub End If ’Variable lnghexstr stores long of hex string in TextBox1, ’and i is a loop counter value. Dim lnghexstr As Long Dim i As Integer ’Loop through characters to compute decimal equivalent ’of hex string. lnghexstr = 0 For i = 0 To hexchars - 1 Select Case Mid(UCase(hexStr), hexchars - i, 1) Case “0" lnghexstr += CLng(0 * (16 ^ i)) Case “1" lnghexstr += CLng(1 * (16 ^ i)) Case “2" lnghexstr += CLng(2 * (16 ^ i)) Case “3" Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. lnghexstr += CLng(3 * (16 ^ i)) Case “4" lnghexstr += CLng(4 * (16 ^ i)) Case “5" lnghexstr += CLng(5 * (16 ^ i)) Case “6" lnghexstr += CLng(6 * (16 ^ i)) Case “7" lnghexstr += CLng(7 * (16 ^ i)) Case “8" lnghexstr += CLng(8 * (16 ^ i)) Case “9" lnghexstr += CLng(9 * (16 ^ i)) Case “A" lnghexstr += CLng(10 * (16 ^ i)) Case “B " lnghexstr += CLng(11 * (16 ^ i)) Case “C" lnghexstr += CLng(12 * (16 ^ i)) Case “D" lnghexstr += CLng(13 * (16 ^ i)) Case “E" lnghexstr += CLng(14 * (16 ^ i)) Case “F" lnghexstr += CLng(15 * (16 ^ i)) End Select Next i ’Display long value for hex string. MsgBox(“Long value for text box equals:” & vbCrLf & _ lnghexstr.ToString) End Sub I nheriting Cla sses Classes are great because t hey package blocks of Visual Basic code for easy reuse. Class inherit ance m ult iplies t hat cor e benefit of classes by let ting one class inherit t he propert ies, m et hods, and events of anot her class. I nherit ance for cust om classes is new t o Visual Basic program m ers wit h Visual Basic .NET. This sect ion begins wit h an overv iew of design issues and keywords for im plem ent ing class inher it ance. Next I cover a couple of sam ples that dem onst rat e the synt ax for im plem enting inher it ance w it h different keyw ords. At t he sect ion’s close, you will discover a discussion of overloading. This feat ure can m ake one m ethod or propert y wit hin a class easily accept m any different t ypes of value inputs. I nst ead of building capabilit ies int o applications by layering one class on t op of anot her or m anually coding a class to t est m ult iple value t ypes and then respond appropriat ely t o t he input value t ype, t he Overloads keyw ord expands the capabilit ies of a single class. I cover t he Overloads keyw ord in t his sect ion because of it s resem blance t o the Over riding keyword— one of t he keyw ords for m anaging inherit ance— and because Over loads widens t he capabilit ies of a class m uch as inherit ance can. Ov er vie w of I nher it a nce Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. I nherit ance is for classes. I t let s one class inherit t he propert ies, m ethods, and events of anot her class. My discussion of inherit ance focuses on propert ies and m et hods t o sim plify t he present at ion. ( See t he “Program m ing Events” sect ion lat er in t his chapter for m or e on m anaging class event s.) When Class B inherit s Class A, Class B can offer the sam e m et hods, propert ies, and event s of Class A. I n addit ion, Class B can offer new propert ies and m et hods as well as m odified versions of t he properties and m et hods in Class A. Visual Basic developers didn’t have t his capability for cust om st and-alone classes wit h v ersions of Visual Basic prior t o t he .NET v ersion. Therefore, it is nat ur al t hat y ou need t o learn som e new concepts and sy nt ax t o take advantage of inherit ance. We can st art our new inherit ance vocabulary by r eferr ing t o t he inherit ed class as t he base class. The class t hat inher it s a base class is a derived class. When one class inherit s fr om anot her class, the der ived class m ust cont ain a declaration st at ing from which class it inherit s propert ies and m et hods. Visual Basic .NET uses an I nherit s st atem ent t o m ake t he declarat ion. The I nherits st at em ent takes as its argum ent t he nam e of t he base class. You can have j ust one class nam e as the argum ent for I nherit s. Therefore, a class can inherit fr om at m ost one ot her class at a tim e. I f t he der ived class adds any new m et hods, it can offer t he m et hods of t he base class along wit h it s ow n new m et hods. I n addit ion t o offer ing new m et hods, t he derived class can offer m odified im plem entat ions of one or m ore m et hods from t he base class. Anot her new inherit ance t erm in Visu al Basic .NET is polym orphism . I t describes t he abilit y of a der iv ed class t o change t he im plem entat ion of a base class m em ber, su ch as a propert y or a m et hod. An applicat ion can inst ant iat e inst ances for a derived class and it s base class. I n t his way, t he applicat ion can invoke an unm odified m et hod from a base class and an updat ed m et hod wit h t he sam e nam e from a deriv ed class. I n order for Visual Basic .NET t o m odify a base class m ethod in a der ived class, your class m et hods require special keyw ords. Fir st , t he base class m ust m ark t he m et hod nam e w it h the Overridable keyword, such as in the following code: Class MyBaseClass Overridable Function One () As Double ’Code for returning a value. End Function End Class I n addit ion t o a keywor d in t he base class, you need a cor responding keyword, Overrides, in the der ived class. This k eyword m ust be applied t o a m et hod in t he der iv ed class wit h t he sam e nam e as t he one in t he base class whose im plem entat ion y ou want t o ch ange. For exam ple Class MyDerivedClass Inherits MyBaseClass Overrides Function One () As Double ’New code for returning a value. End Function End Class As you can see, im plem ent ing polym orphism requir es planning. That is, you m ust m ark t he base class t hat you want over ridden in derived classes w it h t he Overridable key word. You m ust also sy nchr onize m ethod nam es bet ween t he base and derived classes. The m et hod nam es wit hin a class— eit her base or der iv ed— should generally be dist inct . I n general, you should also keep t he m et hod and propert y nam es dist inct bet ween base and derived classes. Using t he sam e nam e for a m et hod or a propert y in bot h base and derived classes has a special m eaning that we will consider short ly. I n order for a der ived class to refer back to a m et hod or propert y in a base class, you need t o use t he special MyBase keyw ord. You will typically use t he My Base keyw ord wit hin a funct ion in a der ived class t hat ov errides an ident ically nam ed Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. funct ion in a base class. You can also use t he MyBase keyw ord t o set and get propert y values for a base class from a derived class. Then you can use the MyBase k eyword to invoke a m et hod w it h t he values that you passed t o the base class. For exam ple, MyBase.One() in a derived class invokes t he One m et hod in the base class. The Shadows keyword can apply to propert ies and m et hods in a derived class. This keyw ord essent ially block s the availabilit y of identically nam ed propert ies and m et hods in a base class. I n a sense, t he Shadows keyword for a propert y or m et hod in a derived class cast s a shadow over an ident ically nam ed property or m et hod in a base class. The Shadows keyw ord is m ore flexible and pow erful t han the Ov erridable/ Ov err ides keyw ords. For exam ple, t he Ov er ridable/ Overrides keyw ords apply only t o m et hods im plem ented wit h sub procedures or funct ion procedures. The Shadow s keyword apples t o m et hods as well as propert ies. I n addit ion, you can shadow a m et hod in a base class w it h a property in a derived class. The Shadows k eyword rem oves t he dependence of a derived class on an ident ically nam ed obj ect in a base class. Th is insu lat es t he derived class from any changes t o t he base class t hat could inadvert ent ly cause an er ror in t he derived class. The Overridable/ Ov errides k eywords don’t offer t his prot ect ion for a der ived class from ch anges m ade in a base class. The Overloads keyw ord isn’t st rictly an inher it ance topic, but t his keyword pert ains t o classes, and it s nam e is sim ilar to Ov err ides. I n addit ion, using t he Overloads keyword on a funct ion procedure, sub procedure, or propert y procedure can alt er t he behavior of t he procedure. How ever, t he Overloads keyw ord can apply t o m et hods or pr opert ies w it hin t he sam e class. A com m on use of t he Overloads k eyword is t o enable m ult iple versions of a funct ion procedure t o operat e as one. Each funct ion procedure in a set of overloaded funct ion procedures has the sam e nam e. However, t he argum ent types change for each funct ion procedure wit hin a set . Therefor e, one version of a m et hod can accept a st ring argum ent , but anot her version can accept a double dat a type as an ar-gum ent. The .NET Fram ework w ill aut om at ically invoke t he right funct ion procedure based on an input ’s dat a type! That ’s t he power of t he Overloads keyw ord. An I nheriting a nd Over riding Sa m ple Any Windows applicat ion applying class inherit ance will cont ain at least t hree units of code. You need t wo unit s of code for t he classes: one for t he base class and a second for t he derived class. A t hird unit of code is necessary t o inst antiat e one or m ore classes and invoke t he m et hods or m anipulat e t he pr ocedures in the der iv ed class or it s base class. I n a Windows application, y ou can inst antiat e classes and m anipulat e the inst ances from event procedures for but t ons on a form . One or m ore text boxes on a form can provide vehicles for users to specify input values as argum ents for m et hods and propert ies. The sam ple for t his sect ion is a Windows application t hat includes a form ( For m 1) wit h m ult iple butt ons and text boxes for users t o m anipulat e. The first sam ple uses But t on1 along wit h Text Box1 and Text Box2. Click ing But t on1 launch es an event procedure that instantiat es a base class, Arit hm et icClass1 , and a derived class, Class1. The procedur e m anipulat es these class inst ances in various way s wit h input from t he ent ries in Text Box1 and Text Box2. I will det ail t he m anipulat ions by describing t he But t on1_Click event pr ocedure aft er discussing the code in t he Arit hm et icClass1 and Class1 classes. N ot e The sam ple for t his sect ion and the next two sect ions dem onst rat ing inherit ance with Visual Basic .NET all use t he Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. sam e solut ion, I nherit ingSam ple. You can double- click I nherit ingSam ple.sln in Windows Explorer to open t he solution in Visual St udio. To run t he applicat ion from Windows Explorer, invoke the I nheritingSam ple1.exe file. The filenam e for t he .ex e file ret ains the original nam e for the solut ion. Arit hm eticClass1 is a variat ion of t he st and- alone class in t he Arit hm et icClass proj ect discussed in t he “Cr eating and Using Class Refer ences” sect ion. This base class resides in t he I nherit ingSam ple solut ion. The code for t he base class follows. I t begins by specifying t wo writ e-only propert ies. Arit hm eticClass1 also sp ecifies two m et hods— bot h based on funct ion procedures. The Add2dbls m ethod follows direct ly from t he Arit hm et icClass present ed earlier in this chapt er; t he m et hod adds t wo values wit h a Double value t ype. A sub procedure im plem ent s this m et hod. The input for t he funct ion procedure is fr om the Writ eOnly propert ies, which sp ecify the double values t o add. A funct ion procedure im plem ent s the second m et hod, Add2dbls2, in Arit hm et icClass1. Using argum ents for the funct ion procedure elim inat es t he need to rely on propert ies t o specify t he values t o add. The Ov err idable k eyword appears at t he st art of the Add2dbls2 m et hod specificat ion. This m eans t hat anot her class inherit ing Arit hm eticClass1 can ov err ide t he code for t he m et hod t hat appears below . Public Class ArithmeticClass1 Private dbl1 As Double Private dbl2 As Double ’WriteOnly property named dblFirst. Public WriteOnly Property dblFirst() As Double Set(ByVal dblValue As Double) dbl1 = dblValue End Set End Property ’WriteOnly property named dblSecond. Public WriteOnly Property dblSecond() As Double Set(ByVal dblValue As Double) dbl2 = dblValue End Set End Property ’Add dbls. Function Add2dbls() As Double Return (dbl1 + dbl2) End Function ’Overridable version of Add dbls. Overridable Function Add2dbls2(ByVal MyNum1 As Double, _ ByVal MyNum2 As Double) As Double Add2dbls2 = MyNum1 + MyNum2 End Function End Class The code for Class1 has three m aj or sect ions; t he full list ing for t he class appears next . The first sect ion inherit s Ar it hm et icClass1. The I nherit s st at em ent m akes Class1 a der ived class wit h Arit hm et icClass1 as it s base class. Class1 can reference all t he propert ies and m et hods of Arit hm et icClass1 t hrough t he MyBase keyw ord. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The next sect ion in Class1 adds a new m et hod wit h t he Nt hPower funct ion. The funct ion com put es t he value of t he base value t o a power, such as 2 3 equaling 8. This funct ion accepts argum ent s for t he base and power variable values. The final sect ion of code in Class1 defines a new im plem ent at ion for t he Add2dbls2 m et hod init ially specified in t he base class. (See t he preceding code for Arit hm eticClass1.) The Overrides k eyword at t he beginning of the m et hod specificat ion in Class1 along w it h t he m at ching Overridable keyword for t he sam e m et hod nam e in Arit hm et icClass1 perm it s t he override. The new im plem ent at ion for t he Add2dbls2 m et hod doubles t he value com put ed in t he base class. The MyBase k eyword facilit at es t he refer ence back t o t he base class. The argum ent s passed to t he Add2dbls2 m et hod in Class1 transfer t o t he base class through t he argum ents in t he expression containing t he My Base k eyword. Public Class Class1 ’Class1 class inherits from ArithmeticClass1. Inherits ArithmeticClass1 ’Added method to complement inherited method ’from ArithmeticClass1. Public Function NthPower(ByVal base As Double, _ ByVal power As Double) As Double NthPower = (base ^ power) End Function ’The Add2dbls2 method in Class1 overrides the ’overridable Add2dbls2 method in ArithmeticClass1. Overrides Function Add2dbls2(ByVal MyNum1 As Double, _ ByVal MyNum2 As Double) As Double ’The following code calls the original method in the base ’class, and then modifies the returned value. Add2dbls2 = MyBase.Add2dbls2(MyNum1, MyNum2) * 2 End Function End Class The Click event for Bu tt on1, which appears nex t, begins by hiding som e cont rols that aren’t necessary for t his use of t he form . Then t he event procedure inst ant iat es Arit hm et icClass1 as t he arclass1 variable and Class1 as the c1 variable. The procedure uses t wo t ext boxes on t he form so t hat users can specify double values for the m ethods in t he classes. Because t he text box values require conversion t o m ake t hem Double values for t he procedures im plem ent ing t he m et hods, t he sam ple com put es t he conversion once and st ores t he result s in t wo variables w it h a Double value specificat ion. Aft er concluding t he pr eceding pr elim inary st eps, t he event procedure st art s com put ing and displaying result s. I nit ially t he procedure passes the Double values saved in num 1 and num 2 t o the propert y procedures assigning values to the dblFirst and dblSecond propert ies in Arit hm et icClass1. Next t he procedure inv okes t he Add2dbls m et hod w it hin t he Arit hm et icClass1 and co- nvert s the outcom e t o a st ring wit h t he ToSt r ing m et hod for display in a m essage box. Aft er a user clears t he m essage box from t he screen, t he event procedure invokes t he Nt hPow er m et hod in Class1. Again, t he m essage box argum ent conv ert s t he num ber to a st ring for display. The last pair of MsgBox funct ions in t he event procedure inv ok es t he Add2dbls2 m et hod. The first m essage box displays t he Add2dbls2 m et hod out com e from it s base class im plem ent at ion ( in Arit hm eticClass1) . The procedure concludes by invok ing t he sam e m et hod from Class1. This result appearing in t he second m essage box w ill be t w ice as large as it s pr edecessor . This is because different funct ion procedures im plem ent the m et hod in each class. ( Cont rast the code for Add2dbls2 in t he t wo pr eceding class list ings. ) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ’Sample to demonstrate basic inheritance to add a ’new method or override an existing one. Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ’Hide unnecessary text controls. Button2.Visible = False Button3.Visible = False ’Instantiate objects based on the ArithmeticClass1 ’and Class1 classes. Dim arclass1 As New ArithmeticClass1() Dim c1 As New Class1() ’Declare num1 and num2 variables and assign values ’to the variables based on text box entries. Dim num1 As Double Dim num2 As Double num1 = CDbl(TextBox1.Text) num2 = CDbl(TextBox2.Text) ’Set properties and invoke the Add2dbls method from ’the ArithmeticClass1 class. arclass1.dblFirst = num1 arclass1.dblSecond = num2 MsgBox(arclass1.Add2dbls.ToString, , _ “Return from Add2dbls in ArithmeticClass1”) ’Invoke the NthPower method in Class1, which is a ’new method not in ArithmeticClass1. MsgBox(c1.NthPower(num1, num2).ToString, , _ “Return from NthPower in Class1”) ’Invoke the Add2dbls2 method for the ArithmeticClass1 ’and Class1 classes; the Add2dbls2 method in Class1 ’overrides the Add2dbls2 method in ArithmeticClass1. MsgBox(arclass1.Add2dbls2(num1, num2).ToString, , _ “Return from Add2dbls2 in ArithmeticClass1”) MsgBox(c1.Add2dbls2(num1, num2).ToString, , _ “Return from Add2dbls2 in Class1”) End Sub Figur e 9-7 su m m ar izes the r esu lt s. On t he left is the form aft er I enter ed values in bot h t ext box es and click ed Butt on1. Notice t hat Button2 and But t on3 aren’t t here; that ’s because t he Butt on1_Click event procedure m ade t hem invisible on t he form by set ting t heir Visible property t o False. The four m essage box es on t he right display t he resu lt s in t he order t hat the But ton1_ Click ev ent procedur e com put es t hem . The caption for each m essage box specifies t he source, including t he m et hod and t he class, for t he displayed r esult . Not ice in particular t he last t wo m essage boxes. These resu lt s in coordinat ion w it h t he list ing for the Butt on1_Click event pr ocedure docum ent and confirm how you can override a m et hod in a base class wit h a differ ent im plem ent at ion in a deriv ed class. Figure 9 - 7 . By cre at ing in st an ce s for bot h a b ase class an d a derived class, you can invoke m et h ods for both classe s, a nd som e of y ou r m e t hod references in a de rived class can over ride t hose in a base cla ss. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. A Sha dow ing Sa m ple As indicat ed in t he “ Overview of I nherit ance” sect ion, shadowing act s sim ilarly to ov erriding but is m or e flexible. Th e sam ple for t his sect ion dem onst rat es t he use of t he Shadows keyw ord. You can use t he Shadows keyword in a der ived class; doing so doesn’t require any corresponding changes t o a base class. The sam ple in the preceding sect ion required t he Overridable k eyword in t he base class for the Ov errides keyword in t he derived class t o function properly . The sam ple in t his sect ion uses t he TypeRef1 class t hat follows as t he base class. Not ice t hat t he list ing for TypeRef1 includes a propert y procedure for a property nam ed Value. The procedure includes bot h Get and Set clauses. This class is sim ilar t o t he TypeRef sam ple presented earlier in t his ch apt er. The sole dist inct ion bet ween TypeRef1 and TypeRef is t hat TypeRef1 com m ent ed out t he New m et hod. Recall t hat in t he prior sam ple using TypeRef, the New m et hod was helpful in set t ing an init ial value for a variable inst ant iat ed on t he class. Howev er, when you use a class as t he base class for an I nherit s st atem ent, t he base class cannot include a m et hod nam ed New. The inabilit y t o specify a New m et hod wit hin t he class isn’t m aj or because an applicat ion can assign a value t o a variable based on t he class im m ediat ely after inst antiat ing t he variable. Public Class TypeRef1 Private intLocal ’Intialize Value to myInput -- not permissible in ’inherited class. ’Public Sub New(ByVal myInput As Integer) ’ Dim Value As Integer = myInput ’ MsgBox(Value.ToString, , “in new”) ’End Sub ’Read/Write property named Value. Public Property Value() As Integer Get Return intLocal Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. End Get Set(ByVal Value As Integer) intLocal = Value End Set End Property End Class The shadow ing sam ple also relies on a second sam ple nam ed Class2. This class inherit s Ty peRef1, so Class2 is a derived class wit h Ty peRef1 as it s base class. Because TypeRef1 has j ust one property, Class2 m ust have a m em ber by t he sam e nam e if it is t o sh adow t he property procedure in TypeRef1. I specifically used t he term m em ber. This leav es open t he possibilit y of t he shadowing elem ent being eit her a property or a m et hod. The only r equirem ent is that t he shadowing elem ent hav e the sam e nam e as t he m em ber t hat it shadows. Alt hough t he following list ing for Class2 dem onst rates t he use of t he Shadows keyw ord, t he use of t his keyw ord is optional for im plem enting shadow ing. As y ou can see from the following list ing, t he shadow ing version of t he propert y procedure for Value in TypeRef1 adds 2 t o t he input . The original version of the property pr ocedure for the Value propert y in TypeRef m erely echoes t he input . Public Class Class2 ’Class2 inherits from TypeRef1 Inherits TypeRef1 Private intLocal ’Read/Write property named Value in Class2 ’shadows property with the same name in TypeRef1. Public Shadows Property Value() As Integer Get Return intLocal End Get ’New version adds 2 to initial input. Set(ByVal Value As Integer) intLocal = Value + 2 End Set End Property End Class Click ing But t on2 on For m 1 in t he I nherit ingSam ple solut ion launches an event procedure, which appears next . The procedure uses Butt on2 and Text Box1 ( along wit h it s label). Therefore, t he event procedure st arts by hiding t he ot her cont rols on the form . Next t he procedure convert s and copies the contents of Text Box1 t o num 1, which t he procedur e declares as an I nt eger variable. This value t ype specificat ion for num 1 is consist ent wit h t he Value propert y in TypeRef1 and Class2. After st oring t he convert ed t ext box entr y in a variable for t he event procedure, the procedure assigns t he value saved in num 1 t o t he Value propert y in TypeRef1 and Class2. Finally, a pair of MsgBox funct ions echoes the quant it y in the property. ’Sample to demonstrate shadowing with inheritance. Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click ’Hide unnecessary text controls. TextBox2.Visible = False Label2.Visible = False Button1.Visible = False Button3.Visible = False Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ’Instantiate objects based on the TypeRef1 ’and Class2 classes. Dim trclass1 As New TypeRef1() Dim c2 As New Class2() ’Declare num1 variable and assign a value ’to the variable based on the text box’s entry. Dim num1 As Integer num1 = CInt(TextBox1.Text) trclass1.Value = num1 c2.Value = num1 MsgBox(trclass1.Value.ToString, , _ “Return from Value property in TypeRef1”) MsgBox(c2.Value.ToString, , _ “Return from Value property in Class2”) End Sub Figur e 9-8 sh ows t he shadow ing sam ple. On t he left panel, y ou see t he t ext box and but ton for launch ing the event procedure. Not ice t hat t he t ext box cont ains the value 3. On t he right side, you see t he tw o m essage boxes cont aining t he echoed Value propert ies fr om Ty peRef1 and Class2. Alt hough t he input t o bot h propert ies was t he sam e, t he out put is different because t he one expression in Class2 is dist inct from it s count erpart for a shadowed pr opert y in TypeRef1. Figur e 9 - 8 . Sh adow in g m ak es it e asie r for a de rived class t o ret ur n a differe nt resu lt t ha n a prop er ty w it h th e sa m e na m e in a base cla ss. An Overloading Sa m ple Bot h overriding and sh adow ing are about doing m ore t hings w it h t he sam e m et hods and propert ies. The Overloads k eyword is one m ore exam ple of a keyw ord that sim plifies how y ou can do m ore w ith t he code in your sam ples. I n essence, it allows you t o construct a set of procedur es all of w hich have the sam e nam e but wit h different argum ent type specificat ions. When a user invokes a m et hod based on t he set of procedures, t he .NET Fram ework autom at ically det ect s the specific procedure that m at ches t he input dat a ty pe. You don’t hav e t o use the Overloads keyword in an inherit ance cont ext , but it can work wit h Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... why Microsoft upgraded it s support for handling run- t im e errors w it h Visual Basic NET Visual Basic 6 and ear lier v ersions of Visual Basic offer ed unst r uct ured err or handling w it h t he On Er ror st at em ent This st at em ent t ype t ransfers cont r ol wit hin a pr ocedur e t o anot her point wit h t he GoTo k eyword Most m oder n Visual Basic program s av oid t he use of t he GoTo st at... frmForm1 As New Form1() frmForm1.Show() Me.Close() End Sub Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Ex ce pt ion H a ndlin g for Ru n - Tim e Er r or s Visual Basic NET int r oduces an at t ract iv e new way of handling r un- t im e er rors based on st ruct ur ed ex cept ion handling Run- t im e er rors are er r ors t hat occur because a com put er isn’t ready t o pr... connect t o a SQL Ser ver inst ance t hat is t em porar ily off line, a r un- t im e error m ight be generat ed Your applicat ions can suffer from run- t im e er r ors even if your code is synt act ically perfect and your logic is im peccable All applicat ions hav e a suscept ibilit y t o run- t im e err ors, and it is t herefore im perat ive t o handle t hem efficient ly That ’s why Microsoft upgraded... for t racking run- t im e errors t hat t he NET Fram ewor k int roduces Run- t im e er rors t hrow, or raise, built - in except ions I n fact , one of t he especially at t ract ive feat ur es of st ruct ured except ion handling is t hat all r un- t im e errors raise a NET Fram ew ork except ion You can v iew t he full list of except ions by choosing Except ions from t he Debug m enu in Visual St udio... course, do any t hing else Visual Basic perm it s you t o program ) Be st Pr a ct ice s for Ex ce pt ion H a n dling Many developers pr efer t o elim inat e r un- t im e er rors befor e t hey happen Ot hers prefer t o let r un- t im e er rors happen t hat t hey can fix w it h a lit t le dat a validat ion or som e ot her m inor bit of pr ogram m ing I believ e t hat any real- w or ld solut ions are likely... program m at ically I nst ant iat e t im er inst ances from t he Syst em Windows.Form s nam espace Microsoft init ially int r oduced Windows t im ers w it h Visual Basic 1.0 Alt hough Serv er t im ers can r un in Windows For m s, t hey t arget t asks t hat don’t requir e a v isual int erface Nevert heless, Visual St udio NET let s you add Ser ver t im ers t o form s from t he Com ponent s sect ion of... a t hread from it s sy st em t hr ead pool for processing Elapsed ev ent s associat ed wit h Server t im ers By using any av ailable t hr ead, t he Server t im er ’s Elapsed event can be m issed by t he t hread associat ed wit h a Windows form Therefore, when y ou add a Server t im er t o a Windows form , Visual St udio NET aut om at ically set s t he t im er ’s SynchronizingObj ect propert y t o... within a class Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click ’Hide unnecessary text controls TextBox2.Visible = False Label2.Visible = False Button1.Visible = False Button2.Visible = False ’Instantiate Class3 with overloaded functions and declare Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark ’a variable with. .. Over loads k eyw ord Som et im es Microsoft can m ake life so sweet ! Figu re 9 - 9 Ove rloa din g au t om at ica lly m a t ch e s t h e p roce du re in vok e d t o t h e d at a t yp e of t h e ar gu m en t in a st a t e m e n t ca llin g a se t of ove rloa de d p roce du re s Pr ogr a m m in g Even t s An ev ent is a not ificat ion t hat som et hing happened As Visual Basic program m ers, you are well... built - in obj ect s, such as form s and but t ons Many int erm ediat e and advanced program m ers r egular ly creat e cust om classes t hat generat e cust om event s wit h pr ior v ersions of Visual Basic Adding ev ent s t o cust om classes allows obj ect s based on t he classes t o conv ey inform at ion back t o t he applicat ions t hat inst ant iat e t he obj ect s Please purchase PDF Split-Merge . Class A. Visual Basic developers didn’t have t his capability for cust om st and-alone classes wit h v ersions of Visual Basic prior t o t he .NET v ersion class. I nherit ance for cust om classes is new t o Visual Basic program m ers wit h Visual Basic .NET. This sect ion begins wit h an overv iew of design

Ngày đăng: 24/12/2013, 02:18

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan