Chương I. AP TRINH HUONG DOI TUQNG TRONG VB.NET 11G iệu + VB.Net là một ngôn ngữ lập trình hường đổi tương (OOP object-oriented programming) + lrong lập trình hưởng đối tương cổ hai khấi niệm quan trọng là elass(lớp) và ‘object di trgmg). + Class 1a mt ting quit hoa (bd bat de chi ted) eta et hue the trong thể giới thực hoặc do, LLL Class la gi? + Cluss thường được mô tả như là một mô hình họäc thiết kế mô hình qua đó Object (dỗi tượng) có thể được tạo + OOP thươ ding class dé bao boc (che chỉ ti encapsulate) cba instance xariables (dữ liệu) và method (phương thức) 1. + Giả xử ta cần "cải đặt” các hình chữ nhật trong một chương trình.
Ta sẽ phẩntích tìm ra những thuộc tỉnh và hành động chung nhất mà một hình chữ nhật nối shúng phải có. Tạ sẽ "bao bọc”."che giấu chỉ tiết” thuộc tỉnh và hành động này trong mat lp Class Rectangle Class Rectangular [Height As Double Width As Double _place As Integer y_place As Integer Ku SetHeight(value As Double) hub SetWidth(value As Double) tunction Area() As Double unction Perimetter() As Double Phương thúc Sụb MoveTo(X As Inleger.Y As Integer) tub Draw(LineColor As Inleger.BackColor As Integer) Sub IncementSize( wBias As Double.hBias As Double Khởi tạo đối tượng. Sau khí khai bảo một Class. chúng ta có thể khởi tạo (instantiate) các đổi tương, từ nó, Các đối tượng có thể truy cập và sử dụng các thành viên (dữ liệu.
phương thúc) cỗ aceess modifier là Publie. Lập hợp các thánh viên di fi và phương thức Publie gọi là "giao điện” của một lớp. Cluss là khuôn mô hình tạo nên đối ương. Classis ao bọc cả dữ liệu (instanee variable.
data member,property. lẫn hành động (method.) “Có thể khởi tạo các đổi tương thật sự từ các Class đã dược khai báo. Các đổi tương là mình dụ (instanee) của một class có thể truy cập và thực hiện. ắc thành viên (dữ liệu phương thie.) ¢6 acess modifier public.
Class é{s Objects Giống như Khuôn lâm bánh: Những cải bánh thất sur Hình lì 1. Khai báo lớp VB.net [Private|Protected|Public] Class <Tén Class> Biển thể hiện + [Private|Protected|Public] mtenbien As <kiểu dữ liệu> “Thuộc tính (Property) + [Private[Protected|Publie] Property ten Thuoetinh() As < kigu di liu Truy xuất gi trị của thuộc ính (truy xuất đến gi tr của biển) Get » Return mtenbien End Get — "Gần trị cho thuộc tính tức giá trị cho biển Set (ByVal Value As String) » mtenbie End Get + End Property Phương thức (Method) + [PrivateProtected|Publie] Sub <tén thu tye>({<ds ede tham s6>)) + End Sub + Hoặc + [Pris tc|Protected|Public] Function <tén him>(|<ds cae tham sé>|) Return <gia i> + End Funi + End Class 1.3 Bài Toán: Cần thiết kế I lớp tượng trưng 1 thời điểm CTime 1.1 Xác định các tập thực thể cần thiết kế. Mùi thời điểm cụ thể (1:30:20).2 Xác định các thuộc tính (cần thiết, chung) của các thực thể.Second= 16 22:0:1 9 Hour=22,Minute=0,Second=1 1. (Thiết kế Class CTime.
a "Khai báo các instance variables “Trờu tượng hóa là quá trình trờu tượng những cái chưng nhất.4 Xác định construetor(phương thức xây dựng) và các phương thức khác liên quan t6i thiét Lap gid trj cho instance variables. Mỗi Class có một hoặc một i constructor: Là phương thức xây dựng. được gọi một cách tự động khi một đối tương được khởi tạo từ Class Dũng để khởi tạo (instantiate) đổi tượng cho class Thiết lập giá trị ban đầu cho cde instance variables, Ôn oe Publ Sub New) CN. hme Sata ge, Del Pai Seth Mane) End Sub ub biel minute Ae rng?) End Sub Phe SubsetSecon&Vloncond htntoge) End Sub Hình L3 1.5 Xác định các hành động có thể thực thi với thực thê,đối tượng.
Public Class CTimevi Public Function toStandardTime() As String Public Funetion toUniverslTime() As Sting Hinh 14 1. Sử dụng lớp trong các đổ án khác. =_ Biển dịch lớp thành tập tin thu vign ‹dH = _ Lâm thễ não sử dụng class trong các ứng dung? Server Client inh 15 1.7 Khởi tạo một đối tượng từ một class + Cú pháp: Dim anObject As New ClassName( -Jumei Vidi: Hinh 1.6 Minh họa các phương thức.setHour(15) ⁄ ati + Gol aTime. Thực thi kiểu dữ liệu trừu tương Time với Clas + Sự tách biệt mình bạch giữa "phí sử dụng client” và "phía cung cấp server" làm, cho chương trình: Mềm dẻo, nh hoatdé thay d6i hom, Vige ái sử dụng các class cho phép RAD (Rapid Application Development) lam ting ki tăng sản x ft (productivity).
Hệ thống chương trình là sự tương tác của các Objet độc ip hoat ding dũngdễ lập trình, báo tì và gỡ rỗi + _ Sự tách biệt mình bạch giữa "phía sử dụng lien và "phía cụng cắp srxer" làm, cho chương trình + Mam dễo nh họađễ thay đổi hơn. + Vige ải sử đụng các class cho phép RAD (Rapid Application Development) lim ting kha nding sin xuit (productivity), 1S Hoat vi Class. “Các thành viên (dữ liệu & phương thức) của một Class có hoạt vì Cluss và có thể được truy cập bởi các thành viên khác của Class. “Các thành viên Publie có thể được tham chiều từ các đổi tương eta Class, + _ Các biển của các method cỏ họat vi cục bộ trong method (block scope).
Truyc các thành viên. + _ Nỗ lực từ một đối tương khởi tạo từ một Class truy cập vào thành viên Private ua Class sé gay ra một lỗ lập trình, VD: Trong Client sir dung Class Time Dim aTime As Time = few Time() aTimemHour=7. “gay ra lỗi ‘Tom tit Access Modifier. 16 Constructor (Phương thức khởi tạo ) Chúng ta dùng Constructor để khởi tạo giá trị cho cắc instanee variable, Constructor ty động được gọi (invoke) khi có một đổi tượng được khởi tạo.
Nếu không cỏ construetor nào trong khai bảo của Clas thị VB.NET s@ ding «onstruetor mặc định (defalut constructor) va khai tạo giả trị ngằm định cho các instance variable, 1. 1 ads 6i 'onstructor (Overload construetor. ) Trong một Class. có thể có nhiều constructor (averloaded constructors) cung, sắp nhiễu cách đ khối ạo đối tượng, (Cae consrutor có cùng tên New chỉ khác nhau danh sich các tham số, Các conamiclor là Sub và không trí về gỉ ea Túy thuộc vào danh sách đổi số cung cấp lúc khởi tạo đổi tượng.NET sẽ chọn construelor thích hợp, 2 VíDụ Fig, Ro: CTime2.vb Represents time and contains overloaded constructors, Class CTime? 4.
“Ucelare Integers for hour, minute and second vate mllour As Integer ‘0-23 vate mMinute As Integer "0 - 59 vate mSecond As Integer " 0 - 59. “constructor initializes each variable to zero and 10.” ensures that each CTime? object stars in consistent tate 1. Publie Sub New) 12.End Sub, 14° Cime2 constructor: hour supplied: 15." minute and second default to 0 16, Publie Sub New(ByVal hourValue As Integer) 17.Setlime(hourValue) 18, End Sub‘ New 19." Cig constructor: hour and minute supplied: 20," second detaulted to 0 21. Publi Sub New(ByVal hourValue As Integer.
22, ByVal minuteValue As Integer) 28. SetTimethourValue, minuteValue) 24, End Sub" New 25." CTime2 constructor: hour, minute and second supplied 26. Publie Sub New(ByVal hourValue As Integer. ByVal minuteValue As Integer, ByVal secondValue As Integer) 28, SetTime(hourValue, minuteValue, secondValue) 30." CTime? constructor: another CTime2 object supplied 31.
Public Sub New(By Val timeValue As CTime2) 33. SetTimetimeValue mHour, tìmeValue." set new time value using universal time 35." pertrm validity checks on data; 36." set invalid values to zero 37. Public Sub Set ime(Optional ByVal hourValue As Integer 38. Optional ByVal minuteValue As Integer ~ 0, 39.
Optional ByVal secondValue As Integer = 0) 40." perform validity checks on hour, then set hour 4L-If (hourValue >= 0 AndAlso hourValue < 24) Then ml our = hourValue Else mtfour= 0 43.’ perform validity checks on minute, then set minute 44.1F (minuteValue 0 AndAlso minuteValue < 60) Then Minute = minuteValue Else mMinute = 0 48." pertonm validity checks on second, then set second 47.1f sccondValue >= 0 AndAlso secondValue < 60) Then mSecon secondValue 48, Else mSecond = 0 49.End Sub' SetTime SI." convert String to universal-time format $2. Public Fun ion ToUniversalString() As 53.End Function ' ToUniversalString 55." convert to String in standard-time format '56,Public Function ToStandardString() As String 51.Dim suffix As String =" P 58, im format As String = "{0):(1:D2)=(2:D2)" ‘59. Dim standardHlour As Integer 60," determine whether time is AM or PM. If mllour< 12 Then suffix= " AM" 62.
convert from universal-time format to standard-time format 64. Else standardHtour 'Hour Moá 12 66. Return String Format(format, standardHour, mMinute, mSecond) & suffix ind Function * ToStandardSiring End Class’ CTime2 L.vb Demonstrates overloading constructors.Forms 4, Module mod TimeTest2 ‘ub Main() 6, ‘use overloaded constructors Dirm time! As New CTime2() 8. Dim time? As New CTime2(2) 9.
Dim times As New CTime2(21,34) 10, Dim times As New CTime2(12, 5.42) MD timeS AsNew CTime2(27, 74,99) Dim time6 As New CTime2(timed)’ use timed as initial value 13. Const SPACING As Integer = 13 spacing between output text 14." invoke time! methods im output As String ~ "Constructed with: * & vbCrI.1 a _ timel; all arguments defaulted” & vbCrL& _ 17." invoke time? methods 20, output &= vbCrLf & _ ime2: hour specified; minute and second defaulted” & _ 22.VoLniversalString() & vbCrLf& Space(SPACING)& _ 24-time?:FoStandardString) invoke time3 methods 26, output &= VOCHLE& 27." time: hour and minute speci sd: second defaulted” & _ 28." invoke timed methods 31.output vbCrLf & - med: hour. minute and second specified” & _ 33. vbC#LL& Space(SPACING) & times.
vbC#L & Space(SPACING) & timet." invoke timeS methods 1X6. output &= vbCHL ER _ ¥7. minute and second specified” & 38." invoke time6 methods 4 output &= vbCHLER + time: Time2 object timed speci " & vOCrLI & 4 Space(SPACING) & time6. ToStandardString() 45 MessageBox,Show(ourput 46.
“Demonstrating Overloaded Construct 4 End Sub’ Main 48 End Module‘ modTimeTest2 Demonstrating Overloaded Constructors [XÌ Constructed with: ‘ume1: all arguments defaulted 0:00:00. 12:00:00 AM time2: hour specified; minute and second defauited 2:00:00 2:00:00 AM 3: hour and minute specfied;second defauted. 21:34:00 9:34:00 PM time4: hour, minute and second specified 12:25:4 12:25:42 PM time5: hour, minute and second specified 0:00:00 12:25:42 PM Hin 1 Đùng overloaded Constructors * use overloaded constructors Dim time} As New CTime2() > 0 tham sé duge goi Dim time? As New CTime2(2) > | tham sé được gọi Dim time} As New CTime2(21, 34) > 2tham sé duge gọi Dim timed As New CTime2(12, 25,42) > 3 tham số được gọi Dim times As New CTime2(27, 74.99) > 3 tham số được gọi Dim time6 As New CTime2(times) > Copy "use times as initial value Minh hga overloaded constructors Tạo ra một Console appication Test - Thêm vào ứng dụng Test class CTimev2 với 5 construetors có chữ kí khác nhau. + Viễt code trong module của Test sử dụng class trên.
Nhược điểm của instance variables. + Aeeess Modifier của các instance variables nên là Private.Khỏng thể truy cập &: cắn giả trị cho các instance variables ciia mot déi tượng một cách trực tiếp. + Chang ta ao ước có thể dùng cú pháp anObjectinstanee, variable để truy cập Sede sắn gỉ 1. Thuộc tính của Class.
Net khắc phục điều này bằng khải niệm Property(thuge tinh). Mot property gắn với một instance variable và cung cấp: Get accessor cho phép truy cập giá trị Set accessor cho phép thiét lip gia r. mHour Hour mMinute » Minute mSecond ~ Second iT HU VIEN 19 ‘A anObj.Hour=x mHour-x nObj.