Các bài tập Microsoft .NET 1 phần 5 ppsx

18 257 0
Các bài tập Microsoft .NET 1 phần 5 ppsx

Đ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

Các tập Microsoft NET 73 TextBox1.text = "Good morning!" Vì Property Text khơng cịn Default Property TextBox Overloading methods Một chức đa diện (Polymorphism) hùng mạnh VB.NET overload (quá tải, có mà cịn cho thêm) method Overloading có nghĩa ta dùng tên cho nhiều methods miễn chúng có danh sách parameters khác nhau, parameter dùng data type khác (td: method dùng Integer, method dùng String), số parameters khác (td: method có parameters, method có parameters) Overloading khơng thể thực cách thay đổi data type Return value Function Phải có parameter list khác Dưới thí dụ ta dùng Overloading để code hai Functions tìm data, cho String, cho Integer: Public Function FindData(ByVal Name As String) As ArrayList ' find data and return result End Function Friend Function FindData(ByVal Age As Integer) As ArrayList ' find data and return result End Function Để ý ta cho overloading Function phạm vi hoạt động (Scope on implementation) khác Trong thí dụ ta dùng Access Modifier Public cho Function đầu Friend cho Function sau Object Lifecycle Object Lifecycle (cuộc đời Object) dùng để nói đến Object bắt đầu hữu khơng cịn Sở dĩ ta cần biết rõ đời Object bắt đầu chấm dứt lúc để tránh dùng nó khơng hữu, tức chưa đời hay khuất bóng Các tập Microsoft NET 74 New method Trong VB6, Object thành hình Sub Class_Initialize executed Tương đương vậy, VB.NET ta có Sub New(), gọi Constructor VB.NET bảo đảm Sub New() CLR gọi Object instantiated chạy trước code Object Nếu Sub Class_Initialize Class Object VB6 khơng nhận parameter Sub New() VB.NET có nhận parameters mà cịn cho phép ta nhiều cách để gọi Sự khác biệt Constructors VB6 VB.NET quan trọng Tưởng tượng ta có Khn làm bánh bơng lan; khn Class cịn bánh làm từ khn Objects bánh lan Nếu ta muốn làm bánh bơng lan với lớp sơ-cơ-la mặt cơng tác gồm có hai bước: Dùng khn (Class) nướng Object bánh lan (dùng Sub Class_Initialize) Đổ lên mặt bánh lớp sô-cô-la (dùng class Public Sub ThoaSôcôla) Đến đây, chuyên tương đối ổn thỏa Bây giờ, khách hàng muốn bánh bơng lan dùng trứng vịt thay trứng gà ta chịu thua thơi, khơng có cách bảo Sub Class_Initialize dùng trứng vịt thay trứng gà lúc tạo dựng Object bánh lan Sub New() VB.NET nhận parameters nên nhận thị để dùng trứng vịt lúc nướng Object bánh lan Cái dạng đơn giản Sub New() mà ta dùng không pass parameter (trong trường hợp giống Sub Class_Initialize VB6) Ta code Sub New() Class sau: Public Class BanhBongLan Public Sub New() ' Code to initialise object here End Sub End Class Các tập Microsoft NET 75 Ta instantiate Object bánh lan sau: Dim myBanhBongLan As New BanhBongLan() Để cho Users có lựa chọn instantiate Object, ta code thêm Sub New khác, Sub dùng danh sách parameter khác Thí dụ: Public Class BanhBongLan Public Sub New() ' Code to initialise object here End Sub Public Sub New(ByVal LoaiTrung As String) Select Case LoaiTrung Case "Vit" ' Code for TrứngVịt here Case "Ga" ' Code for TrứngGà here End Select End Sub End Class Dùng tên method để implement nhiều methods khác gọi overload Đó trường hợp đa dạng (polymorphism) OO programming Trong thí dụ TrứngVịt TrứngGà hai loại Data Types khác ta dùng: Sub New (ByVal TrứngVịt As TrứngVịtDataType) để instantiate bánh TrứngVịt Sub New (ByVal TrứngGà As TrứngGàDataType) để instantiate bánh TrứngGà Các tập Microsoft NET 76 Như ta khỏi bận tâm với Select Case LoaiTrung dùng Sub New với parameter Trong VisualStudio.NET, ta dùng tên overloaded method, IntelliSense hiển thị để hướng dẫn ta đánh vào parameter list khác tùy theo method ta chọn Termination Trong VB6 Object bị huỷ diệt reference (chỗ dùng đến Object) cuối bị lấy Tức khơng có code khác dùng Object Object bị tự động huỷ diệt System giữ counter để đếm số clients dùng Object Cách hay chỗ counter trở thành Object bị huỷ diệt Ta nói có deterministic finalization, nghĩa ta biết rõ ràng Object biến Tuy nhiên, ta có hai Object dùng lẫn (gọi circular references), đến lúc chúng khơng cịn hoạt động nữa, chúng hữu nhớ Reference counter hai Objects không trở thành Nếu trường hợp xảy thường lần lần system khơng cịn memory nữa, ta gọi memory leak (bị rỉ nhớ) NET dùng phương pháp khác để quản lý chuyện Cứ chốc, program chạy để kiểm xem có Object khơng cịn reference để huỷ diệt Ta gọi Garbage Collection (nhặt rác) Ngay trường hợp hai Objects có circular references khơng có code khác reference hai Objects chúng huỷ diệt Có điều, cơng tác nhặt rác chạy in the background (phía sau hậu trường) với ưu tiên thấp, CPU rảnh rang, nên ta Object bị hủy diệt đến thật biến Ta nói có nondeterministic finalization Ta ép CLR nhặt rác code: System.GC.Collect() Tuy nhiên, ta làm việc kẹt q thơi Tốt hơn, ta duyệt lại design phép Objects hết xài ngồi chơi nhớ chờ đến lúc hủy diệt Các tập Microsoft NET 77 Dùng Dispose Method Nếu ta có Object dùng nhiều tài nguyên (resources) nhớ, database connection, file handle,.v.v ta cần phải thả tài nguyên sau Object không hoạt động nữa, ta cần implement Interface tên IDisposable với Implements keyword sau: Public Class TheClass Implements IDisposable Bạn phải viết code cho Sub Dispose giống sau: Private Sub Dispose() Implements IDisposable.Dispose ' Viết clean up code để thả tài nguyên End Sub Sau bạn phải viết code cho Client để gọi Dispose Method IDisposable interface Bạn cần phải dùng CType để cast Object Class gọi Dispose Dim objObject As New TheClass() CType (objObject, IDisposable).Dispose() Để lấy Reference đến Object (gọi Dereference Object) bạn dùng: myObject = Nothing Để ý ta khơng có dùng keyword Set VB6 Nhớ sau statement executed myObject khơng biến đợi Garbage Collector đến giải Thừa kế Thừa kế (Inheritance) khả Class đạt interface (giao diện) behaviours (tánh tình) Class có sẵn Cái q trình để làm nên việc gọi Subclassing Khi ta tạo Class thừa kế interface lẫn behaviours từ Class có sẵn tạo subclass Class nguyên thủy Người ta nói mối liên hệ is-a (là một), ý nói Class loại Class nguyên thủy Ta phân biệt mối liên hệ is-a với mối liên hệ has-a (có một) Trong mối Các tập Microsoft NET 78 liên hệ has-a, Object chủ làm chủ hay nhiều Objects tớ, Object tớ loại hồn tồn khác với Object chủ Để biểu diễn đặc tính Inheritance ta xét trường hợp công ty cung cấp Sản phẩm Dịch vụ Ta code Class cho Sản phẩm (ProductLine) Class cho Dịch vụ (ServiceLine) , riêng rẽ Nhưng thấy chúng có nhiều điểm tương đồng nên ta code Class gọi Món hàng (LineItem), inherit từ LineItem ProductLine ServiceLine LineItem có properties ID, Item, Price (giá) Quantity (số lượng) Nó có Public Function Amount (số tiền) Public Class LineItem Private mintID As Integer Private mstrItem As String Private msngPrice As Single Private mintQuantity As Integer Public Property ID() As Integer Get Return mintID End Get Set (ByVal Value As Integer) mintID = Value End Set End Property Public Property Item() As String Get Return mstrItem End Get Set (ByVal Value As String) Các tập Microsoft NET 79 mstrItem = Value End Set End Property Public Property Price() As Single Get Return msngPrice End Get Set (ByVal Value As Single) msngPrice = Value End Set End Property Public Property Quantity() As Integer Get Return mintQuantity End Get Set (ByVal Value As Integer) mintQuantity = Value End Set End Property Public Function Amount() As Single Return mintQuantity * msngPrice End Function End Class Để tạo Class ProductLine từ Class LineItem ta phải dùng Inherits keyword Mỗi Object ProductLine Object LineItem với ProductID Description ProductID ProductLine pass vào Sub New lúc Các tập Microsoft NET 80 instantiate Object ProductLine Còn Description ReadOnly property ProductLine Ta code Class ProductLine sau: Public Class ProductLine Inherits LineItem Private mstrDescription As String Public ReadOnly Property Description() As String Get Return mstrDescription End Get End Property Public Sub New(ByVal ProductID As String) Item = ProductID mstrDescription = "No description yet" ' Default description ' Viết code để đọc chi tiết Product từ Database ' có Description Product End Sub End Class Statement Inherits LineItem khiến ProductLine thừa kế interface behaviours LineItem Do ta code Sub BtnProduct_Click để hiển thị chi tiết ProductLine Listbox sau: Protected Sub BtnProduct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnProduct.Click Dim pl As ProductLine pl = New ProductLine("P1234") ListBox1.Items.Add("ProductItem:" & pl.Item) ListBox1.Items.Add("Description: $" & pl.Description) Các tập Microsoft NET 81 End Sub Trong code bên ta dùng property Item Class LineItem lẫn property Description Class ProductLine Cả hai property ProductLine SubClass LineItem Giống vậy, ServiceLine có ghi ngày cung cấp service Ta code Class ServiceLine sau: Public Class ServiceLine Inherits LineItem Private mdtDateProvided As Date Public Sub New() ' Make as default number of services of this kind for invoice Quantity = End Sub Public Property DateProvided() As Date Get Return mdtDateProvided End Get Set (ByVal Value As Date) mdtDateProvided = Value End Set End Property End Class Một lần ta dùng Statement Inherits để nói ServiceLine SubClass LineItem Ta thêm property DateProvided vào interface thừa kế từ Class LineItem Các tập Microsoft NET 82 Bài Những chức Đối Tượng VB.NET (phần III) Dùng OO VB.NET Ngăn cản Thừa kế Bình thường (By default) class dùng làm base class để từ ta thừa kế Nhưng đơi ta không muốn cho thừa kế từ Class đó, để làm việc ta dùng keyword NotInheritable declare class: Public NotInheritable Class KhôngCon End Class Khi ta dùng keyword NotInheritable khơng class dùng keyword Inherits để tạo subclass từ class Thừa kế Phạm vi hoạt động Khi ta dùng đặc tính thừa kế để tạo SubClass class có đủ methods, propertỉes variables với Access Modifier Public hay Friend SuperClass Bất thứ declared Private SuperClass SubClass khơng thấy hay dùng Có ngoại lệ New method Các Constructor methods cần phải implemented (định nghĩa) lại SubClass Một chốc ta bàn vào chi tiết điểm Để làm sáng tỏ vấn đề SubClass dùng Class Members SuperClass, ta thử code lại Function Amount LineItem class cách khiến gọi Private Function tên CalculateAmount để tính Amount thay để tính trực tiếp trước đây: Public Function Amount() As Single Return CalculateAmount End Function Các tập Microsoft NET 83 Private Function CalculateAmount() As Single Return mintQuantity * msngPrice End Function Khi ta SubClass LineItem để tạo ServiceLine class, Object ServiceLine thừa kế Function Amount Function declared Public BaseClass LineItem Ngược lại, Function CalculateAmount Private nên ServiceLine class lẫn client code dùng LineItem Object khơng truy cập Như thế, ta gọi Function Amount được, đến phiên gọi Private Function CalculateAmount có bị trở ngại khơng? Khơng Vì Function Amount nằm Class với Private Function CalculateAmount nên gọi được, ta gọi Function Amount từ ServiceLine hay client code Thí dụ client code ta có hàng code sau: Protected Sub BtnShowAmount_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnShowAmount.Click Dim Service As ServiceLine Service = New ServiceLine() Service.Item = "Delivery" Service.Price = 50 Service.DateProvided = Now MessageBox.Show (Service.Amount.ToString, "Amount", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Kết hiển thị message box, cho thấy Function CalculateAmount Function Amount gọi dùm cho client code client code lẫn ServiceLine code gọi trực tiếp Điểm nhắc nhớ lại cịn bé, có lần bà vườn đem chợ cho ba má thúng xồi thơm ngon Bạn tơi lối xóm thấy Các tập Microsoft NET 84 biểu lấy hai trái xồi để ăn vụn Vì khơng phải người nhà nên bạn lấy đuợc xoài, Access Modifier thún xoài Private nhà tơi Nhưng tơi Public, nên bạn tơi nhờ tơi lấy dùm Protected Methods Đơi Public hay Private chưa đủ Nếu ta declare thứ Private hồn tồn giới hạn class, ngược lại ta declare Public (hay Friend) dùng subclasses hay client code Tuy nhiên, có lúc ta muốn class member dùng subclasses thơi, khơng cho client code dùng Trong trường hợp ta dùng keyword Protected Thí dụ: Public Class FatherClass Protected DiSản As Single End Class Public Class SonClass Inherits FatherClass Public Function ChiaCủa() As Single Return Disản End Function End Class Ở ta có BaseClass FatherClass với Protected Field Disản Khơng có client code thấy Field DiSản Thế SubClass FatherClass thừa kế dùng DiSản Trong thí dụ trên, lần SubClass có Public method (ChiaCủa) return protected value - value ấy, DiSản, không trực tiếp cho phép client code dùng Overriding Methods Chúng ta biết đặc tính quan trọng Inheritance SubClass thừa kế behaviours ParentClass mà cịn override Các tập Microsoft NET 85 (lấn quyền) behaviours Chúng ta thấy SubClass extend (thêm ra) ParentClass cách cho thêm methods Public, Protected Friend Hơn nữa, dùng overriding, SubClass alter (sửa đổi) behaviours methods ParentClass Bình thường (By default), ta override methods ParentClass trừ methods declared với keyword Overridable ParentClass Thí dụ: Public Class ClassCha Public Overridable Sub ChàoHỏi() MessageBox.Show("Chào cháu", "Class Cha") End Sub End Class Tiếp theo, tạo SubClass, muốn ta override behaviour Sub ChàoHỏi cách dùng keyword Overrides sau: Public Class ClassCon Inherits ClassCha Public Overrides Sub ChàoHỏi() MessageBox.Show("Thưa Bác", "Class Con") End Sub End Class Bây ta viết client code sau: Private Sub BtnSubClassObject_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnSubClassObject.Click Dim obj As New ClassCon() obj.ChàoHỏi() End Sub Khi ta click button BtnSubClassObject program hiển thị message dialog đây: Các tập Microsoft NET 86 Virtual Methods Tuy nhiên, xem trường hợp ta code sau: Private Sub BtnParentClassObject_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnParentClassObject.Click Dim obj As ClassCha obj = New ClassCon() obj.ChàoHỏi() End Sub Trước hết, kỳ kỳ, declare variable loại ClassCha mà lại instantiate object ClassCon Chuyện hồn tồn bình thường, ClassCon ClassCha Tức variable loại ClassCha hay ClassCon chứa, thật hold references to (point to, tới), instance ClassCon Điểm áp dụng tổng quát ta dùng Inheritance Một variable loại SuperClass hold reference to SubClass Object thừa kế từ SuperClass Đó cách để ta implement tính đa dạng (polymorphism) Đều làm ta ngạc nhiên ta click button BtnParentClassObject ta thấy hiển thị message " Thưa Bác" Các tập Microsoft NET 87 Sao lạ vậy? Variable obj declared ClassCha message "Chào cháu"? Lý Sub ChàoHỏi ClassCon gọi thay Sub ChàoHỏi ClassCha Ta nói Sub ChàoHỏi Virtual method Tất methods VB.NET virtual Ý niệm virtual để nói implementation cháu trẻ dịng họ dùng - khơng cần biết variable có data type class hệ dòng họ Tức là, variable dùng client code hold references to ClassÔngNội, ClassCha, ClassCon hay ClassCháu method ClassCháu gọi Nếu ClassCháu khơng có implementation method ta gọi method ClassCon, khơng có gọi method ClassCha v.v theo thứ tự từ bề lên bề Keyword Me Keyword Me dùng ta muốn nói rõ (explicitly) ta muốn dùng method Class chứa code ấy, implementation khác method Cũng có trường hợp ta phải dùng keyword Me để nói ta muốn dùng classlevel variable khơng phải procedure-level variable có tên Một procedure-level variable, tức local variable method, có tên với class-level variable gọi shadowed variable Thí dụ: Public Class TheClass Private strName As String Public Sub DoSomething() Dim strName As String Các tập Microsoft NET 88 strName = "Quang" End Sub End Class Ở đây, variable strName declared class-level bên Sub DoSomething Bên method local variables (kể shadowed variables) dùng chúng che đậy class-level variables trừ ta nói rõ phải dùng variable class-level cách dùng keyword Me: Public Class TheClass Private strName As String Public Sub DoSomething() Dim strName As String strName = "Quang" ' thay đổi value local (shadowed) variable Me.strName = "Kim" ' thay đổi value class-level variable End Sub End Class Keyword MyBase Keyword Me tiện dụng ta muốn dùng Class members Class chứa code Tương tự vậy, đơi ta muốn dùng Class method BaseClass (cũng gọi SuperClass), implementation method SubClass Nhớ virtual method luôn gọi implementation Class trẻ Từ SubClass, muốn gọi method BaseClass ta dùng keyword MyBase sau: Public Class ClassCon Inherits ClassCha Public Overrides Sub ChàoHỏi() MessageBox.Show("Thưa Bác", "Class Con") MyBase.ChàoHỏi() End Sub Các tập Microsoft NET 89 End Class Bây ta chạy Sub ChàoHỏi ClassCon ta có hai messages, từ ClassCon theo sau từ ClassCha MyBase nói đến BaseClass trực tiếp, tức Class cha thơi khơng nói đến Class ơng nội Khơng có cách để nói đến hệ Dầu vậy, keyword Mybase dùng cho thứ declared Public, Friend hay Protected ParentClass Điều kể thứ mà ParentClass thừa kế từ hệ trước gia đình, tức ClassƠngNội, ClassƠngCố v.v Keyword MyClass Vì lý virtual method, ta gặp trường hợp rắc rối code ParentClass lại chạy code SubClasses Khi viết code class, từ method ta thường gọi methods khác nằm class Thí dụ như: Public Class ClassCha Public Sub VôĐề() ChàoHỏi() End Sub Public Overridable Sub ChàoHỏi() MessageBox.Show("Chào cháu", "Class Cha") End Sub End Class Trong trường hợp này, VơĐề gọi Sub ChàoHỏi để đón tiếp Để ý ChàoHỏi declared Overridable nên SubClass implement method ChàoHỏi lấn quyền Thí dụ: Public Class ClassCon Inherits ClassCha Public Overrides Sub ChàoHỏi() MessageBox.Show("Thưa Bác", "Class Con") Các tập Microsoft NET 90 End Sub End Class Vì đặc tính virtual ChàoHỏi nên ta tưởng ClassCha execute Sub ChàoHỏi té lại execute code ChàoHỏi ClassCon Trong code đây, Object ClassCon gọi Sub VôĐề ClassCha: Private Sub BtnSubClassObject_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnSubClassObject.Click Dim obj As New ClassCon() obj.VôĐề() End Sub Trong ClassCha, Sub VôĐề gọi ChàoHỏi nó, nhiên Sub ChàoHỏi bị overridden implementation ChàoHỏi ClassCon Do đó, program hiển thị message "Thưa Bác" Nếu ta khơng muốn vậy, ta muốn VơĐề execute code ChàoHỏi ClassCha phải dùng keyword MyClass sau: Public Class ClassCha Public Sub VôĐề() MyClass.ChàoHỏi() End Sub Public Overridable Sub ChàoHỏi() MessageBox.Show("Chào cháu", "Class Cha") End Sub End Class Ở ta dùng keyword Me VơĐề có gọi ChàoHỏi classlevel ClassCha khơng phải SubClass, bị overridden Hình minh họa q trình gọi VơĐề từ client code: ... ProductLine pl = New ProductLine("P1234") ListBox1.Items.Add("ProductItem:" & pl.Item) ListBox1.Items.Add("Description: $" & pl.Description) Các tập Microsoft NET 81 End Sub Trong code bên ta dùng... property DateProvided vào interface thừa kế từ Class LineItem Các tập Microsoft NET 82 Bài Những chức Đối Tượng VB.NET (phần III) Dùng OO VB.NET Ngăn cản Thừa kế Bình thường (By default) class dùng.. .Các tập Microsoft NET 74 New method Trong VB6, Object thành hình Sub Class_Initialize executed Tương đương vậy, VB.NET ta có Sub New(), gọi Constructor VB.NET bảo đảm Sub New()

Ngày đăng: 31/07/2014, 09:20

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan