Cac bai tap .net

Embed Size (px)

DESCRIPTION

Cac bai tap .net http://www.hono-bono.com/

Citation preview

  • 1. Cc bi tp Microsoft .NET1 MC LCBi 1 Microsoft .NET Framework .................................................................................2Bi 2 Visual Studio.NET .............................................................................................13Bi 3 Nhng khc bit gia VB.NET vi VB6 ...........................................................37Bi 4 Nhng chc nng i Tng mi ca VB.NET (phn I)..................................59Bi 5 Nhng chc nng i Tng mi ca VB.NET (phn II) ................................68Bi 6 Nhng chc nng i Tng mi ca VB.NET (phn III) ...............................82Bi 7 Nhng chc nng i Tng mi ca VB.NET (phn IV)...............................95Bi 8 Nhng chc nng mi trong giao din ca s ca VB.NET (phn I) ..............112Bi 9 Nhng chc nng mi trong giao din ca s ca VB.NET (phn II).............124Bi 10 Nhng chc nng mi trong giao din ca s ca VB.NET (phn III) .........134Bi 11 Nhng chc nng mi trong giao din ca s ca VB.NET (phn IV) .........144Bi 12 Nhng chc nng mi trong giao din ca s ca VB.NET (phn V) ..........161

2. Cc bi tp Microsoft .NET 2Bi 1 Microsoft .NET FrameworkCi t Visual Studio.NET Beta 2Visual Studio.NET nm trong 3 CDs, gm c 4 files: EN_VS_NET_BETA2_WINCUP.exe EN_VS_NET_BETA2_CD1.exe EN_VS_NET_BETA2_CD2.exe EN_VS_NET_BETA2_CD3.exeChy EN_VS_NET_BETA2_WINCUP.exe Unzip n vo mt foldertrong mt harddisk (eg: E:CDWINCUP).Ln lt chy EN_VS_NET_BETA2_CD1.exe,EN_VS_NET_BETA2_CD2.exe v EN_VS_NET_BETA2_CD3.exe Unzip chng vo chung mt folder trong mt harddisk (eg: E:CD ).Vic Unzip files c th rt lu, bn phi kin nhn ch cho n khi n ktthc. Nu khng, khi ci t c th b than phin l thiu files.K , trc ht chy Setup.exe ca Windows Component Update nhdi y, click No khi Warning dialog hin ra:Tip theo, chy Setup.exe ca Visual Studio.NET:Bn nn c CPU Pentium III, 500MHz tr ln, vi 256 MB RAM v tnht 10GB Harddisk. V OS bn nn dng Windows 2000 (Professional 3. Cc bi tp Microsoft .NET 3hay Server) hay Windows XP. L do chnh l cc versions Windows nyh tr Unicode v c Internet Information Server (IIS) h tr ASPX tadng cho ASP.NET.M cc Samples ca QuickStartTrc khi expand Samples ca Quickstart bn cn phi ci t IIS. Nucha lm vic y bn b CD ca Windows2000 hay WindowsXP vo install IIS component.QuickStart Samples ca .NET Framework cha cc gii thch cn bn vnhiu th d. expand cc Samples doubleclick WebpageStarthere.htm nh trong hnh di y:Khi trang Web ca QuickStart hin ra, click QuickStart, tutorials andsamples ri sau theo ch dn tng bc.Trang Framework SDK QuickStart Tutorials cho ta cc bi tp caASP.NET, Windows Forms v How Do I...Nh nguyn cc folders ca Unzipped files (E:CD, E:CDWINCUP),ng delete chng, v .NET s cn dng chng. Ngoi ra, nu sau ny.NET b corrupted v conflict vi cc application software khc, bn cth ci t .NET li.Gii hn ca Software Tools hin gi 4. Cc bi tp Microsoft .NET4Architect ca application software hin gi c ni chung ba tng (threetiers): tng giao din (Presentation Tier), tng gia (Middle Tier) v tngd kin (Data Tier):Presentation Tier: Trong desktop Client ta dng VB6 v ni vi middletier qua DCOM. Trong browser based Client ta dng Javascript hay Javaapplet. T browser based Client ta dng http ni vi middle tier quaIIS/ASP (c th dng COM y).Middle Tier: Cha cc rules validate data trn client v cc businessrules khc. Ta dng VB6 y, nhng cch trin khai COM vi nhngObject Oriented Programming concepts rc ri hn bnh thng. Ta phithit k sao cho cc components scale well (dng cho mi c). C khidng Microsoft Transaction Server trn Windows NT hay COM+Services trn Windows 2000. Lp rp cc versions ca components lmt thch thc ln.Nhiu khi middle tier cn ni chuyn vi cc database qua HTTP, ADOv CDO (Collaborative Data Objects), .v.v..Data Tier: Thng l relational database nh Microsoft SQL Server hayOracle. Ngoi ra cn c Exchange hay cc database xa ca mainframe.Do ta thy: Desktop tools khng thch hp cho Distributed System hay Internet Phi dng nhiu th codes nh VB6 Code, VBScript, JavaScript, Dynamic HTML, Cascading Style Sheet, VC++, Stored Procedures (Transact-SQL trong SQLServer hay PL-SQL trong Oracle).Ty thuc qu nhiu vo central database: Ngay c ADO d l tin dngcng i hi Client lun lun connect vi Server. iu ny khng thch 5. Cc bi tp Microsoft .NET5hp cho Internet applications, v bn cht ca Internet l stateless (khnggi trng thi), mi ln cn lm vic mi connect li mt cht thi. DLL "Hell": Cc ActiveX cn phi c registeredvi Windows Registry, ch c mt version c chpnhn. Nu version mi nht ca mt DLL khngcompatible vi cc versions trc m applicationstrn my ang cn th c rc ri.Gii hn ca VB6 Thiu kh nng inheritance (tha k) v mt s ObjectOriented features khc. Kh nng Error handling gii hn: On Error Goto ...,On Error Resume Next 6. Cc bi tp Microsoft .NET 6 Nhiu khi cn phi gi Windows API lm nhngvic VB6 khng h tr: vic ny khng t nhin vi khi nguy him. Khng c multi-threading: khng th on trcresponse ca code chy trong cc windows ca cngmt VB6 application. Ngay c gii quyt vn multitasking bng Timers cng khng ng tin cy. Khng d dng chung vi cc ngn ng khc nhVC++. Khng tin cho Web development: WebClass khngthnh cng lm. t ai chu cho ta ci ActiveX trn myca h..NET Framework.NET c developed t u nm 1998, lc u c tn l NextGeneration Windows Services (NGWS). N c thit k hon ton tcon s khng dng cho Internet. Vin tng ca Microsoft l xy dngmt globally distributed system, dng XML (cha nhng databases thon) lm cht keo kt hp chc nng ca nhng computers khc nhautrong cng mt t chc hay trn khp th gii.Nhng computers ny c th l Servers, Desktop, Notebook hay PocketComputers, u c th chy cng mt software da trn mt platform duynht, c lp vi hardware v ngn ng lp trnh. l .NETFramework. N s tr thnh mt phn ca MS Windows v s c portqua cc platform khc, c th ngay c Unix.Mc du hy cn l Beta, .NET Framework rt stable v VisualStudio.NET rt t bugs, c th dng cho software development ngay tby gi. Hin nay c mt s sch v lp trnh .NET do Wrox vOreilly xut bn.Cc phn chnh ca Microsoft.NET Framework:.NET application c chia ra lm hai loi: cho Internet gi l ASP.NET, 7. Cc bi tp Microsoft .NET7gm c Web Forms v Web Services v cho desktop gi l WindowsForms.Windows Forms ging nh Forms ca VB6. N h tr Unicode honton, rt tin cho ch Vit v tht s Object Oriented.Web Forms c nhng Server Controls lm vic ging nh cc Controlstrong Windows Forms, nht l c th dng codes x l Events y htnh ca Windows Forms.im khc bit chnh gia ASP (Active Server Pages) v ASP.NET ltrong ASP.NET, phn i din visual components v code nm ringnhau, khng ln xn nh trong ASP. Ngoi ra ASP.NET code hon tonObject Oriented.Web Services ging nh nhng Functions m ta c th gi dng t ccURL trn Internet, th d nh Credit Card authorisation.ADO.NET l mt loi cache database nho nh (gi l disconnecteddatabase) thay th ADO. Thay v application connects vnh vin vidatabase m qua ADO, application trong .NET lm vic vi portabledatabase ch cha mt hai tables, l copy t database m. Khi no cn,portable database ny (ADO.NET) s c reconciled vi database m update cc thay i. Hai tables trong ADO.NET c th c related nhautrong Master/Details relationship. V ADO.NET c cha original dataln data mi nht nn Rollback trong ADO.NET rt d dng v nh k.XML c ym tr ti a. Nm pha sau ADO.NET l XML. XML cth l Table of records trong ADO.NET hay Tree of nodes trong DOM(Document Object Model).IO c h tr bng ton b Stream k c Memory Stream vStreamReader/StreamWriter. Thm vo l DataFormatting choSerialisation cha Object xung binary file hay text file.TCP/IP v http l hai protocols thng dng nht trong .NET, nhngchng lm vic pha sau sn khu gip ta gi mt remote procedure (nmtrn computer khc) d dng nh mt local procedure. K thut y gi lRemoting. 8. Cc bi tp Microsoft .NET8Security h tr Cryptography, Permissions v Policy.Diagnostics cho ta Debug v Trace.Threading rt tin v n gin implement Lightweight Process. Vn Timing trong .NET program rt linh ng, hiu qu v chnh xc.Vic thit k Common Language Runtime nhm vo cc mc tiu chnhsau y: Vic trin khai n gin v nhanh hn: developers sdnh th gi quyt nh rp nhng softwarecomponents no li vi nhau nhiu hn l lp trnhtht s. Cc cng tc thit yu ("plumbing") nh memorymanagement, process communication .v.v. c loliu t ng. Cc cng c h tr rt y (no more API): .NETFramework Base classes rt phong ph cho file,network, serialisation, m ha, XML, database, v.v.. Ci t n gin v an ton (no more DLL "hell"): chcn xcopy files, ging nh thi vng son ca DOS. Ldo l .NET application chy trn .NET framework,mt khi ta ci .NET framework vo my ri th cy mi .DLL cn thit. C l trong tng laiMicrosoft ci .NET framework chung vi Windows. Dng cho t WindowsCE n Desktop, n Web(scalability). 9. Cc bi tp Microsoft .NET9MetadataMetadata l cc d kin ct ngha cho ta bit v d kin. Th d XMLSchema ca mt XML file l metadata ct ngha v data structure cadata trong XML file. Chnh ci XML Schema cng l mt XML file. Cc.NET application components, gi l Assembly, cha rt nhiu metadata ct ngha v chnh n (self describing). Tm bit v mt .NETapplication c th lm vic vi n th gi l Reflection.H tr v phi hp mi ngn ng lp trnhCommon Language Runtime (CLR) l trung tm im ca .NETFamework, n l hm my chy cc nng tnh ca .NET. Trong .NET,mi ngn ng lp trnh u c compiled ra Microsoft IntermediateLanguage (IL) ging ging nh byte code ca Java. Nh bt buc mingn ng u phi dng cng cc loi data types (gi l Common TypeSystem) nn Common Language Runtime c th kim sot mi interface,gi gia cc components v cho php cc ngn ng c th hp tc nhaumt cch thng sut. Tc l trong .NET, VB.NET program c th inheritC# programvngcli mt cch hon ton t nhin.iu ny chng nhng gip cc VC++ hay Java programmers bt u 10. Cc bi tp Microsoft .NET 10dng C# mt cch d dng m cn lm cng mt d n vi VB.NETprogrammers na.Nu VC++ linh ng v hiu nng hn VB6, th C# chng khc gVB.NET. Bn c th port C# code qua VB.NET code rt d dng. Vsource code VC++ v Java gn gi C# hn VB6 vi VB.NET nn ngoii c nhiu C# code hn VB.NET. Do , mc du hai ngn ngVB.NET v C# u ngang c nhau, nu dng C# bn c li im cnhiu source code sn v nht l lu nay ngi ta vn mang n tng rngVC++ hay Java programmers mi tht s l cc cao th lp trnh, v ckhuynh hng tr lng cc guru VC++/Java cao hn VB programmers.Khi chy .NET application, n s c compiled bng mt JIT (Just-In-Time) compiler rt hiu nng ra machine code chy. im ny gip.NET application chy nhanh hn Java interpreted code trong JavaVirtual Machine. Just-In-Time cng c ngha l ch phn code no cn xl trong lc y mi c compiled. IL code chy trong CLR uc ni lmanaged code..NET code c th chy chung vi ActiveX, nhng code trong ActiveXc gi l unmanaged code, tc l CLR khng chu trch nhim.Ngoi vic allocation v management of memory, CLR cn gi ccrefrerence n objects v rc (handle garbage collection), tc l thuli cc mnh vn memory khi chng khng cn dng na. Trc y, mikhi mt DLL uc loaded vo memory, system s ghi nhn c bao nhiutask dng n khi task cui cng chm dt th system unload DLL vtr li phn memory n dng trc y system dng cho chuyn khc.Ch nu allocate memory dng m khng nh dispose n th s bmemory leak (r ), ln ln ta dng ht memory, b bt buc phi reboot 11. Cc bi tp Microsoft .NET11OS. Nhng by gi .NET dng mt process c lp lm vic garbagecollection. Ci phn ng ph ca vic ny l khi ta Dispose mtObject ri, ta vn khng bit chc chn chng no n mi tht s binmt. V garbage collector l mt low priority process lm vic trongbackground, ch khi no system memory gn cn n mi nng caopriority ln. D nhin, nu mun, ta c th i hi system Dispose mtObject ngay lp tc.Assembly.NET application xy dng t cc assemblies. Mi assembly phi c mtmanifest. C th n nm ring trong mt file hay nm bn trong mtmodule. Manifest cha nhng metadata sau y: Tn v Version number ca assembly Nhng assembly khc (k c version number caassembly) m assembly ny ty thuc vo chy 12. Cc bi tp Microsoft .NET 12 Types (classes v members) m assembly ny choxut khu Assembly ny i hi iu kin an ninh no (securitypermissions)Manifest cho php ta dng hn mt version ca assembly (tng ngvi DLL trc y) cng mt lc. T y khng cn register DLL na.Thay vo , ta ch cn copy cc assembly vo mt subfolder /bin cachng trnh chnh.Quyt nh ca bnSau khi bit qua v .NET, cu hi bn s t ra l bn c nn hc lp trnhtrn .NET hay khng. Ni chung, v lp trnh c nhiu tn gio nhVC++/Java, VB6, Delphi ..v.v.. Bn c th chn gia C# v VB.NET.i vi VB6 programmers, hc lp trnh VB.NET s mt mt thi gian,nhng khng kh. Nn nh rng .NET khng phi ch cho ta cc ngnng lp trnh, m c mt h thng trin khai phn mm ch trng vomc tiu hn l cch thc. Cc li ch .NET cng hin cho bn cch thctin l: K thut .NET s honh hnh trn giang h trong t 5n 10 nm ti. Tnh trung bnh, lp trnh trong .NET s tit kim thgi cho bn t 25% n 50% so vi trc y. L dol trong .NET bn s nghin cu dng componentno nhiu hn l tht s vit code. Hn na, hu nhcode no bn cn phi vit, bn s dng n li trongtng lai. V bo tr .NET code th li cng khe hntrc y, v chnh bn c vit bao nhiu code (c thb bugs) u m bo tr.Do , c l trong tng lai .NET programmers chng ta s ng n 10gi sng mi thc, mt ngy ch cn lm vic vi ting, rnh rang lmvn, cu c.Trong bi ti ta s hc v Visual Studio.NET interface v bt u vit thmt program Demo . 13. Cc bi tp Microsoft .NET 13 Bi 2Visual Studio.NETVisual Studio.NET chy VisualStudio.NET bn cn phi Set Time ca Windows li trccui thng 7,2001, eg: 1-July-2001.Visual Studio.NET Beta 2 hin nay c Service Pak 2, n cho php tadng Visual Studio.NET Beta 2 sau ngy 31-July-2001, tc l khng ctime-bomb. Nu VS.NET version ca bn b gii hn v thi gian nitrn, t trong VS.NET bn c th download Service Pak 2 ci t bngcch dng IDE Menu Command Help | Check for Updates.C hai cch bt u mt project mi trong VS.NET. Hoc Click NewProject trong trang Web StartPage nh di y:Hoc dng Menu command File | New | Project ging nh trong VB6IDE: 14. Cc bi tp Microsoft .NET14Khi Add New Project, Name s l subfolder name ca New Project. Bnc th chn VB.NET, C# hay VC++.NET project. Trong tng lai chngta s ch nhm vo VB.NET v C# thi. Ngoi ra SetUp and Deploymentby gi l mt loi project nm trong IDE ca Visual Studio.NET, takhng cn phi chy ring chng trnh Package and Deployment bnngoi VB6 IDE nh trc y.Solution trong VS.NET c th cha hn mt Project v bao gm tt cnhng files bn lit ra l cn thit cho Solution. Nu mt trong nhngfiles y b thay i bn ngoi VS.NET, khi VS.NET khm ph ra n sload vo trong VS.NET cho bn nu bn ng . 15. Cc bi tp Microsoft .NET15 m mt Solution/Project c sn, bn c th click link ca tn projecttrn trang StartPage, hay dng Menu command File | Open | Project ,hay Menu Command File | Recent Projects.Visual Studio.NET IDE 16. Cc bi tp Microsoft .NET 16Giao din ca VS.NET c nhng c im ging nh Delphi v VisualInterDev ch code c generated t ng, Windows nm chung thnhTab set hay float khp ni, v h tr Solution rt thch hp cho vic trinkhai ca c i.Toolbox bn tri cha Controls cho Windows Forms, Web Forms,General Components, Data Components, HTML tags, XML Schematools v.v... Khi mt Form ang hin th, click ln mt button trongToolbox chn Tool Set bn cn. Toolbox trng thi Fixed displayed(nh trong hnh trn) khi cy ghim pha trn m xung. Bn c th clickcy ghim cho n nm ngang v vertical Toolbox tab hin ra bn tri. Lcy, Toolbox trong trng thi Auto Hide (hin ra/rt vo) nh di y: 17. Cc bi tp Microsoft .NET17Bn c th gi hu ht cc Windows hin th bng cch dng Menucommands View, View | Other Windows v Debug | Windows:Cc Windows bn phi c th float, nm chng ln nhau thnh nhngTabs trong mt Window set hay nm cnh nhau vertically tiled. NmTittle bar di nguyn mt Window set i. Nm Window Tab ca mtWindow set ko ch mt Window ra. Bn c th chng hai 18. Cc bi tp Microsoft .NET 18Windows li vi nhau bng cch nm Tittle bar ca mt Window chng ln mt Window khc. Th nhch i, nhch li, trc khi bungWindow ra lm quen vi kt qu.Pha di c Task List Window bn gi s sch v din tin ca dn v qun l c i. Khi bn dng menu command Build | Build compile program, nu c errors chng s c hin th trong Task ListWindow. Double click ln mt hng error mang cursor n ch gy raerror y trong code window.Trong hnh di y, ta c comment out hng Dim sw AsStreamWriter:Ngoi ra, Debug by gi bn c Output Window in ra ccmessages m trong VB6 bn dng Immediate Window. Th d trong VB6bn vit: Debug.Print "Count=" & CStr(Count) in ra trong Immediate Window, th trong VB.NET bn c th vit: Console.WriteLine("Count= {0}", Count) 19. Cc bi tp Microsoft .NET 19 in ra trong Output Window.D nhin bn vn c th tip tc dng Immediate Window trong cng tcDebug nh trc y trong VB6.Cha ht, VS.NET cn cho bn Command Window ta c th enternhng VS.NET commands manipulate IDE, x l macros, .v.v hin th Window ny bn dng menu command View | OtherWindows | Command Window. tin hn, bn drag title bar ca n chng ln tab bar ca Task List v Output windows.Nu ta enter mt command nh:File.AddNewProjectIDE s hin th Add New Project dialog.VS.NET h tr Macro bn c th record v playback mt chui cngtc.Phng tin Integrated Debugging cho ta Debug Menu, Call StackWindow, Breakpoints Window v Watch and Value DisplayWindows.Thng thng bn s Add Reference cc .NET components. Nhng bncng c th dng ActiveX (c sn trong VB6) trong .NET applicationbng cch Add Reference COM (click Tab COM trn Add ReferenceDialog). .NET s gi ActiveX thnh mt NET component (click Yes tr 20. Cc bi tp Microsoft .NET20li cu hi "Would you like to have a wrapper generated for you?").Ngoi ra dng Add Reference Projects refer n DLL ca cc Userdeveloped DLL.Demo ProgramTrong chng trnh biu din ny, ta dng giao din hu nh hon tonbng ch Vit. Ta c th nh ch Vit (Unicode) cho Title Bar, Menu,TextBox, ListBox .v.v..Nu bn cn mt key input software cho ch Vit h tr Unicode thdownload VPS, Vietkey hay Unikey.Cc documents nh Form, XML .v.v. trong .NET project u c Savedvi UTF-8 encoding. 21. Cc bi tp Microsoft .NET21Trong program S th Saigon ny ta c hai Listboxes. Khi chy, bn cth drag tn cc loi th t Listbox1 (bn tri) drop vo Listbox2 (bnphi). Pha di l mt Label dng hin th ngy gi. C mt buttonLu tr danh sch ta save data trong Listbox2 vo file animal.txttrong subFolder bin. Ngoi ra bn cng c th dng Main menu Item cdanhsch Load data t file animal.txt vo Listbox2.Nhng components khng cn phi hin ra lc runtime nh Timer,Menu, Tooltip .v.v. nm trong mt Component Tray (mm) ring. MunEdit MainMenu, click ln MainMenu1 icon ri nh trc tip voMainMenu. Thm cc menuitems mi bng cch nh thng vo cc chc ch Type Here. Lu cc Tabs bn trn Editing Area khi bn mnhiu forms. 22. Cc bi tp Microsoft .NET22Edit MainMenu, insert mt Separator 23. Cc bi tp Microsoft .NET23Ch danh sch cc References c lit k trong Solution Explorer.Edit Shortcut cho mt menu item. 24. Cc bi tp Microsoft .NET24Button by gi chng nhng c th cha hnh m cn cho bn chn v trca hnh trong button bng ImageAlign na.Bn c th Anchor mt Button n dnh vo mt gc ca form khiform resizes th Button chy theo gc y ca form. y ta click haithanh Di v Phi cho chng tr nn mu en chn Anchor Bottomv Right. 25. Cc bi tp Microsoft .NET25Trong lc thit k ta c th edit cc List items ca mt Listbox bng cchm property Items Collection ra v Edit vo mt trang.Walk Through CodeTrong .NET, cc classes c chia ra thnh nhiu nhm nh System.IO,System.XML, System.Data, System.Drawing ..v.v..Ngoi ra trong mi nhm li cn chia thnh nhng nhm con, chu nhSystem.Windows.Forms,System.Windows.Collections,System.Windows.Diagnostics, .v.v.. Mc du mt khi Project | AddReference cc .NET components y ta c th dng chng trong program 26. Cc bi tp Microsoft .NET26nhng vn phi bin mt tn di nh System.IO.StreamReader trnhln ln. c th vit tn class gn hn ta dng Imports nh ImportsSystem.IO, sau ta ch cn vit StreamReader l . Cng vicImports ny c gi l importing Namespace (ca System.IO).Tng t nh th, c th tip tc dng cc Functions Left, Right, Midca VB6 trong .NET ta c th thm cu Imports VB6 =Microsoft.VisualBasic u chng trnh. Sau ta c th vit:AppPath = VB6.Left(AppPath, Pos)Nguyn program chng ta ti y l Public Class Form1. Form1 tha kstandardform classca .NET Framework nn ta declare: Inherits System.Windows.Forms.FormImports System.IOImports VB6 = Microsoft.VisualBasicPublic Class Form1Inherits System.Windows.Forms.FormDim AppPath As StringPrivate Sub MenuItem4_Click(ByVal sender As System.Object, ByVal eAs System.EventArgs) Handles MenuItem4.ClickEndTerminate the programEnd SubPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles MyBase.Load Obtain the folder where this program EXE resides and initialise tooltip 27. Cc bi tp Microsoft .NET 27 Dim AppPath As String Dim Pos As IntegerFetch full pathname of the EXE file AppPath = System.Reflection.Assembly.GetExecutingAssembly.LocationLocate the last slash in the pathname string Pos = InStrRev(AppPath, "/")Extract the part up to the backslash AppPath = VB6.Left(AppPath, Pos)Initialise the tooltip for Listbox1 ToolTip1.SetToolTip(ListBox1, "Xin nm ko tn mt con th qua Listbox bn phi")End SubHy xem cch vit mt Event Handler nh:Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal eAs System.EventArgs) Handles MenuItem4.ClickKhc vi VB6, n c thm cc ch Handles MenuItem4.Click pha cui ni handling event Click ca MenuItem4. Mi Event Handler uc passed cho hai parameters: ByVal sender As System.Object vByVal e As System.EventArgs. Parameter th nht, sender, l Object chng chuyn RaiseEvent, cn e l Event c cha nhiu d kin khc nhauty theo tnh hung. Khi edit code bn c th nh Intellisense ca IDEgip cho bit parameter e cha nhng d kin g.Trong .NET, vn handling event khng phi l mt iu b him nhtrong VB6. Khi mt control c th RaiseEvent th chng nhng mt, m 28. Cc bi tp Microsoft .NET28nhiu controls khc u c th ng k (Register) c Thng bo(Notified) khi Event y xy ra.Control RaiseEvent c gi l Publisher (Nh Xut Bn), cc controlsmun handle event c gi l Subcribers (nhng Ngi t Mua dihn) . D nhin cch handle event ca mi control u khc nhau, durng c passed cho cng hai parameters. Cc EventHandlers ny cgi l Delegates (nhng Nh i Din lnh trch nhim gii quyt mt sc).Do , ta c th dng vn vn mt EventHandler handle nhiu Eventkhc nhau, xut pht t nhiu Objects. Ni cho n gin ra, sau khi ta ng k mt hay nhiu Delegates (tc l EventHandler Subs), th khiEvent xy ra, ccEventHandler Subs y s c x l.Nu bn vn cn thy kh hiu th hy c th d ny. Tng tng bnlm bing nu n nn t nh hng giao cm mi ngy n tn nh. Chai cch bn nhn "g-mn" cm:1. Ngi giao cm s "g-mn" cm trc nh, cnh bn hp th. Khi i lm v, bn s mang n v nh. Trong trng hp ny bn x l cng vic khi no tin, tc l lc v n nh. Cch ny c im bt li l hm no bn i lm v tr th cm c th b thiu v tri nng.Bn a cha kha nh cho ngi giao cm gi. Khi giao cm, ngi ys t ng m ca v nh "g-mn" thng vo trong t lnh. Trongcch ny Event GiaoCm c handled bng EventHandler SubOpenDoorPutIntoFridge, do ngi giao cm x l, ch khng phichnh bn.Nh th, l Subscriber (ngi n cm thng giao tn nh) bn registerEventHandler "Sub OpenDoorPutIntoFridge" vi ngi giao cm qua 29. Cc bi tp Microsoft .NET29vic a cha kha. Khi Event "GiaoCm" xy ra, ngi giao cm tng executes Sub OpenDoorPutIntoFridge. K thut giao AddressOfSub cho mt Object khc n execute khi cn cn c tn l CallBack.Do , ngay c trong lc runtime (khng phi khi design), RegisterEventHandler Sub MenuItem4_Click vi system handle Event Clickca MenuItem4 ta c th execute code:AddHandler MenuItem4.Click, AddressOf MenuItem4_ClickLu cch ta dng control ToolTip1 register Tooltip Text viListbox1. Ta c th dng ch mt control ToopTip1 register nhiuTooltip Texts vi nhng controls khc nhau nh TextBox, ComboBox.v.v..Bn c th thay th hng:AppPath = VB6.Left(AppPath, Pos)bngAppPath = AppPath.SubString(0,Pos)Trong VB6, Visual components ca mt form c cha di dng Textdin t cc controls rt d c ngay u form file, nhng n khng phil VB6 code.Trong .NET, Visual components ca mt form c cha di dng codetht s. Tc l, nu khng c VS.NET ta c th dng Notepad vit codenh th v sau khi compile, n vn chy y ht nh trong trng hp tadng VS.NET. im ny ging nh trong Java, ta c th vit code bngNotepad v dng Command line compile v link code file vi cccomponents khc.Th d nh khi ta vit mt VB.NET program n gin chy trn trongDOS Console, ta c th compile n nh sau: 30. Cc bi tp Microsoft .NET30 vbc /t:exe /r:system.dll mysource.vbvbc l VisualBasic Compiler, /t: c ngha target tc l EXE chytrong DOS console. /r: c ngha reference n DLL.Nu mun chy trong Windows, ta dng: vbc /t:winexe /r:system.dll /r:system.windows.forms.dllmysource.vbBnh thng generated code c du trong Region khi chon ch,hay khu gi chng ta sa i.Click du + bn l tri m mt Region hay Sub/Function. Click du - ng li.i khi ta cng c th Edit generated code, nhng bn nh backup codetrc, ri form khng th hin th v b error, ch cho ta mt trang giytrng, th ta cn c ng restore. 31. Cc bi tp Microsoft .NET31Mi class u c t nht mt Sub New, gi l Constructor (ging nhClass_Initialize ca VB6 class) v Sub Dispose, gi l Destructor. l hai Sub dng to ra v ph hy Object. V Form1 tha k tStandard Form nn trong Sub New trc ht phi gi constructorMyBase.New() ca cha n, v trong Sub Dispose sau ht phi gidestructor MyBase.Dispose ca cha n.M Class View WindowBn c th Navigate trong Code qua Class View. DoubleClick ln tn caObject hay Sub/Function trong Class View mang cursor n code can trong trang Edit. 32. Cc bi tp Microsoft .NET32Bi u di n DragDropCode ca DragDrop, lu ta phi vit thm Sub ListBox2_DragEnter handle Event DragEnter.Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.MouseEventArgs) HandlesListBox1.MouseDownStart the DragDrop process Dim ItemIndex As Integer 33. Cc bi tp Microsoft .NET 33Identify the Listbox item that has mousedown using mouse coordinates ItemIndex = ListBox1.IndexFromPoint(New System.Drawing.Point(e.X, e.Y))Start the DragDrop process passing along the ListboxItem asListBox1.Items(ItemIndex) ListBox1.DoDragDrop(ListBox1.Items(ItemIndex),DragDropEffects.Copy Or DragDropEffects.Move)End SubPrivate Sub ListBox2_DragEnter(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.DragEventArgs) Handles ListBox2.DragEnterApply the copy effectAND remember to set the property Allow Drop of Listbox2 to TRUE If (e.Data.GetDataPresent(DataFormats.Text)) Thene.Effect = DragDropEffects.Copy Elsee.Effect = DragDropEffects.None End IfEnd SubPrivate Sub ListBox2_DragDrop(ByVal sender As Object, ByVal e AsSystem.Windows.Forms.DragEventArgs) Handles ListBox2.DragDrop Dim LItem As String 34. Cc bi tp Microsoft .NET 34Obtain the Source ListItem String LItem = e.Data.GetData(DataFormats.Text).ToStringAdd it to Listbox2 ListBox2.Items.Add(LItem)Remove the Item from Listbox1 ListBox1.Items.RemoveAt(ListBox1.FindString(LItem))End SubKhi Load data vo Listbox ta dng StreamReader Open mt File asInput.Khi Save data ca Listbox vo mt Text file ta dng StreamWriter Open mt File as Output (hay Append nu ta cho thm OptionAppend=True):Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal eAs System.EventArgs) Handles MenuItem2.ClickRead the list of animals from a text file into Listbox2 Dim sr As StreamReader Dim Pos As Integer Dim TStr As String ListBox2.Items.Clear()Clear Listbox2Use a StreamReader to open the UTF-8 file to read. sr = New StreamReader(AppPath & "animals.txt")Read each line in the file.When the end of the file is reached, return the value "-1". Dim x As String 35. Cc bi tp Microsoft .NET 35 While sr.Peek -1 x = sr.ReadLine()Read a line ListBox2.Items.Add(x)Add it to Listbox2 End While sr.Close()Close the fileEnd SubPrivate Sub SaveAnimalList()Save the content of Listbox2 into a UTF-8 Text file Dim i As Integer Dim sw As StreamWriterOpen the file to write in UTF-8 mode, using a StreamWriter. sw = New StreamWriter(AppPath & "Animals.txt")Write each line in the Listbox. For i = 0 To ListBox2.Items.Count - 1 sw.WriteLine(ListBox2.Items(i)) Next sw.Close()Close the fileEnd SubTa hin th ngy v gi bng cch dng Timer1 v Shared Function DateTime.Nowformated bng hai Functions c sn ToLongDateString v ToLongTimeString.Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) HandlesTimer1.TickDisplay Date and Time every half a second Label3.Text = DateTime.Now.ToLongDateString & " " & DateTime.Now.ToLongTimeStringEnd SubBn cng c th hin th ngy gi trong format khc bng cch vit:Label3.Text = DateTime.Now.ToString("ddd dd/MM/yyyy hh:mm:ss") c: WED 18/07/2001 09:16:42 36. Cc bi tp Microsoft .NET36 trong Format string ta dng MM cho Month v mm cho Minute. 37. Cc bi tp Microsoft .NET37Bi 3Nhng khc bit gia VB.NET vi VB6V B.NET, cn gi l VB7, chng qua l C# vit theo li Visual Basic.Nay VB7 hon ton l Object Oriented, tc l cho ta dng li (reuse)classes/forms theo cch tha k tht thoi mi, nn n khc VB6 nhiulm.Du vy, i vi VB6 programmers hc VB.NET khng kh. L do lVB.NET khng cho thm nhiu t mi (reserved words). Ni chung cc nim mi trong VB.NET u d lnh hi, nht l khi em ra p dngcch thc t. l nh Microsoft vn gi nguyn tc du v lm sn(ca VB6) nhng g rc ri pha sau sn khu, ta c th tp trung vovic tm kim mt gii php, thay v qu bn tm vo cch thc lm mtvic g. Chnh nguyn tc y gip Microsoft chiu m c 3 triuVB6 programmers trn khp th gii. VB.NET cng hin cho VBprogrammers mt cng c rt hu hiu dng cho mi hon cnh, tdatabase, desktop, distributed, internet cho n real-time hay mobile(pocket PC).Nhng u im (features) ca VB.NET n t chc nng ca .NETFramework. N mang n phng tin lp trnh cho mng cch ObjectOriented nh XML, Remoting, Streaming, Serialisation, Threading .v.v...Nhng th ny tuy l nhng khng kh hc, ngc li s tit kim rtnhiu th gi.Mc du VB6 l mt ngn ng lp trnh trng thnh v hiu nng, chcchn hy cn tn ti trong nhiu nm na, nhng hc thm VB.NET lmt u t tng i t tn km v m bo hu li gp bao nhiu lntrong hng thp nin ti.Trong bi ny ta s bn v nhng im khc nhau gia VB6 v VB.NETt quan im ngn ng lp trnh. Trong mt bi khc ta s bn v nhngchc nng i tng (Object Oriented) ca VB.NET.NamespacesNamespaces l mt cch t tn gip sp t cc Classes ta dngtrong program mt cch th t hu d tm kim chng. Tt c code trong 38. Cc bi tp Microsoft .NET38.NET, vit bng VB.NET, C# hay ngn ng no khc, u c chatrong mt namespace.im ny cng p dng cho code trong .NET system class libraries.Chng hn, cc classes ca WinForms u nm trongSystem.Windows.Forms namespace. V cc classes dng cho collectionsnh Queue, Stack, Hashtable .v.v.. u nm trong System.Collectionsnamespace.Tt c code ta vit trong program ca mnh cng u nm trong ccnamespaces.Trc y trong VB6, mi khi nhc n mt Class trong mt COM tnCompName ta vit CompName.classname (cn gi l PROGID) , tc lcng dng mt dng namespace.Tuy nhin phng php ny c mt vi gii hn: a ch ca class b buc cng vo component angcha n. Nhng classes khng nm trong mt COM componentth khng c "namespace". Cch gi tn PROGID ch c mt bc thi, khng cbc con, bc chu. Tn ca Component lun lun c hiu lc trn khpc computer.Namespaces trong .NET khc phc c mi gii hn ni trn trongVB6.Nhiu assemblies c th nm trong cng mt namespace, ngha l classestuyn b trong cc components khc nhau c th c chung mtnamespace. iu ny cng p dng xuyn qua cc ngn ng, gip chomt class vit trong VB.NET c th nm trong cng mt namespace vimt class vit trong C#, chng hn.Hn na, trong mt assembly c th c nhiu namespaces, d rng thng 39. Cc bi tp Microsoft .NET39thng ta ch dng mt namespace duy nht cho tt c cc classes trongy.Nh l mt assembly trong .NET th i khi tng ng vi mt COM component. Tt c code trong .NET u nm trong nhng assemblies.By default, tn ca project c dng lm namespace. Nu bn right clickln project name NETListbox trong Solution Explorer ca programDemo, ri chn Properties trong popup menu, IDE s hin th PropertyPages dialog nh di y:Bn thy Root namespace ca project l NETListbox. Bn c th thayi tn namespace y nu bn mun.Namespaces c th c phn chia th bc ging nh Folders trong mtFile Directory. N s gip user sp t cc classes theo ng nhm chotrong sng v d c. Th d bn ang vit mt program cho mt hngsn xut, bn s dng namespace NhSnXut root level. Bn trongnamespace y bn s to thm cc nhnh ca chng trnh nh: NhSnXut.TnKho NhSnXut.SnPhm NhSnXut.KTon.ChiPh NhSnXut.KTon.ThuNhp 40. Cc bi tp Microsoft .NET 40Nh th ta nh ngha mt base namespace tn NhSnXut, vinhng namespaces con, chu bn trong, mi namespace c cha classes,modules, enums, structures v cc namespaces khc.Mi namespace cha nhng phn ca code thch hp cho n trongprogram ni chung. Trong File Directory, ta c th c hai files d mangcng tn nhng nm trong hai folders khc nhau. Ging nh vy, trong.NET ta c th c hai classes c cng mt tn nhng nm trong hainamespaces khc nhau. l v khi ta vit tn ca mt class vi cnamespace ca n th c th phn bit vi mt class khc vi cng tn.Local v Global NamespacesKhc vi COM components vi "namespace" ca chng p dng chokhp c computer, namespaces ca .NET thng thng l Local, ch capplication program ca n thy m thi. .NET cng h tr Globalnamespace, nhng phi c k tn (digitally signed) v ng k vi.NET runtime cha n trong global assembly cache.Cng vic lm mt namespace Global rc ri nh th gim thiutrng hp ta tr v tnh trng DLL hell trc y.Dng NamespacesTa c th dng namespaces bng cch ni thng ra (explicitly) vinguyn tn (Direct Addressing) hay hm (implicitly) vi Importkeyword. Nhng iu tin quyt l ta phi reference ci assembly chanamespace m ta mun dng. Ta thc hin vic y vi Menu commandProject | Add References. Khi Add References dialog hin ra, chn Tab.NET cho standard .NET components hay Tab Projects cho DLL camt .NET project khc , highlight DLL bn mun ri click Select button,on click OK. 41. Cc bi tp Microsoft .NET 41Chng hn ta mun read v write t stdio (ci console input/outputstream). Ci namespace ta cn s l System.Console. Trong cch DirectAddressing ta s code nh sau vit hng ch "Cho th gii":System.Console.WriteLine ("Hello world!")Nu ta dng Import keyword bng cch nht vo cu ImportsSystem.Console u code module, ta c th code gn hn:WriteLine ("Hello world!")Di y l mt s namespaces thng dng:Namespace Chc nng Classes in hnhc/Vit files v cc data FileStream, Path, StreamReader,System.IOstreams khc StreamWriterBitmap, Brush, Pen Color, Font,System.Drawing haGraphicsDataSet, DataTable, DataRow,System.Data Qun l dataSQLConnection, ADOConnection 42. Cc bi tp Microsoft .NET 42To v qun l cc loi ArrayList, BitArray, Queue, Stack,System.Collectioncollections HashTableSystem.Math Tnh ton Sqrt, Cos, Log, MinSystem.Diagnostics DebugDebug, TraceLm vic vi XML, XMLDocument, XMLElement,System.XMLDocument Object Model XMLReader, XMLWriterCho php kim sot anSystem.Security Cryptography, Permission, PolicyninhAliasing Namespaces (dng b danh)Khi hai namespaces trng tn, ta phi dng nguyn tn (k c gc tch) phn bit chng. in hnh l khi ta dng nhng namespaces lin h nVB6 nh Microsoft.Visualbasic. Thay v code:Microsoft.Visualbasic.Left ( InputString,6)ta tuyn b:Imports VB6= Microsoft.VisualbasicSau ta c th code:VB6.Left ( InputString,6)Dng Namespaces keywordTrong th d v program c Root Namespace l NhSnXut nh ni trn,nu ta mun t ra mt namespace con l TnKho, ta phi dngNameSpace keyword trong code nh sau: Root Namespace l NhSnXutNamespace TnKho Class PhngLnhCode cho Phng Lnh End ClassEnd Namespace 43. Cc bi tp Microsoft .NET43By gi mun ni n class PhngLnh bn trong namespace TnKho tas code nh sau:NhSnXut.TnKho.PhngLnhThay i trong Data TypesTt c u l ObjectMt thay i ln cho Data Type ca VB.NET, l nhng variables dngData Type a phng nh Integer, Single, Boolean,.v.v.. u l nhngObjects. Chng u c derived (xut pht) t Class cn bn nht tnObject trong VB.NET. Nu bn th dng Intellisense xem c baonhiu Functions/Properties mt Object loi Integer c, bn s thy nhdi y:Trong .NET, Integer c bn loi: Byte (8 bits, khng c du, tc l t 0n 255), Short (16 bits, c du cng tr, tc l t -32768 n 32767),Integer (32 bits, c du) v Long (64 bits, c du). Nh vy Integer bygi tng ng vi Long trong VB6, v Long by gi ln gp i trongVB6.Floating-Point Division (Chia s ni)Vic chia s ni (Single, Double) trong VB.NET c lm theo ng tiuchun ca IEEE. Do nu ta vit code nh sau:Dim dValueA As DoubleDim dValueB As DoubledValueA = 1dValueB = 0 44. Cc bi tp Microsoft .NET 44Console.WriteLine(dValueA / dValueB)Trong VB6 ta bit mnh s gp Division by Zero error, nhng yprogram s vit trong Output Window ch Infinity (v cc). Tng tnh vy, nu ta vit code:Dim dValueA As DoubleDim dValueB As DoubledValueA = 0dValueB = 0Console.WriteLine(dValueA / dValueB)Kt qu s l ch NaN (Not a Number) hin th trong Output Window.Thay th Currency bng DecimalVB.NET dng Decimal data type vi 128 bits thay th Currency datatype trong VB6. N c th biu din mt s ti 28 digits nm bn phidu chm cho tht chnh xc. H cng nhiu digits nm bn phi duchm th tm tr s ca Decimal cng nh hn.Char TypeVB.NET c c Byte ln Char data type. Byte c dng cho mt s nh0-255, c th cha mt ASCII character trong dng con s.Char c dng cha mt Unicode (16 bit) character. Char l mtcharacter ca String.String TypeNhn lt qua, String trong VB.NET khng c v khc VB6 bao nhiu.Nhng tr khi ta mun tip tc dng cc Functions nh InStr, Left, Midand Right trong VB6, ta nn xem String l mt object v dng nhngProperties/Functions ca n trong VB.NET cho tin hn. Sau ny ta shc thm v String ca VB.NET trong mt bi ring. nim fixed-length (c chiu di nht nh) String trong VB6 khng cndng na. Do ta khng th declare: 45. Cc bi tp Microsoft .NET45Dim myString As String * 25Object thay th VariantMt trong nhng data types linh ng, hiu nng v nguy him trongVB6 l Variant. Mt variable thuc data type Variant c th cha gnnh th g cng c (tr fixed-length string), n t ng thch nghi bntrong cha tr s mi. Ci gi phi tr cho s linh ng y l programchy chm v d c bugs to ra bi s bin i t data loi ny qua loikhc khng theo d tnh ca ta.VB.NET thay th Variant bng Object. V trn phng din k thut ttc data types trong .NET u l Object nn, ging nh Variant, Object cth cha th.Ni chung, du Object ging nh Variant, nhng trong .NET ta phi nir ra (explicitly) mnh mun lm g. Ta th xem mt th d code trongVB6 nh sau:Private Sub Button1_Click() Dim X1 As Variant Dim X2 As Variant X1 = "24.7" X2 = 5 Debug.Print X1 + X2Cng hai s vi operator + Debug.Print X1 & X2Ghp hai strings li vi operator &End SubKt qu hin th trong Immediate Window l :29.724.75Trong VB.NET, ta phi code cho r rng hn nh sau c cng kt qunh trn hin th trong Output Window:Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesButton1.Click 46. Cc bi tp Microsoft .NET46 Dim X1 As Object Dim X2 As Object X1 = "24.7" X2 = 5 Console.WriteLine(CSng(X1) + CInt(X2)) Console.WriteLine(CStr(X1) & CStr(X2))End SubCType StatementTrong VB.NET c Option Strict by default. N bt ta phi thn trngtrong cch dng data types. V Object c th cha bt c th g, khi tamun dng n nh mt loi data type hay class no, ta phi i Object rath y bng CType, th d:Class Product Public Description As StringEnd ClassPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesButton1.Click Dim X As Object X = New Product()Treat X like an actual product CType(X, Product).Description = "Soft Drink" Console.WriteLine(CType(X, Product).Description)End SubMc d X c instantiated nh mt Product, n vn c xem nh mtObject variable. Do mi khi mun dng n nh mt Product ta phinh n CType. T chuyn mn trong programming gi l TypeCasting.Thay i trong cch tuyn b VariablesTuyn b nhiu Variables 47. Cc bi tp Microsoft .NET47Trong VB6 ta c th Declare nhiu variables trn cng mt hng nh:Dim i, j, k As IntegerKt qu l ch c k l Integer, cn i v j l Variant (c th l iu bnkhng ng). Trong VB.NET th c ba i,j v k u l Integer, v nh thhp l hn.Tuyn b tr s khi uTrong VB6, sau khi declare variable ta thng cho n mt tr s khi unh:Dim X As IntegerX = 12By gi trong VB.NET ta c th gp chung hai statements trn li nhsau:Dim X As Integer = 12Tuyn b ConstantsKhi tuyn b Constants trong VB.NET ta phi khai r Data type ca n lString, Integer, Boolean ..v.v.:Public Const myConstantString As String = "happy"Public Const maxStudent As Integer = 30Dim As NewTrong VB6 ta c khuyn khng nn code:Dim X As New Customerv VB6 khng instantiate mt Object Customer cho n khi X c dngn - chuyn ny rt nguy him v c th to ra bug m ta khng ng.Trong VB.NET ta c th yn tm code:Dim X As New Customer()v statement ni trn lp tc to ra mt Object Customer.Tuyn b Variable trong Scope ca Block 48. Cc bi tp Microsoft .NET48Trong th d di y, variable X c declared trong mt IF..THEN...END IF block. Khi execution ra khi IF block y, X s b hydit.Do , VB.NET s than phin l X undefined v n khng thy X bnngoi IF block. Lut ny cng p dng cho nhng Blocks khc nhDO...LOOP, WHILE...END WHILE, FOR...NEXT, .v.v..Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) HandlesButton1.Click Dim A As Integer = 5 Dim B As Integer = 5 If A = B Then Dim X As IntegerX is declared in this IF block X = 12 End If A=X X has been destroyed, so it is undefined hereEnd SubC l bn hi Declare Variable trong FOR...LOOP c li g, ti sao takhng Declare mt ln duy nht u?Th nht l Block gii hn scope (phm vi hot ng) ca mt variable n khng ng chm ai d gy nn bug, th hai l trng hp inhnh ta s cn feature ny l trong mt FOR...LOOP, c mi iteration tamun instantiate mt Object mi. Khi y ta cn Declare mt Objectvariable, instantiate Object , ri cha n vo mt collection chng hn.Truy cp Variable/Class/StructureTrong VB.NET ta c th quyt nh gii hn vic truy cp mt Variable,Class, Structure .v.v. bng cch dng cc keywords sau:Loi truy Th dCh thchcp Cho php u cng dng n c. Ta ch Public Classc th dng Public mc Module,Public ClassForEverybody Namespace hay File. Tc l ta khng th dng Public trong mt Sub/Function. 49. Cc bi tp Microsoft .NET49Cho php cc classes con, chu c dng. Protected ClassProtected Ta ch c th dng Protected mc ClassForMyHeirsClass. FriendCho php code trong cng mt Project cFriend StringForThisProject Asdng. StringCho php code trong cng module, class, Privatehay structure c dng. Lu l Dim coiPrivateNumberForMeOnly Asnh tng ng vi Private, do ta nn Integerdng Private cho d c.Ngoi ra, nh l nu container (Object cha) ca mtVariable/Class/Structure l Private th d ta c tuyn b mtVariable/Class/Structure nm bn trong container l Public ta cng khngthy n t bn ngoi.Thay i trong ArrayArray index t 0Trong VB.NET khng c Option Base v mi Array u c index btu t 0. Khi bn tuyn b mt array nh:Dim myArray(10) As IntegerKt qu l mt array c 11 elements v index t 0 n 10. UBound caarray ny l 10 v LBound ca tt c arrays trong VB.NET u l 0.Tuyn b Array vi nhng tr s khi uBn c th tuyn b Array vi nhng tr s khi u nh sau:Dim myArray() As Integer = { 1, 5, 8, 16 }Note the curly bracketsStatement lm hai chuyn: quyt nh size ca array v cho cc elementstr s khi u. dng feature ny, bn khng c ni r size caarray, m cho program t tnh.ReDim PreserveTrong VB.NET bn cng c th tip tc dng Preserve keyword ginguyn tr s ca cc elements trong mt array khi bn ReDim n. Tuy 50. Cc bi tp Microsoft .NET 50nhin c mt gii hn cho array vi hn mt dimension - bn ch c thresize dimention cui (bn phi) , nn nhng hng code sau y hp l:Dim myArray(,) As StringReDim myArray(5, 5)ReDim Preserve myArray(5, 8)Thay i trong User-Defined Type nim User-Defined Type (UDT) rt tin cho ta gom cc mnh datalin h li thnh mt data type c cu trc. Trong VB6 ta dng n nhsau:Public Type UStudent FullName As String Age As IntegerEnd TypeVB.NET cng gi y c tnh ca UDT nhng thay i ch Type thnhStructure:Public Structure UStudent Public FullName As String Public Age As IntegerEnd StructureLu cc Structure Members (nh FullName , Age ) cn phi cDeclared vi keyword Dim, Public, Private hay Friend, nhng khng thdng Protected v Structure khng th Inherit t mt Structure khc. Sd, c dng Private l v bn trong Structure c th c Property,Sub/Function .v.v..Thay i trong CollectionsVB6 h tr Collection v sau ny Windows Scripting Host Library cho tacollection kiu Dictionary. VB.NET cho ta mt thnh phn collection rthng hu trong Namespace System.Collections. V Collection l mttrong nhng cng c rt thng dng v hiu nng trong VB.NET nn ta sc mt bi dnh ring cho collection sau ny. 51. Cc bi tp Microsoft .NET 51Di y l danh sch cc collections ta s dng thng xuyn:Collection Chc nngArrayListDynamic Array t ng ln ln khi elements c b vo.BitArray Array cha tr s Boolean (True/False).HashTable Collection cha nhng cp key-value data, cho ta dng lm t in. Cha mt FIFO (First In, First Out) structure. Element c th l bt cQueue Object loi no.StackCha mt LIFO (Last In, First Out) structure.SortedList Cha mt danh sch nhng cp key-value data c sp theo th t.Arithmetic Operators miVB.NET cho ta thm cch vit Arithmetic Operator mi m Cprogrammers rt thch t lu nay.X += 4 tng ng vi X = X + 4 Mess &= " text" tng ng vi Mess = Mess & " text"Arithmetic Operation Trong VB6 Cch vit tc miCng X = X +5X += 5TrX = X - 10X -= 10Nhn X=X*7 X *= 7Chia X = X / 19X /= 19Chia Integer X = X13X = 13Ly tha X=X^3 X ^= 3Ghp Strings X = X & "more text" X &= "more text"Ta vn c th tip tc dng cch vit trong VB6, nhng by gi c thmmt cch vit gn hn. 52. Cc bi tp Microsoft .NET52Short Circuit trong IF..THEN StatementTrong VB6, nu ta vit:Dim myInt As IntegermyInt = 0If (myInt 0) And (17myInt < 5 ) ThenTh s b Division by Zero error, v mc du phn (myInt 0) l False,nhng VB6 vn tip tc tnh phn(17myInt < 5 ), v to ra error v 17 chia cho mt s 0.Trong vi ngn ng lp trnh khc, khi (myInt 0) l False th n khngtnh thm na, tc l n ni rng khi mt phn ca AND l False th nhtnh kt qu ca Logical Statement trong IF phi l False. c tnh nygi l Short-Circuit (i tc).Nu ta dng code ni trn trong VB.NET, n vn cho Division by Zeroerror ging nh VB6. Tuy nhin, nu ta mun dng c tnh Short-Circuitth ta ch cn thay th ch And bng AndAlso nh sau:Dim myInt As IntegermyInt = 0If (myInt 0) AndAlso (17myInt < 5 ) ThenShort-Circuit cng p dng cho Logical OR khi ta thay th ch Or bngOrElse ni rng khi phn u ca OR l True th nht nh kt quca Logical Statement trong IF phi l True.Khng cn Set statement cho ObjectTrong VB6 ta c th vit:Set x = New ProductSet w = xTrong VB.NET s c vit li nh sau: 53. Cc bi tp Microsoft .NET 53x = New Product()w=xBy gi ta khng cn phi nh dng ch Set khi ni n Object.Thay i trong cch vit Property routinesDng mt Property duy nhtNu trong VB6 ta vit:Private mdescription as StringPublic Property Let Description (Value As String) mdescription = ValueEnd PropertyPublic Property Get Description() As String Description = mdescriptionEnd PropertyTrong VB.NET Let v Get uc hp li trong mt Property routine duynht v ta li dng ch Set thay cho ch Let (mc du ch Set khng cndng cho Object nh mi ni trn) nh sau:Private mdescription As StringPublic Property Description() As String Set (ByVal Value As String) mdescription = Value End Set Get Description = mdescription End GetEnd PropertyReadOnly v WriteOnly propertyBy gi nu Property l ReadOnly ta s vit: 54. Cc bi tp Microsoft .NET54Public ReadOnly Property Age() As Integer Get Age = 3 End GetEnd Propertyhay WriteOnly ta s vit:Private _data As IntegerPublic WriteOnly Property Data() As Integer Set (ByVal Value As Integer) _data = Value End SetEnd PropertyDefault PropertiesTa dng Default keyword to ra Default Property nh sau:Default Public Property Item(ByVal Index As Integer) As StringVB.NET bt buc ta phi t nht mt parameter cho Default Property.Dng Reserved Word lm Procedure NameTrong VB.NET ta c th dng Reserved Word lm Procedure Name bngcch n gia ngoc vung. Gi t ta mun dng ch Compare lm tnmt Function, ta s vit nh sau:Public Function [Compare] (ByVal v1 As Integer, ByVal v2 As Integer) As BooleanStructured Error HandlingTRY...CATCH...FINALLYVB.NET cho ta Structure TRY...CATCH...FINALLY...END TRY xl error. Th d nh trong bi ton chia di y, nu b Division by 0error th ta s cho kt qu bng 0. D c error hay khng, program vnhin th kt qu trong Output Window qua statementConsole.WriteLine( result) trong phn Finally: 55. Cc bi tp Microsoft .NET 55Try result = a / bif this section has error jump to Catch sectionCatchonly get here if an error occurs between Try and Catch result = 0FinallyThis section is optional, but is always executed whether there is an error or not Console.WriteLine( result)End TryNu ta khng code g phn Catch th c ngha l chng ta c HandleError nhng li khng lm g ht, do Program s khng t. Ngc li,nu ta khng dng Try..Catch, th program s t.Nu mun nhy ra khi Try Structure bt c lc no ta c th dng ExitTry,Nhng cch CATCH errorTa c th dng Catch ging nh Select Case c mt cch x l chomi error:TryMain code goes hereCatch When Err.Number=5handle Error 5Catchhandle other errorsEnd TryTa c th Catch Error Exception data trong mt variable dng n nhsau:Catch e as Exception MessageBox.Show (e.ToString)Hai cch code trn c th c gp li thnh: 56. Cc bi tp Microsoft .NET 56Catch e As Exception When Err.Number = 5Thay i trong cch vit Sub/FunctionDng du ngoc khi gi ProcedureTrong VB6, nu khng dng keyword Call ta khng dng du ngoc khigi Sub. Trong VB.NET ta lun lun dng cp du ngoc, ngay c khikhng c parameter. Th d:ProcessData()x = New Customer()ByVal l Default cho mi ParametersTrong VB6, ByRef l default cho cc parameters passed vSub/Function. Tc l, Sub/Function c th v tnh lm thay thi tr snguyn thy ca parameter variables.Trong VB.NET, ByVal l default cho cc parameters passed vSub/Function. Do , n s trnh li lm ni trn.Optional Parameter cn c tr s DefaultTrong VB6 ta c th dng IsMissing bit xem Optional parameterc hin din khng. VB.NET b IsMissing v bt buc ta phi cungcp tr s Default cho Optional parameter trong phn proceduredeclaration ging nh sau y :Public Sub VerifyInput (Optional ByVal InputData As String="")trong th d ny ta cho Default value ca Optional parameter InputData lEmpty string.Return StatementHy xem mt th d dng Function return mt Customer Object trongVB6:Public Function GetCustomer (ByVal CustID As Long) As Customer Dim objCust As Customer Set objCust = New Customer objCust.Load CustID 57. Cc bi tp Microsoft .NET57 Set GetCustomer = objCustEnd FunctionTrong VB.NET ta c th dng Return Statement Return kt qu camt Function thay v dng chnh tn ca Function.Public Function GetCustomer (ByVal CustID As Long) As Customer Dim objCust As New Customer(CustID) Return objCustEnd FunctionDelegateDelegate l mt cch gip ta pass mt procedure nh mt parameter votrong mt method. nim ny c gi l Function Pointer hayCallback. Mt trng hp c in ta dng Delegate l cung cp mtdataArray sort vi mt Function so snh mi hai items trong array.Trong VB.NET ta dng AddressOf operator pass mt procedure. Tadeclare mt Delegate bng cch ni n l mt procedure di dng no,c bao nhiu parameters, mi parameter thuc loi data type no. Th d:Delegate Function IsGreater (ByVal v1 As Integer, ByVal v2 As Integer) as BooleanKhi vit code ta c yn tm s c cung cp mt Function c dng y vi khi code nh sau:Public Sub DoSort (ByRef DataArray() As Integer, Greater As IsGreater) Dim outer As Integer Dim inner As Integer Dim temp As Integer For outer = 0 To UBound(DataArray) For inner = outer + 1 To UBound(DataArray) If GreaterThan.Invoke( DataArray(outer), DataArray(inner)) Then temp = DataArray(outer) DataArray(outer) = DataArray(inner) DataArray(inner) = temp 58. Cc bi tp Microsoft .NET58 End If Next NextEnd Sub cch dng Method Invoke gi mt Delegate. By gi ta ch cncung cp Delegate routine m ta ha:Public Function myIsGreater (ByVal v1 As Integer, ByVal v2 As Integer) as Boolean Return ( v1 > v2)End FunctionTip theo y l cch ta dng Delegate ni trn:Dim myData() As Integer = { 2, 5, 8, 13, 26}DoSort (myData, AddressOf myIsGreater)Khi mt Subscriber registers vi mt Publisher mt routine Handlemt loi Event, ta cng dng delegate nh sau:AddHandler Button4.Click, AddressOf Button4_ClickKhi mt Event Click xy ra Button4, system s execute SubButton4_Click. 59. Cc bi tp Microsoft .NET59 Bi 4Nhng chc nng i Tng mi ca VB.NET (phn I)V B.NET khc phc nhng gii hn v i Tng (Object-Oriented)ca VB6 v mang n cho ta mt ngn ng lp trnh hon ton Object-Oriented (OO). Gn nh mi th trong VB.NET u lin h vi Object.Nu bn cn mi vi lp trnh theo hng i tng (Object OrientedProgramming) th phn gii thch sau y s gip bn lm quen vi n.Classes v Objects, nguyn tc AbstractionTheo phng php i tng, program c thit k mt phn codei din cho mt vt tng ng ngoi i. N c gi l Class.Khi lp trnh VB6 ta dng nhng controls t Toolbox nh Textbox,Label, Listbox ..v.v.. Textbox l Class ca cc Objects Text1, Text2.Cng nh Label1, Label2 l nhng Objects to ra t Class Label. Ta haydng hai t Class v Object ln ln nhau. iu khng quan trng,min l ta bit rng Class l mt nim Tru tng (Abstraction), cnObject l mt vt thc hu. Ging nh Class CaS l mt nim trutng, cn Object KhnhH ca Class CaS l mt ngi bng da, bngtht vi ting ht c nhiu ngi ngng m.Ta ni Object l mt Instance ca Class, v ta instantiate Class cmt Object. 60. Cc bi tp Microsoft .NET60Thng thng khi ta phn tch mt vn thit k chng trnh thcc Danh t (Nouns) l nhng Classes. Gi d ta phn tch hot ngca mt Nh Kho (warehouse). Ta c phng cha, ngn t, bi nhnhng, xe nng hng, nhn vin ..v.v., mi th u c th l mt Objectnn ta s thit k mt Class cho n.Fields, Properties, Methods v Events, nguyn tc EncapsulationClass CaS din t CaS l ngi nh th no. Nh SBiHt l mtPublic Variable ca Class, c gi l Field c th c c/vit trctip. Cn Kiu tc (di, ngn, mu en, c sc nu ...), Ging ht (cao,trm, ..). l nhng Properties. Chng cng ging nh Field nhng cimplemented (thi hnh) bng cch dng procedures Property Get vProperty Set. Property Set c th c coded kim sot nu "Kiutc" khng thch hp th s b loi b. Ngc li, nu "Kiu tc" thchhp v c p dng th ta s thy kt qu ngay l CaS li p thm ra.Thng thng Fields v Properties l cc Danh t (Nouns).Mt CaS c kh nng nCa, KTnLuNim, TrnhDin. Ta gi l nhng Methods m ta implemented bng Subs v Functions (th dnh Function KTnLuNim s return mt ch k). Thng thngMethods l nhng ng t (Verbs)i vi code bn trong Class th Property ging nh mt Method cn ivi Client (tc l program ang dng Class) th Property ging nhField.i khi, nu trnh din lu, CaS cn mt ly nc. CaS s Raise EventKht Nc nhn vin trong hu trng phc v.Ta gi chung Fields, Properties, Methods v Events l nhng ClassMembers (Cc Thnh vin ca Class)C mt ngoi l v s khc bit gi Class v Member, l khi ta dngcc Shared Class Members ca mt Class th ta khng nht thit phiinstantiate mt Object. Ta c th dng thng tn ca Class nh mtObject.Ci li im ca Object Oriented Programming l ta c th gi tt cnhng c im, kh nng ca mt Class vo trong mt Unit of Code(n v m) t tc. Khi chng ta lch s yu cu th CaS nCa. Ta bit 61. Cc bi tp Microsoft .NET 61CaS ca th thu ht lng ngi, nhng ta khng cn bit lm sao CaS tn trnh nh vy. khng phi l chuyn chng ta quan tm.i vi ta Class CaS l mt Black Box, ta khng bit v khng cn bitchuyn g xy ra bn trong. Nu sau ny CaS thay i k thut n ca ht d v hay hn, iu khng nh hng g n chng ta. c tnhOO y gi l Encapsulation (Gi kn).Cch ta lp trnh vi Class ch khc cch ta lp trnh trc y mt chtthi. Nu trc y ta phi t lm, th by gi ta instantiate mt Objectca Class chuyn tr nhng chuyn ta mun lm, ri bo n lm cho ta.So vi ngoi i, th d bn c m mt tim photocopy. Sau mt nm bnt trng coi, cng chuyn lm n n nh v c kt qu tt. Bn mun mthm mt tim photocopy na ch khc. Trc khi i lo ch khc bnhun luyn ngh photocopy cho mt ngi lm cng trung thnh, ri giaocho ngi y lm qun l thay th bn. Ngi l mt Object caClass QunLTimPhotoCopy. 62. Cc bi tp Microsoft .NET 62Tr li cch lp trnh, nhng cng vic bn lm hng ngy trong timphotocopy l nhng Methods. Tt c c, s sch ca tim l nhngProperties. Bn sp t mi tun phi gi ngi li qut dn tim,mi thng phi bo tr cc my photocopiers, l nhng Events. Bygi bn gi tt c nhng th y li thnh ClassQunLTimPhotoCopy.LnubninstantiateClassQunLTimPhotoCopy lm thnh ChTThng, ngi s thay th bnlm qun l tim photocopy u tin. Khi bn mun m thm tim thba, bn s instantiate Class QunLTimPhotoCopy mt ln na lmthnh DSuHng , ngi s thay th bn lm qun l tim photocopyth nh.Khi phn chia trch nhim cc phn code thnh nhng Class, bn cth tp trung t tng vo tng Class mt, khng cn phi c nh mi thtrong u khi gii quyt chuyn g. V code ca Class no ch lm vic vnh hng trong phm vi hot ng ca n, khng ng chm n aikhc. Nu c g trc trc, thng thng ta c th xc nh l li caClass no tng i d dng.C mt cu hi a rng theo phng php OO th: "Thay mt bng ncn bao nhiu programmers?". p: "Khng cn programmer no ht,bn bo n t thay bng ca n." (Li p khc: "Khng cnprogrammer no ht, Microsoft i tiu chun ra bng m.")Do , nu trc kia bn lp trnh t mnh lo liu cng chuyn th bygi hy giao cho cc Objects t lo cho chng. Tc l trc y, nu bnl ch in mi nm bn phi i gp la rung, th by gi bn bo cc tin phi t em np la vo trong kho cho bn. Sng khng? Ch trong th gii lp trnh OO, ta mi c th m mng nh vy.Inheritance (Tha K)Nguyn tc Encapsulation ni trn cho php ta dng nhiu Objects camt hay nhiu Classes mt cch an ton, tc l khng s Methods ca ccObjects gim chn ln nhau.Gi s ta mun dng li mt Class lm mt Class mi, c bit hn,th d nh ta mun lm nn mt Class CaS t Class NghS. Cch lm 63. Cc bi tp Microsoft .NET63y gi l Inheritance (Tha k). Cng vic tha k ny c thc hinqua mt qu trnh gi l Subclassing. y ta dng li Class NghS m hon ton khng ng n SourceCode (Ngun M) ca Class NghS. Nguyn tc y gi l Reusability(Dng li). Lu l nu ta dng li Source code m c sa i mt chttrong Source Code th khng th gi l Reuse c v c th vic sa iSource Code s gy ra bugs mi. Ta phi ch cn Inherit t ObjectCode ca mt Class cng c th mi tht s l Reuse.Ta dng Inheritance cho thm cc Class Members, tc l thm c tnhv chc nng. Th d NghS th c Property TmHn (NhyCm(Sentitive) , ThMng (Romantic),...), v Methods KTnLuNim,TrnhDin. Class CaS s gi y cc c tnh v chc nng y v thmSub nCa, Function HtNhcYuCu, .v.v..Tng t nh vy, ta cng c th tha k t Class NghS to ra ClassHaS. Class HaS s gi y cc c tnh v chc nng ca Class NghSnhng thm Function VChnDung, Sub TrangTr.Trong th d ni trn, ngi ta gi Class NghS l Parent Class, SuperClass hay Base Class. Cn Class CaS v Class HaS c gi l ChildClass hay SubClass. 64. Cc bi tp Microsoft .NET64Nu ta li Inherit Class CaS to ra Class CaSTnNhc v ClassCaSCNhc th trong trng hp ny CaS l Parent Class vCaSTnNhc vi CaSCNhc l Child Classes.Mi Cas l mt NghS nn ta c mi lin h "IS (L)" gia hai classesny. N khc vi mi lin h "HAS (C)". Th d nu trong Class CaSc mt Object thuc Class uBp, th mt CaS c th cho ta mt ban ngon nhng khng hn cho chnh CaS nu. N ging nh ngoi iCaS KhnhH mn mt u bp i khch. Ta s ni Class CaS cmi lin h HAS (C) vi Class uBp trong trng hp ny, chkhng phi Class CaS IS (L) mt Class uBp.Trong .NET ta ch c Single (n) Inheritance, tc l mt Class khngth Inherit t hai hay ba Classes khc. Ging nh ni Con tha k t Chav Cha tha k t ngNi, khng c nhc g n M hay BNi. MtChild Class ch c mt Parent Class, ngc li, mt Parent Class c thc nhiu Child Classes.Polymorphism (a dng)Polymorphism l kh nng dng Class Members trng tn ca Objectsthuc v cc Classes khc nhau. Th d Objects KhchHng vNhnVin u c Property Name. Nu ta c th lp trnh dng Name 65. Cc bi tp Microsoft .NET 65m khng cn ni r n thuc v Object KhchHng hay NhnVin th l Polymorphism.Polymorphism th hin di nhiu hnh thc:1. Late Binding (Hiu lc tr): C ngha l i n gi cht, khi execution, th code mi bit n ang lm vic vi loi Object no. Ch binding ni n "hiu lc", late binding l c hiu lc tr. iu ny c thc hin bng cch ha hn mt Object thuc Parent Class trong lc runtime ta c th giao cho code mt Object thuc Child Class. Th d ta ha vi khn gi s c mt CaS trnh din, lc m mn ta c th cung cp mt CaSTnNhc hay mt CaSCNhc.2. Overloading (Qu ti, c ri m cn cho thm) : Overloading cho php ta vit trong cng mt Class nhiu versions khc nhau ca Property hay Method. Chng c phn bit nh dng parameters khc data type hay con s parameters khc nhau. Th d mt version ca Sub c passed cho mt Integer Parameter, mt version khc c passed cho mt String Parameter, mt version khc li c passed cho hai parameters. Khi ta gi mt Method ca Class, n s da vo data type ca parameters ta pass v s parameters ta pass execute ng version ca Method. Mt th d v Overloading ngoi i l khi ta yu cu CaS n ca ta c php ngh CaS ht theo 66. Cc bi tp Microsoft .NET 66 Karaoke, hay c Ban Nhc Sng ph ha, hay thm c mt nhm ca s khc ph ha .v.v..3. Overriding (Ln quyn) : Overriding p dng cho Child Class i vi Parent Class. Trong Child Class ta cung cp mt Method cng tn, cng s parameters v cng parameter data type vi mt Method trong Parent Class ( y khng nht thit phi l Cha, c th l ngNi hay nhiu i trc) dng n thay th cho Parent Class Method. Ta ni Child Class thay i behaviour (tnh tnh, cch x s) ca Parent Class. i khi ging nh c LLin trc y Ht nhc hi hc, by gi c KhnhH tha k t c nhng override Method Ht ca c v c implement mt Method Ht mi dng cho nhc tr tnh. Lc runtime, nu mt Object khng c implementation ca mt Method th CLR (Common Language Runtime) s dng Method ca Parent Class ca n. Trong th d trn v c KhnhH c mt implementation cho method Ht nn system s dng method , thay v dng method Ht ca c LLin.Dng OO trong VB.NETTo mt Class miBn to mt Class mi trong VB.NET IDE bng cch dng MenuCommand Project | Add Class. Dialog Add New Item s hin ra, chnClass trong s hnh cc Icons nm trong khung bn phi ca Dialog. 67. Cc bi tp Microsoft .NET67Source code ca Class mi ny s c cha trong mt VB source filevi extension vb. Trong VB.NET tt c mi VB source files u cextension .vb. System s nhn din ra loi VB file (form, class,module,.v.v..) nh c content ca file, ch khng da vo file extension.Nu bn mun t tn cho Class mi ny l TheClass chng hn, th bnc th sa tn n trong Dialog. Khi bn click button Open mt file mi sc cho thm vo trong Project v n cha hai hng code sau:Public Class TheClassEnd Class 68. Cc bi tp Microsoft .NET 68Bi 5Nhng chc nng i Tng mi ca VB.NET(phn II)Dng OO trong VB.NETTo mt Class miClass KeywordTrong mt .vb file ta c th vit nhiu Classes, code ca mi Class nmtrong mt Class ... End Class block. Th d:Public Class TheClass Public Sub Greeting() MessageBox.Show("Hello world", MsgBoxStyle.Information, "TheClass") End SubEnd ClassMessageBox.Show v MsgBoxStyle.Information trong VB.NET thay thMsgBox v vbInformation trong VB6.Classes v NamespacesNhc li l .NET dng Namespace sp t cc Classes cho th t theonhm, loi. Namespaces c declared vi mt Block Structure gingnh sau:Namespace Vovisoft Public Class TheClass Public Sub Greeting() MessageBox.Show("Hello world", MsgBoxStyle.Information, "TheClass") End Sub End ClassEnd Namespace 69. Cc bi tp Microsoft .NET69Mun ni n bt c Class, Structure, hay th g c declared bn trongmt Namespace...End Namespace block ta phi dng tn Namespacetrc. Th d:Private myObject As Vovisoft.TheClassMt source file c th cha nhiu Namespaces, v bn trong miNamespace li c th c nhiu Classes.Ngoi ra, Classes thuc v cng mt Namespace c th nm trong nhiufiles khc nhau trong mt VB.NET project.Th d ta c mt source file vi code nh sau:Namespace Vovisoft Public Class TheClassCode End ClassEnd NamespaceV mt source file khc trong cng project vi code:Namespace Vovisoft Public Class TheOtherClassCode End ClassEnd NamespaceVy th trong Namespace Vovisoft ta c hai Classes TheClass vTheOtherClass.Nh l, by default, Root Namespace ca mt VB.NET project l tn caproject y. Khi ta dng Namespace block structure l chng ta ang thmmt tng tn vo Root Namespace. Do , trong th d trn nu tnproject l MyProject th, t bn ngoi project y, ta c th declare mtvariable nh sau:Private myObject As MyProject.Vovisoft.TheClass 70. Cc bi tp Microsoft .NET70To ra MethodsMethods trong VB.NET c hai th: Sub v Function. Function th phireturn mt kt qu. By default, parameters ca Method l ByVal chkhng phi ByRef. Tc l nu mun parameter no ByRef th phi nhkhai ra r rng.Nhc li l khi mt variable c passed vo trong mt method bngByVal th system cho method mt copy (bn sao) ca variable, do ,tr s ca variable khng b thay i bi cng tc ca method. Ngc li,nu mt variable c passed vo trong mt method bng ByRef thmethod dng chnh variable , do , tr s ca variable c th b thayi bi cng tc ca method.Ta c th gii hn vic s dng mt method bng cch p t mt AccessModifier (sa i quyn truy nhp) hay cn gi l Scoping keyword(phm vi hot ng): Private - ch cho php code trong cng Class cgi. Friend - ch cho php code trong cngproject/component c gi. Public - cho php ai gi cng c. Protected - cho php code trong subclasses (classescon, chu) c gi. Protected Friend - cho php code trong cngproject/component hay code trong subclasses cgi.To ra PropertiesTrong VB.NET ta ch dng mt routine duy nht cho mi Property, vihai ch Get v Set nh sau (khng cn dng ch Let ca VB6 na):Private mdescription As StringPublic Property Description() As String Set (ByVal Value As String) mdescription = Value 71. Cc bi tp Microsoft .NET 71 End Set Get Description = mdescription End GetEnd PropertyReadOnly v WriteOnly propertyBy gi nu Property l ReadOnly ta s ly phn Set ra v vit:Public ReadOnly Property Age() As Integer Get Age = 3 End GetEnd Propertyhay WriteOnly ta s y phn Get ra v vit:Private _data As IntegerPublic WriteOnly Property Data() As Integer Set (ByVal Value As Integer) _data = Value End SetEnd PropertyDefault PropertiesDefault Property l property ca Object m program dng khi ta ch chotn ca Object v khng ni r property no. Th d trong VB6 khi tacode:TextBox1 = "The house of rising sun"VB6 hiu rng ta mun dng Default Property text ca Textbox1 nncode y tng ng vi:TextBox1.text = "The house of rising sun"Trong VB6 khi ta dng keyword Set vi tn ca Object, th d nh: Dim myTextBox As Textbox 72. Cc bi tp Microsoft .NET 72 Set myTextBox = TextBox1program s hiu l ta mun ni n chnh Object myTextBox . Nukhng th n bit ta mun ni n Object Default Property m lm bingcode cho r ra.Trong VB.NET Default Property phi l mt Property array. MtProperty array l mt property c Indexed (ni n tng Item bngcon s Index) ging nh mt array. L do chnh ca s bt buc ny l khi ln ln gia hai trng hp ta ni n Default property ca mtObject hay chnh Object y, v trong VB.NET ta khng cn dng Setkeyword cho Object assignment na (ta ch cn dng keyword Set trongProperty m thi).By gi h mun ni n Default Property ca Object th phi dngIndex. Th d ni n chnh Object, ta code:myValue = myObject ni n Default Property Item 3 ca Object, ta code:myValue = myObject(3)S thay i t VB6 ny c ngha l mt property array procedure phinhn mt parameter. Th d:Private theData(100) As StringDefault Public Property Data(ByVal Index As Integer) As String Get Data = theData(Index) End Get Set(ByVal Value As String) theData(Index) = Value End SetEnd PropertyT nay ta khng th code:TextBox1 = "Good morning!"nh trong VB6 c na, m phi code: 73. Cc bi tp Microsoft .NET 73TextBox1.text = "Good morning!"V Property Text khng cn l Default Property ca TextBox.Overloading methodsMt trong nhng chc nng a din (Polymorphism) hng mnh nht caVB.NET l overload (qu ti, c ri m cn cho thm) mt method.Overloading c ngha l ta c th dng cng mt tn cho nhiu methods -min l chng c danh sch cc parameters khc nhau, hoc l parameterdng data type khc nhau (td: method ny dng Integer, method kia dngString), hoc l s parameters khc nhau (td: method ny c 2 parameters,method kia c 3 parameters).Overloading khng th c thc hin ch bng cch thay i data typeca Return value ca Function. Phi c parameter list khc nhau mic.Di y l th d ta dng Overloading code hai Functions tm data,mt ci cho String, mt ci cho Integer:Public Function FindData(ByVal Name As String) As ArrayListfind data and return resultEnd FunctionFriend Function FindData(ByVal Age As Integer) As ArrayListfind data and return resultEnd Function l ta c th cho mi overloading Function mt phm vi hot ng(Scope on implementation) khc nhau. Trong th d trn ta dng AccessModifier Public cho Function u v Friend cho Function sau.Object LifecycleObject Lifecycle (cuc i ca Object) c dng ni n khi noObject bt u hin hu v khi no n khng cn na. S d ta cn bit rcuc i ca mt Object bt u v chm dt lc no l trnh dng nkhi n khng hin hu, tc l cha ra i hay khut bng ri. 74. Cc bi tp Microsoft .NET74New methodTrong VB6, khi mt Object thnh hnh th Sub Class_Initialize cexecuted. Tng ng nh vy, trong VB.NET ta c Sub New(), gi lConstructor. VB.NET bo m Sub New() s c CLR gi khi Objectc instantiated v n chy trc bt c code no trong Object.Nu Sub Class_Initialize ca mt Class Object trong VB6 khng nhnparameter th Sub New() trong VB.NET chng nhng c nhn parametersm cn cho php ta nhiu cch gi n. S khc bit trong Constructorsca VB6 v VB.NET rt quan trng.Tng tng ta c mt Khun lm bnh bng lan; khun l Class cnnhng bnh lm ra t khun s l cc Objects bnh bng lan. Nu tamun lm mt ci bnh bng lan vi mt lp s-c-la trn mt th cngtc s gm c hai bc: 1. Dng khun (Class) nng mt ci Object bnh bnglan (dng Sub Class_Initialize) 2. ln mt bnh mt lp s-c-la (dng class PublicSub ThoaScla)n y, mi chuyn tng i n tha. By gi, nu khch hng munmt ci bnh bng lan dng trng vt thay v trng g th ta chu thuathi, v khng c cch no bo Sub Class_Initialize dng trng vt thay vtrng g ngay trong lc ang to dng ra Object bnh bng lan.Sub New() trong VB.NET c th nhn parameters nn n c th nhn chth dng trng vt ngay trong lc nng ci Object bnh bng lan.Ci dng n gin nht ca Sub New() m ta c th dng l khng passparameter no c (trong trng hp ny th ging nh SubClass_Initialize ca VB6). Ta code Sub New() trong Class nh sau:Public Class BanhBongLan Public Sub New()Code to initialise object here End SubEnd Class 75. Cc bi tp Microsoft .NET 75Ta instantiate mt Object bnh bng lan nh sau:Dim myBanhBongLan As New BanhBongLan() cho Users c s la chn khi instantiate Object, ta c th code thmnhng Sub New khc, mi Sub dng mt danh sch parameter khc nhau.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 TrngVt here Case "Ga"Code for TrngG here End Select End SubEnd ClassDng cng mt tn method implement nhiu methods khc nhau cgi l overload. l mt trng hp a dng (polymorphism) ca OOprogramming. Trong th d trn nu TrngVt v TrngG l hai loiData Types khc nhau th ta cng c th dng:Sub New (ByVal TrngVt As TrngVtDataType) instantiate bnh TrngVt vSub New (ByVal TrngG As TrngGDataType)instantiatebnhTrngG. 76. Cc bi tp Microsoft .NET76Nh th ta khi bn tm vi Select Case LoaiTrung khi ch dng mtSub New duy nht vi 1 parameter.Trong VisualStudio.NET, khi ta dng tn ca mt overloaded method,IntelliSense s hin th hng dn ta nh vo parameter list khcnhau ty theo method ta chn.TerminationTrong VB6 mt Object s b hu dit khi ci reference (ch dng nObject) cui cng b ly i. Tc l khi khng c code no khc dngObject na th Object s b t ng hu dit. System gi mt counter m s clients ang dng Object. Cch ny hay ch khi counter trthnh 0 th Object b hu dit ngay. Ta ni n c deterministicfinalization, ngha l ta bit r rng khi no Object bin mt.Tuy nhin, nu ta c hai Object dng ln nhau (gi l circularreferences), th ngay c n lc chng khng cn hot ng na, chngvn hin hu mi trong b nh v ci Reference counter ca c haiObjects khng bao gi tr thnh 0. Nu trng hp ny xy ra thng lnln system khng cn memory na, ta gi l memory leak (b r bnh) ..NET dng phng php khc qun l chuyn ny. C mi chc, mtprogram s chy kim xem c Object no khng cn reference na hu dit. Ta gi l Garbage Collection (nht rc). Ngay c trnghp hai Objects c circular references nhng nu khng c code no khcreference mt trong hai Objects th chng cng s c hu dit. C iu,cng tc nht rc chy in the background (pha sau hu trng) vi utin thp, khi CPU rnh rang, nn ta khng bit chc mt Object s b hydit n bao gi mi tht s bin mt. Ta ni n c nondeterministicfinalization.Ta c th p CLR nht rc lp tc bng code: System.GC.Collect()Tuy nhin, ta ch lm vic y khi kt qu thi. Tt hn, ta duyt li designca mnh cho php cc Objects ht xi c th ngi chi trong b nhch n lc c hy dit. 77. Cc bi tp Microsoft .NET 77Dng Dispose MethodNu ta c mt Object dng nhiu ti nguyn (resources) nh b nh,database connection, file handle,.v.v. v ta cn phi th cc ti nguyn rangay sau khi Object khng cn hot ng na, ta cn implement mtInterface tn IDisposable vi Implements keyword nh sau:Public Class TheClassImplements IDisposableBn phi vit code cho Sub Dispose ging nh sau:Private Sub Dispose() Implements IDisposable.DisposeVit clean up code y th cc ti nguyn raEnd SubSau bn vn phi vit code cho Client n gi Dispose Method trongIDisposable interface. Bn cn phi dng CType cast Object Class khigi Dispose.Dim objObject As New TheClass()CType (objObject, IDisposable).Dispose() ly i Reference n mt Object (gi l Dereference Object) bn cth dng:myObject = Nothing l ta khng c dng keyword Set nh trong VB6. Nh l sau khistatement trn c executed th myObject khng bin mt ngay nhngn i Garbage Collector n gii quyt.Tha kTha k (Inheritance) l kh nng ca mt Class t c interface(giao din) v behaviours (tnh tnh) ca mt Class c sn. Ci qu trnh lm nn vic y c gi l Subclassing. Khi ta to ra mt Class mitha k c interface ln behaviours t mt Class c sn l chng ta tora mt subclass ca Class nguyn thy. Ngi ta ni l mt mi linh is-a (l mt), ni Class mi l mt loi Class nguyn thy.Ta phn bit mi lin h is-a vi mi lin h has-a (c mt). Trong mi 78. Cc bi tp Microsoft .NET78lin h has-a, Object ch c th lm ch mt hay nhiu Objects t, nhngObject t l mt loi c th hon ton khc vi Object ch. biu din c tnh Inheritance ta hy xt trng hp mt cng ty cungcp Sn phm v Dch v. Ta c th code mt Class cho Sn phm(ProductLine) v mt Class cho Dch v (ServiceLine) , ring r nhau.Nhng v thy chng c nhiu im tng ng nn ta s code mt Classgi l Mn hng (LineItem), ri inherit t LineItem ra ProductLine vServiceLine.LineItem c cc properties ID, Item, Price (gi) v Quantity (s lng).N cng c mt Public Function cho Amount (s tin).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) 79. Cc bi tp Microsoft .NET79 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 FunctionEnd Class to Class ProductLine t Class LineItem ta phi dng Inheritskeyword. Mi Object ProductLine l mt Object LineItem vi ProductIDv Description. ProductID ca ProductLine c pass vo Sub New lc 80. Cc bi tp Microsoft .NET 80instantiate Object ProductLine. Cn Description l mt ReadOnlyproperty ca ProductLine. Ta c th code Class ProductLine nh 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 Vit code y c chi tit ca Product t Database trong c th c Description ca Product End SubEnd ClassStatement Inherits LineItem khin ProductLine tha k mi interface vbehaviours ca LineItem. Do ta c th code mt SubBtnProduct_Click hin th chi tit ca ProductLine trong mt Listboxnh 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) 81. Cc bi tp Microsoft .NET81End SubTrong code bn trn ta dng c property Item ca Class LineItem lnproperty Description ca Class ProductLine. C hai u l property caProductLine v n l mt SubClass ca LineItem.Ging nh vy, mt ServiceLine c th c ghi ngy gi cung cp service.Ta code Class ServiceLine nh sau:Public Class ServiceLine Inherits LineItem Private mdtDateProvided As Date Public Sub New() Make 1 as default number of services of this kind for invoice Quantity = 1 End Sub Public Property DateProvided() As Date Get Return mdtDateProvided End Get Set (ByVal Value As Date) mdtDateProvided = Value End Set End PropertyEnd ClassMt ln na ta dng Statement Inherits ni rng ServiceLine l mtSubClass ca LineItem. Ta thm property DateProvided vo interfacetha k t Class LineItem. 82. Cc bi tp Microsoft .NET82Bi 6Nhng chc nng i Tng mi ca VB.NET(phn III)Dng OO trong VB.NETNgn cn Tha kBnh thng (By default) class no cng c th c dng lm base class t ta tha k. Nhng i khi ta khng mun cho ai tha k t mtClass no , lm vic y ta dng keyword NotInheritable khi declareclass:Public NotInheritable Class KhngConEnd ClassKhi ta dng keyword NotInheritable ri th khng class no c thdng keyword Inherits to mt subclass t class y.Tha k v Phm vi hot ngKhi ta dng c tnh tha k to mt SubClass th class mi ny c mi methods, propertes v variables vi Access Modifier Public hayFriend ca SuperClass. Bt c th g declared l Private trongSuperClass th SubClass khng thy hay dng c. C mt ngoi l l New method. Cc Constructor methods cn phi cimplemented (nh ngha) li trong mi SubClass. Mt chc na ta s bn vo chi tit v im ny. lm sng t vn SubClass c th dng Class Members no caSuperClass, ta th code li Function Amount trong LineItem class bngcch khin n gi mt Private Function tn CalculateAmount tnh raAmount thay v n tnh trc tip nh trc y:Public Function Amount() As Single Return CalculateAmountEnd Function 83. Cc bi tp Microsoft .NET 83Private Function CalculateAmount() As Single Return mintQuantity * msngPriceEnd FunctionKhi ta SubClass LineItem to ra ServiceLine class, bt c ObjectServiceLine no cng tha k Function Amount v Function y cdeclared Public trong BaseClass LineItem. Ngc li, v FunctionCalculateAmount l Private nn c ServiceLine class ln bt c clientcode no dng mt LineItem Object u khng truy cp n c.Nh th, mc du ta gi Function Amount c, nhng n phin n giPrivate Function CalculateAmount th c b tr ngi khng? Khng saoc. V Function Amount nm trong cng Class vi Private FunctionCalculateAmount nn n c th gi c, d rng ta gi FunctionAmount t ServiceLine hay client code.Th d trong client code ta c nhng hng code nh 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 SubKt qu s c hin th trong message box, cho thy FunctionCalculateAmount c Function Amount gi dm cho client code drng c client code ln ServiceLine code u khng th gi trc tipc.im ny nhc ti nh li khi cn b, c ln b con trong vn em rach cho ba m ti c thng xoi thm rt ngon. Bn ti li xm thy 84. Cc bi tp Microsoft .NET84vy biu ti ln ly hai tri xoi n vn. V khng phi l ngi nhnn bn ti khng th ly uc xoi, bi Access Modifier ca thn xoi lPrivate trong nh ti. Nhng v ti l Public, nn bn ti c th nh tily dm.Protected Methodsi khi Public hay Private thi cha . Nu ta declare th g Private thn hon ton gii hn trong class, ngc li nu ta declare n Public (hayFriend) th n c th c dng trong subclasses hay client code.Tuy nhin, c lc ta mun mt class member ch c th c dng trongsubclasses thi, ch khng cho client code dng. Trong trng hp y tadng keyword Protected. Th d:Public Class FatherClass Protected DiSn As SingleEnd ClassPublic Class SonClass Inherits FatherClass Public Function ChiaCa() As Single Return Disn End FunctionEnd Class y ta c BaseClass FatherClass vi Protected Field Disn. Khngc client code no c th thy Field DiSn c. Th nhng bt cSubClass no ca FatherClass cng u tha k v dng c DiSn.Trong th d trn, mt ln na SubClass c mt Public method (ChiaCa)c th return mt protected value - nhng chnh value y, DiSn, khngtrc tip cho php client code dng.Overriding MethodsChng ta bit rng c tnh quan trng ca Inheritance l mt SubClasschng nhng tha k behaviours ca ParentClass m cn c th override 85. Cc bi tp Microsoft .NET85(ln quyn) cc behaviours y na. Chng ta thy mt SubClass c thextend (thm ra) ParentClass bng cch cho thm cc methods Public,Protected v Friend. Hn na, khi dng overriding, mt SubClass c thalter (sa i) behaviours ca cc methods trong ParentClass.Bnh thng (By default), ta khng th override methods trongParentClass tr khi cc methods y c declared vi keywordOverridable trong ParentClass. Th d:Public Class ClassCha Public Overridable Sub ChoHi() MessageBox.Show("Cho cc chu", "Class Cha") End SubEnd ClassTip theo, khi to mt SubClass, nu mun ta c th override behaviourca Sub ChoHi bng cch dng keyword Overrides nh sau:Public Class ClassCon Inherits ClassCha Public Overrides Sub ChoHi() MessageBox.Show("Tha cc Bc", "Class Con") End SubEnd ClassBy gi ta c th vit client code nh sau:Private Sub BtnSubClassObject_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles BtnSubClassObject.Click Dim obj As New ClassCon() obj.ChoHi()End SubKhi ta click button BtnSubClassObject program s hin th messagedialog di y: 86. Cc bi tp Microsoft .NET86Virtual MethodsTuy nhin, hy xem trng hp ta code nh 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.ChoHi()End SubTrc ht, y c v k k, ti sao declare mt variable loi ClassCham li instantiate mt object ClassCon. Chuyn hon ton bnhthng, v ClassCon l mt ClassCha. Tc l mt variable loi ClassChahay ClassCon u c th cha, tht ra l hold references to (point to, chti), mt instance ca ClassCon.im ny p dng tng qut khi ta dng Inheritance. Mt variable loiSuperClass c th hold reference to bt c SubClass Object no tha kt SuperClass y. l mt cch ta implement tnh a dng(polymorphism).u c th lm ta ngc nhin l khi ta click button BtnParentClassObjectta cng thy hin th message " Tha cc Bc". 87. Cc bi tp Microsoft .NET87Sao l vy? Variable obj c declared l ClassCha ti sao messagekhng phi l "Cho cc chu"? L do l Sub ChoHi ca ClassConc gi thay v Sub ChoHi ca ClassCha. Ta ni Sub ChoHi lVirtual method. Tt c methods trong VB.NET u l virtual. nim virtual ni rng ci implementation ca con chu tr nhttrong dng h c dng - khng cn bit l variable c data type lclass ca th h no trong dng h. Tc l, nu variable dng trong clientcode hold references to ClassngNi, ClassCha, ClassCon hayClassChu th method trong ClassChu c gi. Nu trong ClassChukhng c implementation ca method th ta gi method trong ClassCon,nu khng c th gi method trong ClassCha .v.v.. theo th t t b diln b trn.Keyword MeKeyword Me c dng khi ta mun ni r (explicitly) rng ta mundng method ca chnh ci Class ang cha code y, ch khng phi mtimplementation no khc ca method y.Cng c trng hp ta phi dng keyword Me ni ta mun dng class-level variable ch khng phi procedure-level variable c cng tn. Mtprocedure-level variable, tc l local variable ca mt method, c cngtn vi mt class-level variable c gi l shadowed variable. Th d:Public Class TheClass Private strName As String Public Sub DoSomething() Dim strName As String 88. Cc bi tp Microsoft .NET 88 strName = "Quang" End SubEnd Class y, variable strName c declared class-level v bn trong SubDoSomething. Bn trong method y local variables (k c shadowedvariables) s c dng v chng che y class-level variables tr khi tani r rng phi dng variable ca class-level bng cch dng keywordMe:Public Class TheClass Private strName As String Public Sub DoSomething() Dim strName As String strName = "Quang"thay i value ca local (shadowed) variable Me.strName = "Kim"thay i value ca class-level variable End SubEnd ClassKeyword MyBaseKeyword Me rt tin dng khi ta mun dng Class members ca chnhClass cha code. Tng t nh vy, i khi ta mun dng Class methodca BaseClass (cng gi l SuperClass), ch khng phi mtimplementation ca method y trong SubClass. Nh l mt virtualmethod lun lun gi implementation ca Class tr nht.T trong mt SubClass, nu mun gi mt method ca BaseClass ta dngkeyword MyBase nh sau:Public Class ClassCon Inherits ClassCha Public Overrides Sub ChoHi() MessageBox.Show("Tha cc Bc", "Class Con") MyBase.ChoHi() End Sub 89. Cc bi tp Microsoft .NET89End ClassBy gi nu ta chy Sub ChoHi ca ClassCon ta s c hai messages,mt ci t ClassCon theo sau bi mt ci t ClassCha.MyBase ch ni n BaseClass trc tip, tc l Class cha thi ch khngni n Class ng ni. Khng c cch no ni n hn mt th h.Du vy, keyword Mybase c th c dng cho bt c th g cdeclared Public, Friend hay Protected trong ParentClass. iu ny klun c nhng th m ParentClass tha k t cc th h trc trong gianh, tc l ClassngNi, ClassngC .v.v..Keyword MyClassV l do virtual method, ta s gp nhng trng hp rc ri nh khi codeca ParentClass li chy code ca SubClasses.Khi vit code ca mt class, t method ny ta thng gi nhng methodskhc nm trong cng class. Th d nh:Public Class ClassCha Public Sub V() ChoHi() End Sub Public Overridable Sub ChoHi() MessageBox.Show("Cho cc chu", "Class Cha") End SubEnd ClassTrong trng hp ny, V gi Sub ChoHi n tip. l vChoHi c declared Overridable nn rt c th mt SubClass simplement method ChoHi v ln quyn n. Th d:Public Class ClassCon Inherits ClassCha Public Overrides Sub ChoHi() MessageBox.Show("Tha cc Bc", "Class Con") 90. Cc bi tp Microsoft .NET 90 End SubEnd ClassV c tnh virtual ca ChoHi nn ta tng ClassCha execute chnh SubChoHi ca n nhng t ra n li execute code ca ChoHi trongClassCon. Trong code di y, mt Object ClassCon gi Sub V caClassCha: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 SubTrong ClassCha, Sub V gi ChoHi ca chnh n, tuy nhin SubChoHi y b overridden bi implementation ca ChoHi trongClassCon. Do , program s hin th message "Tha cc Bc".Nu ta khng mun nh vy, ta mun V execute chnh code caChoHi trong ClassCha th phi dng keyword MyClass nh sau:Public Class ClassCha Public Sub V() MyClass.ChoHi() End Sub Public Overridable Sub ChoHi() MessageBox.Show("Cho cc chu", "Class Cha") End SubEnd Class y ta khng th dng keyword Me v V c gi ChoHi class-level trong ClassCha ch khng phi trong mt SubClass, nhng boverridden. Hnh di y minh ha qu trnh gi V t client code: 91. Cc bi tp Microsoft .NET91Sub V tht ra nm trong ClassCha m ClassCon tha k nn Vc executed trong ClassCha v gi Sub ChoHi trong cng class (ClassCha). Nhng v ClassCon c mt implementation ca Sub ChoHinn n overrides ChoHi ca ClassCha.Overridding Method NewChng ta thy ta c th override methods v dng cc keywords Me,MyBase v MyClass gi cc overriden methods trong dy chuyn thak. Tuy nhin, i vi Constructor ca class th c nhng lut l c bitdnh ring cho method New.Nhng methods New khng t ng di truyn t BaseClass xungSubClass. Mi SubClass phi c mt implementation ring choConstructor d rng, nu mun, n c th gi vo BaseClass vi keywordMyBase:Public Class ClassCon Inherits ClassCha Public Sub New() MyBase.New() thm cc code khc initialise ti y End SubEnd Class 92. Cc bi tp Microsoft .NET 92Khi gi Constructor ca BaseClass, ta phi gi n trc nht - nu khngs b error. Tuy nhin ta khng cn gi Constructor ca BaseClass vConstructor ca BaseClass c gi t ng.C mt lut c bit l nu tt c methods New trong BaseClass u ihi parameters th ta phi implement t nht mt method New trongSubClass v ta phi t statement MyBase.New ngay pha u.D nhin l ta c th Overload method New trong SubClass, nhng taphi t lo liu cch gi mt method New thch hp trong BaseClass.To BaseClasses v Abstract MethodsCho n gi ta bn v virtual method vi c tnh override trongnguyn tc tha k. Trong cc th d trc y BaseClass cinstantiated thnh Object lm chuyn ny, chuyn kia. Nhng i khita mun to mt BaseClass ch dng cho tha k m thi.Keyword MustInherit (Phi c Tha K)Tr li ci th d v Inheritance vi Class LineItem. S d ta t ra ClassLineItem l v n cha nhng th chung cho c hai classes ProductLinev ServiceLine. Ch tht ra mt Object ca Class LineItem khng cha mi c tnh lm mt vic g thc t. Nu ta mun ni r rng ClassLineItem ch c dng to nhng SubClasses bng cch tha k tn, ta c th declare nh sau:Public MustInherit Class LineItemTc l ta ch thm keyword MustInherit thi, ch khng thay i gkhc. Kt qu l t nay Client code khng th instantiate mt Object tClass LineItem. Do dng code sau s b syntax error:Dim myObject As New LineItem()Thay vo , nu mun dng LineItem ta phi to SubClass t n.Keyword MustOverride (Phi b Ln Quyn)Tng t vi nim Phi-c-tha-k trong Class, ta cng cMustOverride cho mt method. C th trong BaseClass ta khai bo mtmethod, nhng ta i hi method y phi c mt implementation trongSubClass. Ta declare nh sau: 93. Cc bi tp Microsoft .NET93Dim MustOverride Sub CalculatePrice l y khng c thn th ca Sub CalculatePrice hay statementEnd Sub g c. Khi dng MustOverride ta khng c php cung cp mtimplementation cho method trong BaseClass. Mt method nh th cgi l abstract method hay pure virtual function, v n ch c phnkhai bo ch khng c phn nh ngha. Nhng abstract methods phic overridden trong bt c SubClass no ca BaseClass th mi dngc. Nu khng, ta s khng c phn implementation ca method u cv khi compile s gp syntax error.Abstract Base ClassesNu hp c hai nim MustInherit v MustOverride li ta s to ra mtabstract base class. y l mt Class ch c khai bo ch hon tonkhng c implementation. Ta phi SubClass t n th mi lm vic c,th d nh:Public MustInherit Class ClassCha Public MustOverride Sub V() Public MustOverride Sub ChoHi()End ClassK thut ny rt thch hp ta code ci sn hay b cc ca programngay trong lc thit k. Class no tha k ClassCha th phi implementc Sub V ln Sub ChoHi, nu khng s b syntax error.Nhn v mt phng din, abstract base class rt ging khai bo Interface.Nu dng Interface, chng ta c th khai bo nh sau:Public Interface ICha Sub V() Sub ChoHi()End InterfaceBt c class no chu implement interface ICha th phi implement cSub V ln Sub ChoHi, nu khng s b syntax error - do , tathy Interface rt ging mt abstract base class. 94. Cc bi tp Microsoft .NET 94S khc bit chnh gia abstract base class vi Interface l ch tha k.Khi ta to mt class con bng cch SubClass t ClassCha, chnh class cony li cng c th c SubClassed. My class chu ny s t ng thak V v ChoHi t class con.Trong khi y ni v Interface, mi class phi t implement ICha mt cchc lp v phi cung cp hai Subs V v ChoHi ca chnh n. Vth, nu ta khng c nh dng li code ca cc Subs khi ta to ccclasses mi th ta c th dng interface. Ngc li nu ta mun dng licode trong SubClass theo nguyn tc tha k th ta nn dng abstract baseclass. 95. Cc bi tp Microsoft .NET95Bi 7Nhng chc nng i Tng mi ca VB.NET(phn IV)Dng OO trong VB.NETShared class members ( Cc thnh vin dng chung ca class)Mc d Object rt hiu nng v hu ch, c khi ta ch mun truy cp ccvariables hay methods ca mt class lm vic m khng cn phiinstantiate mt Object no c. Tc l y nh trong qu kh, khi vit VB6,ta dng cc variables hay methods ca mt BAS Module. i khi gingnh thay v k giao ko vi mt thu (Object) thc hin mt cngtrnh, ta ch mun mn th hay chuyn vin lm vic gia cng ( gi ccmethods) thi.Shared MethodsTrong VB.NET chng nhng mt Class c cc methods v propertiesthng thng nh ta thy - tc l nhng methods v properties camt Object ta c th dng ngay sau khi Object y thnh hnh qua qutrnh instantiation - m cn c cc methods v properties ta c th dngm khng cn phi to ra mt instance no t Class. Chng c gi lshared methods. ( Trong cc ngn