You are on page 1of 214

Mn hc

CHUYN : Lp trnh ng dng s dng C#.NET


(ti liu lu hnh ni b) GV: Phm Vn Thun B mn K thut My tnh Khoa CNTT- H BKHN email: thuanpv@it-hut.edu.vn
1

Mc tiu mn hc
Sau khi kt thc mn hc ny, sinh vin c th
Trnh by c c trng c bn ca cng ngh .NET Trnh by c k thut lp trnh hng i tng s dng ngn ng C#.NET Lp trnh c mt ng dng Windows Form s dng ngn ng C#.NET, kt ni vi c s d liu SQL Server, lp bo co s dng cng c Crystal Report.

Lp trnh C#.NET

Ti liu tham kho chnh:


Programming C#, 4th Edition, Jesse Liberty Pro .NET 2.0 Windows Forms and Custom Controls in C#, Matthew MacDonald Professional C#, 2nd Edition, Wrox Press Ltd (Bn dch ting Vit) ftp://dce.hut.edu.vn/thuanpv/C_Sharp

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

Lp trnh C#.NET

Ni dung chng 1
1.1. Nn tng .NET (.NET Flatform) 1.2. Kin trc .NET (.NET Framework) 1.3. Bin dch trong .NET 1.4. Ngn ng lp trnh C#

Lp trnh C#.NET

1.1. Nn tng .NET (.NET Flatform)


.NET Platform l nn tng pht trin: - Cung cp giao din lp trnh (API) cho cc dch v (services) v cc hm API truyn thng ca h iu hnh Windows - Cung cp mt nn tng pht trin chung cho nhiu ngn ng lp trnh khc nhau ca Microsoft: C#, Visual J#, Visual Basic

Lp trnh C#.NET

Nn tng .NET (.NET Flatform)


.NET Platform bao gm cc nhm sn phm
Tp hp cc ngn ng (C#, VB), mt tp hp cc cng c pht trin bao gm Visual Studio .NET, th vin pht trin cc ng dng web (web and web services), cc ng dng Windows cng nh mi trng thc thi chung (Common Language Runtime (CLR)) Nn tng .NET 2.0 khng ch h tr cc ng dng trn my tnh c nhn, my ch m cn h tr cc thit b nhng (Cell phones, game boxes)
9

Lp trnh C#.NET

1.2. Kin trc .NET (.NET Framework)


Microsoft .NET h tr nhiu ngn ng khc nhau nh h thng - Common Type System (CTS) Quy nh nhng yu cu ti thiu mt ngn ng lp trnh c th tch hp vo .NET Common Language Specification (CLS) Kin trc .NET l tng ngay trn h iu hnh, bao gm:
5 ngn ng lp trnh chnh thc: C#, VB, VC++, Visual J# v Jscript.NET CLR (Common Language Runtime) Cc th vin lp trnh
10

Lp trnh C#.NET

.NET Framework

11

Lp trnh C#.NET

1.3. Bin dch trong .NET


.NET khng bin dch trc tip cc chng trnh thnh file thc thi. .NET bin dch cc chng trnh thnh cc assembly, cha cc m chng trnh trung gian ca Microsoft (Microsoft Intermediate Language MSIL) CLR s dch mt ln na, s dng chng trnh bin dch Just In Time (JIT) chuyn cc m MSIL sang m my v thc thi
12

Lp trnh C#.NET

Bin dch trong .NET

13

Lp trnh C#.NET

1.4. Ngn ng lp trnh C#


C# c pht trin bi nhm tc gi iu hnh bi Anders Hejlsberg v Scott Wiltamuth, tc gi ca Turbo Pascal v Borland Delphi. C# l ngn ng lp trnh hng i tng (Object Oriented Language)
H tr nh ngha v lm vic vi lp (class) H tr y ba c ch c trng ca lp trnh hng i tng: ng gi (encapsulation), k tha (inheritance) v a hnh (polymorphism)
14

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

15

Lp trnh C#.NET

Ni dung chng 2
2.1. Mi trng pht trin ng dng .NET 2.2. Chng trnh Hello World 2.3. Mi trng pht trin ng dng Visual Studio .NET

16

Lp trnh C#.NET

2.1. Mi trng pht trin ng dng .NET

Mi trng thc thi ng dng .NET: Microsoft .NET Framework


http://www.microsoft.com/downloads/

Trnh son tho v bin dch


- Visual Studio .NET IDE - Trnh son tho vn bn (Notepad, UltraEdit) & Trnh bin dch bng dng lnh (Command-line compiler)

17

Lp trnh C#.NET

2.2. Chng trnh Hello World


1) M chng trnh Visual Studio .NET 2005 2) To mt d n mi vi kiu ng dng console(HelloWorld)

18

Lp trnh C#.NET

Chng trnh Hello World


Chng trnh s t to mt khung d n Thm dng code n gin hin th thng bo helloworld ra mn hnh Bm F6 bin dch, F5 chy
19

Lp trnh C#.NET

Chng trnh Hello World

Kt qu khi chy chng trnh Hello World


20

Lp trnh C#.NET

Mt s khi nim c bn trong C#


Ch thch
Ch thch trn mt dng dng // Ch thch trn nhiu dng dng /* */ Trnh bin dch b qua ch thch Ch dng cho ngi c Nhm cc tnh nng c lin quan ca C# vo mt loi Cho php d dng ti s dng m Trong th vin .NET framework c nhiu khng gian tn Phi tham chiu ti s dng
21

Namespaces (Khng gian tn)

Lp trnh C#.NET

Mt s khi nim c bn trong C#


K t cch trng (White Space) Cha cc khong trng, k t xung dng v tabs T kho (Keywords) Cc t khng c dng lm tn bin,tn lp hay bt k th g khc C cc chc nng c bit khng th thay i trong ngn ng V d : class Tt c cc t kho u c vit thng
Lp trnh C#.NET
22

Mt s khi nim c bn trong C#


Lp (class): nh ngha mt kiu d liu, m t mt nhm cc i tng vi cc phng thc v thuc tnh
Phng thc (Method) Thuc tnh (Property)

23

Lp trnh C#.NET

Chng trnh Hello World


Using statement
using System; using System.Collections.Generic; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World"); } } }
24

Namespace

Class

Static function

Code statement

Lp trnh C#.NET

2.3. Visual Studio .NET IDE 2005

Giao din lm vic chnh


Lp trnh C#.NET

25

G li s dng VS.NET 2005


Set breakpoint -Nhn F9 hoc -Click chut tri vo bn l tri ca hng cn t breakpoint

26

Lp trnh C#.NET

G li s dng VS.NET 2005


Bt u qu trnh debug: nhn F5 (Debug -> Start Debugging

27

Lp trnh C#.NET

G li s dng VS.NET 2005


Xem gi tr ca cc bin, i tng

Xem gi tr cc bin, i tng ti ca s local

28

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

29

Lp trnh C#.NET

Ni dung chng 3
3.1. Kiu d liu (Types) 3.2. Bin v hng s (Variables and Constants) 3.3. Cc cu lnh v cu trc iu khin (Statements) 3.4. Cc ton t (Operators)

30

Lp trnh C#.NET

3.1. Kiu d liu (Types)


C# l ngn ng nh kiu mnh:
Phi nh ngha kiu d liu ca mi i tng (V d: integers, floats, strings, buttons) Trnh bin dch s kim tra v m bo ngn chn cc li do cc php gn sai kiu d liu

Phn loi d liu


Phn theo phng thc nh ngha: build-in (c sn) v user-defined (ngi dng t nh ngha) Phn theo cch thc lu tr: value (tham tr) v reference (tham chiu)
31

Lp trnh C#.NET

Kiu d liu (Types)


Kiu tham tr (value type)
Lu tr trong vng nh ngn xp (stack)

Kiu tham chiu (reference type)


a ch lu tr trong ngn xp (stack) D liu thc c lu tr trong vng nh Heap

Cho php lu tr i tng c kch thc ln

32

Lp trnh C#.NET

Kiu d liu c sn (build-in type)


C# h tr mt s kiu d liu c sn, mi kiu d liu ny tng ng vi mt kiu d liu h tr bi .NET CLS (Common Language System). C# c th s dng i tng do cc ngn ng khc trong b .NET to ra v ngc li (V d: VB.NET) Mi kiu d liu c kch thc xc nh

33

Lp trnh C#.NET

Kiu d liu c sn (build-in type)

34

Lp trnh C#.NET

Kiu d liu c sn (build-in type)

35

Lp trnh C#.NET

Escape Character

36

Lp trnh C#.NET

Chuyn i kiu d liu


C hai cch chuyn i kiu d liu c sn
Chuyn i ngm (implicity): qu trnh chuyn i din ra t ng v m bo khng b mt mt d liu
V d: short x=5;
int y=x;

Chuyn i tng minh (explicity) s dng ton t chuyn i (cast operator)


V d: (char)65 -> chuyn i t s sang k t

37

Lp trnh C#.NET

3.2. Bin v hng s (Variables and Constants)

Bin (variable):
Mt vng nh c nh kiu C th gn v thay i c gi tr Cc bin phi c khi gn trc khi s dng, nu khng, trnh bin dch s bo li
int myInt; System.Console.WriteLine ("Uninitialized, myInt: {0}", myInt);

38

Lp trnh C#.NET

Hng s
Hng s (Constant)
L bin s nhng khng th thay i gi tr sau khi khi gn. const int myConst=32; myConst = 30;

39

Lp trnh C#.NET

Kiu lit k
Kiu lit k cha mt tp hp cc hng s (enumerator list). Li ch ca enumerator
Cho php nhm mt tp hp cc hng s c lin quan vi nhau -> trnh phi khai bo nhiu hng s v tng mi quan h logic gia cc hng s Lm n gin ha m chng trnh
enum GoodWeather : uint { temperature=28, moisture=80, wind=5 }
Lp trnh C#.NET

40

Chui (string) v cch t tn trong C#


Chui l mt mng cc k t Khai bo v khi gn gi tr cho chui
string myString=Test String;

Trong C#, chng ta nn t tn cc bin, cc phng thc, cc lptheo khuyn co ca Microsoft


Tn bin: bt u bng ch thng (VD: someName) Tn phng thc v cc thnh phn khc: bt u bng ch hoa (VD: SomeOtherMethod)
41

Lp trnh C#.NET

3.3. Cc cu lnh (statements)


Mt chng trnh C# l mt dy cc cu lnh (statements) Mi cu lnh kt thc bi du ; Cc cu lnh c x l tun t theo chiu t trn xung di (tr cc cu lnh iu khin: lnh nhy, lnh lp)
int x; // a statement x = 23; // another statement int y = x; // yet another statement
42

Lp trnh C#.NET

Lnh nhy khng iu kin


C hai trng hp pht sinh lnh nhy khng iu kin:
C li gi mt phng thc: dng phng thc hin ti v chuyn sang (nhy khng iu kin) thc hin phng thc va triu gi, sau khi thc hin xong, tr v phng thc trc . S dng mt trong s cc lnh nhy khng iu kin: goto, break, continue, return hoc throw

43

Lp trnh C#.NET

Lnh nhy c iu kin


Cu lnh: ifelse Cu lnh iu kin lng (Nested if) Cu lnh chn: switchcase

44

Lp trnh C#.NET

Cu lnh iu kin ifelse


if (Biu thc iu kin) Cng vic 1 [else Cng vic 2]
int valueOne = 10; int valueTwo = 15; if(valueOne>=valueTwo) { Console.WriteLine("Max= {0}",valueOne); } else { Console.WriteLine("Max= {0}",valueTwo); }
45

Lp trnh C#.NET

Cu lnh iu kin lng (Nested if)


C th c s dng trong nhng cu lnh iu kin phc tp, iu kin lng nhau.
char charTest = 'z'; if (charTest < 'A') { Console.WriteLine("Khong phai chu cai hoa"); } else { if (charTest > 'Z') { Console.WriteLine("Khong phai chu cai hoa"); } else { Console.WriteLine("La chu cai hoa"); } }

46

Lp trnh C#.NET

Cu lnh chn: switchcase


switch (biu thc cn kim tra) { case trng_hp: Cc cu lnh Lnh nhy (break, continue) [default: Cc cu lnh cho trng hp mc nh] }

47

Lp trnh C#.NET

Cu lnh chn: switchcase


static void Main(string[] args) { const int Vietnam = 0; const int Laos = 1; const int Cambodia = 2; const int Thailand = 3; int country=Thailand; switch (country) { case Vietnam: Console.WriteLine("The Capital is Hanoi"); break; case Laos: Console.WriteLine("The Capital is Vientiane"); break; case Cambodia: Console.WriteLine("The Capital is Phnompenh"); break; default: Console.WriteLine("This country isn't belong to The Indochinese Peninsula"); break; }

48

Lp trnh C#.NET

Cu lnh chn: switchcase


static void Main(string[] args) { string country="Vietnam"; switch (country) { case "Vietnam": Console.WriteLine("The Capital is Hanoi"); break; case "Laos": Console.WriteLine("The Capital is Vientiane"); break; case "Cambodia": Console.WriteLine("The Capital is Phnompenh"); break; default: Console.WriteLine("This country isn't belong to The Indochinese Peninsula"); break; }

49

Lp trnh C#.NET

Cc lnh lp
Vng lp for Vng lp while Vng lp dowhile Vng lp foreach : s dng lp qua cc phn t ca mt mng hay mt tp hp

50

Lp trnh C#.NET

Vng lp for
for ( [initializers]; [expression]; [iterators]) statement
Khi to Biu thc kim tra Lnh lp Cng vic cn thc thi for (int i=0; i<10; i++) Console.WriteLine(Current value = {0},i);
51

Lp trnh C#.NET

Vng lp for (V d)
static void Main(string[] args) { for (int i = 0; i < 25; i++) { if (i % 5 == 0) { Console.Write("\n"); Console.Write("\t{0}", i); } else { Console.Write("\t{0}", i); } } }
52

Lp trnh C#.NET

Vng lp while

while (expression) statement


Biu thc kim tra
static void Main(string[ ] args) { int iTest=0 ; while(iTest<10) { Console.Write("{0}",iTest); iTest++; } }
53

Cng vic cn thc thi

Lp trnh C#.NET

Vng lp dowhile
do statement while expression
Cng vic cn thc thi Biu thc kim tra

static void Main(string[ ] args) { int i = 11; do { Console.WriteLine("i: {0}", i); i++; } while (i < 10); } Lp trnh C#.NET

54

3.4. Ton t (Operator)


Ton t c phn thnh nhiu liu khc nhau
Ton t gn (assignment operator): = Ton t ton hc (arithmetic operators): +, -, * Ton t tng, gim (increment and decrement operators): ++, --, -=, *= Ton t quan h (relational operators): ==, != Ton t logic (logical operators): &&, || Ton t ba thnh phn (Ternary Operator)

55

Lp trnh C#.NET

Ton t ton hc
Cc ton t c bn: cng (+), tr (-), nhn (*), chia (/) Ton t chia ly phn d (modulus): %
static void Main(string[] args) { int i1 = 17; int i2 = 4; Console.WriteLine("Integer:{0} \nFloat:{1} \nModulus:{2}", i1 / i2, (float)i1 / i2, i1 % i2); }

56

Lp trnh C#.NET

Ton t tng, gim


myInt=myInt+10 myInt=myInt-10 myInt=myInt*10 myInt=myInt/10
Postfix: myInt++ myInt-Prefix : ++myInt --myInt

myInt+=10 myInt-=10 myInt*=10 myInt/=10


Gn trc, bin i sau
VD: myInt=1; newInt=myInt++;

newInt=1

Bin i trc, gn sau


VD: myInt=1; newInt=++myInt

newInt=2
57

Lp trnh C#.NET

Ton t quan h
Ton t == != > >= < <= So snh bng So snh khc nhau So snh ln hn So snh ln hn hoc bng So snh nh hn So snh nh hn hoc bng
58

Tn

Lp trnh C#.NET

Ton t logic
Ton t && Chc nng Ton t v logic (x==3) && (y==7) -> false Ton t hoc logic (x==3) || (y==7) -> true Ton t ph nh logic !(x==3) -> true

||

Ch thch: d liu kim tra, x=5 v y=7


59

Lp trnh C#.NET

Ton t ba thnh phn


conditional-expression ? expression1 : expression2
Conditional-expression: biu thc kim tra iu kin Expression1: biu thc 1, thc hin khi biu thc kim tra tr v true Expression2: biu thc 2, thc hin khi biu thc kim tra tr v false V d: int valueOne = 10; int valueTwo = 20; int maxValue = valueOne > valueTwo ? valueOne : valueTwo;
60

Lp trnh C#.NET

Bi thc hnh s 1

61

Lp trnh C#.NET

Bi thc hnh s 1
Bi 1: Vit mt chng trnh cho php ngi dng nhp tn ca h, sau in li tn di dng mt li cho

Bi 2: Vit mt chng trnh gi mt phng thc tnh bnh phng ca mt s

62

Lp trnh C#.NET

Bi thc hnh s 1
Bi 3: Vit on chng trnh c vo mt s nguyn dng v kim tra s l chn hay l

Bi 4: Vit on chng trnh hin th bng cu chng ca s bt k (t 1 n 9)

63

Lp trnh C#.NET

Bi thc hnh s 1
Bi 5: Vit chng trnh hin th mt tam gic vung cn to thnh t cc k t bt k, c di cnh nhp t bn phm

64

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

65

Lp trnh C#.NET

Ni dung chng 4
4.1. C bn v lp trnh hng i tng 4.2. Lp v i tng (Class and Object) 4.3. K thut k tha v a hnh (Inheritance and Polymorphism) 4.4. K thut chng ton t (Operator Overloading) 4.5. Cu trc struct 4.6. Interfaces 4.7. Mng, ch s v tp hp (Arrays, Indexers) 4.8. X l chui 4.9. Bt ngoi l (Handling Exception) 4.10. Delegates v Events
Lp trnh C#.NET

66

4.1. C bn v lp trnh hng i tng

Quy cc thnh phn ca h thng v cc i tng Mt i tng l mt th hin ca mt lp (class)


Class Loi c vng Object Con c vng 1 Con c vng 2 Con c vng 3
Lp trnh C#.NET

67

Thuc tnh v phng thc


Lp v cc i tng thuc lp c chung cc thuc tnh (properties) v phng thc (methods)
Thuc tnh (Property): kch thc, mu, gii tnh Phng thc (Method): bi, th, n

68

Lp trnh C#.NET

K tha (Inheritance)

69

Lp trnh C#.NET

Cc quan h (relationships)
Cc i tng khng tn ti mt cch c lp, lun tn ti mi quan h gia n v cc i tng khc: tng qut ha (generalization) , cng tc (asscociation)
Cc vt nm trong phng L hoa trn bn Bn v gh thuc nhm ni tht
70

Lp trnh C#.NET

Tng qut ha (generalization)

Lp cha (fish) tng qut ha cc thuc tnh, phng thc chung ca cc lp con (Goldfish v Shark). Cc lp con cng c nhng thuc tnh, phng thc ring.
71

Lp trnh C#.NET

Quan h cng tc (Association)


Cc lp c lin kt (connected) hoc lin quan (related) vi nhau

Cd player + Speaker (Collaboration)

Shark eat fish

72

Lp trnh C#.NET

Quan h kt tp (Aggregation)
Th hin mi quan h gia tng th (the whole) v b phn (parts)
Tng th: n c vng B phn: tng con c vng

73

Lp trnh C#.NET

Quan h cu thnh (Composition)


L mt dng ca quan h kt tp, tuy nhin yu cu cht ch hn
Mi b phn (part) ch nm trong mt ci tng th (the whole) duy nht
VD: phng ng nh bn phi nm trong nh bn, khng th nm trong nh hng xm hay bt c ngi nh no khc

74

Lp trnh C#.NET

Quan h cu thnh (Composition)


Khi ph hy ci tng th th ng thi ci b phn cng b ph hy

Ph nh

Ph phng ng

75

Lp trnh C#.NET

Quan h (relationship)
S lng i tng tham gia vo quan h
Quan h 1 1
Mt lp hc trong mt phng hc

Quan h 1 nhiu
Mt gio vin c th dy nhiu lp

Quan h nhiu nhiu


Mt gio vin dy nhiu sinh vin Mt sinh vin hc nhiu gio vin

76

Lp trnh C#.NET

Tnh a hnh (Polymorphism)


a hnh: l kh nng c th thc hin cng mt hnh ng (phng thc) vi nhiu cch thc khc nhau khng ph thuc vo i tng c th thuc v lp no

77

Lp trnh C#.NET

4.2. Lp v i tng
nh ngha lp (class)
[attributes] [access-modifiers] class identifier [:base-class [,interface(s)]] {class-body}

Access-modifiers : quyt nh phm vi truy cp ti cc thuc tnh v phng thc ca lp Identifier : tn lp Base-class : lp c s (lp cha) Class-body : nh ngha cc thuc tnh v phng thc ca lp
78

Lp trnh C#.NET

Access-modifiers
Access-modifier
public

Gii hn truy nhp


Khng gii hn. Cc thnh phn public c th c truy xut bi bt c phng thc ca bt k lp no khc Ch c th truy xut bi cc phng thc ca chnh lp C th c truy xut bi cc phng thc ca chnh lp v cc lp dn xut (derived) t n C th c truy xut bi cc phng thc ca cc lp trong cng Assembly C th c truy xut bi cc phng thc ca lp , lp dn xut t lp v cc lp trong cng Assembly vi n
79

private

protected

internal

internal protected

Lp trnh C#.NET

V d nh ngha lp
public class Time { // Cc thuc tnh private int Year; int Month; int Date; int Hour; int Minute; int Second; // Cc phng thc public public void DisplayCurrentTime() { Console.WriteLine("Ngay, gio hien tai"); } }
Lp trnh C#.NET

Khai bo lp Cc thuc tnh (phng thc truy cp mc nh l private)

Phng thc ca lp

80

Khai bo v s dng i tng ca lp


public class Tester { static void Main() { Time t = new Time(); t.DisplayCurrentTime(); } }

81

Lp trnh C#.NET

To i tng (create object)


S dng t kha new Class_name Object_name = new Class_name( ); V d: Time t=new Time( ); i tng l bin kiu tham chiu, khng phi tham tr.
Bin t khng cha gi tr ca i tng Bin t cha a ch ca i tng c to trong b nh Heap
82

Lp trnh C#.NET

Hm to (constructor)
Khi to mt i tng -> gi hm to (constructor)
Hm to mc nh: s c CLR cung cp nu ngi lp trnh khng nh ngha Hm to do ngi lp trnh nh ngha

Hm to c chc nng:
To mt i tng ca lp v chuyn n sang trng thi xc nh (valid state) Hm to thng c dng khi gn cc thuc tnh ca i tng
83

Lp trnh C#.NET

Hm to mc nh (default constructor)
Hm to mc nh to i tng ca lp, ngoi ra khng lm g khc Cc thuc tnh c khi gn cc gi tr mc nh Kiu d liu numeric (int, long, ) bool char enum reference 0 false \0 (null) 0 null
84

Gi tr mc nh

Lp trnh C#.NET

Xy dng hm to
Hm to c tn hm trng tn i tng, khng c kiu d liu tr v v phm vi truy nhp thng l public. Hm to c th c tham s hoc khng
public Class_name() public Class_name( argument list )

V d:
public Time() public Time(System.Datetime t)
85

Lp trnh C#.NET

Xy dng hm to
public class Time { // private variables int Year; int Month; int Date; int Hour; int Minute; int Second; // contructor public Time(System.DateTime d) { Year = d.Year; Month = d.Month; Date = d.Day; Hour = d.Hour; Minute = d.Minute; Second = d.Second; } // public methods public void DisplayCurrentTime() { System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Date, Month, Year, Hour, Minute, Second); } }

86

Lp trnh C#.NET

Kim tra hm to
public class Tester { static void Main() { System.DateTime currentDate = System.DateTime.Now; Time t = new Time(currentDate); t.DisplayCurrentTime(); } }

87

Lp trnh C#.NET

Hm to sao chp (copy constructor)


h tr chc nng hm to sao chp.NET nh ngha mt interface ICloneable Class h tr hm to sao chp phi
implement interface ICloneable

public Object Clone() { return MemberwiseClone(); // shallow copy }


T xy dng hm to sao chp (hand-copying copy constructor)
88

Lp trnh C#.NET

T xy dng hm to
//hand-copying contructor public Time(Time previousTime) { Year = previousTime.Year; Month = previousTime.Month; Date = previousTime.Date; Hour = previousTime.Hour; Minute = previousTime.Minute; Second = previousTime.Second; }
89

Lp trnh C#.NET

Gi hm to sao chp
public class Tester { static void Main() { System.DateTime currentDate = System.DateTime.Now; Time t = new Time(currentDate); Time t2 = (Time)t.Clone(); t2.DisplayCurrentTime(); Time t3 = new Time(t2); t3.DisplayCurrentTime(); } }

90

Lp trnh C#.NET

T kha this
T kha this tr n th hin hin ti (current instance) ca i tng T kha this rt hu ch trong mt s trng hp
1) Ch r thnh phn (thuc tnh) ca i tng, trnh nhm ln vi tn bin, trnh s nhp nhng v tn
public void SomeMethod (int hour) { this.hour = hour; }
91

Lp trnh C#.NET

T kha this (tip)


2)Dng lm tham s truyn vo cho mt phng thc ca i tng khc, cho php phng thc c th tc ng n cc thnh phn ca i tng hin ti. class myClass
{ public void Foo(OtherClass otherObject) { otherObject.Bar(this); } }
92

Lp trnh C#.NET

T kha this (tip)


3) S dng cng vi indexer (Tm hiu sau) 4) Gi mt hm to t hm to khc ca lp
class myClass { public myClass(int i) { //... } public myClass( ) : this(42) { //... } }

93

Lp trnh C#.NET

T kha this (tip)


5) Gi tng minh cc phng thc, thuc tnh ca lp
public void MyMethod(int y) { int x = 0; x = 7; // assign to a local variable y = 8; // assign to a parameter this.z = 5; // assign to a member variable this.Draw( ); // invoke member method }
94

Lp trnh C#.NET

S dng cc thnh phn tnh (static memebrs)

Thnh phn tnh l cc thnh phn chung (thuc tnh, phng thc) ca lp
Truy xut cc thnh phn tnh thng qua tn lp Class_name.Static_Member C# khng cho php truy xut cc thnh phn tnh thng qua i tng (th hin ca lp) Cc thnh phn tnh c th c truy nhp, triu gi trc khi cc i tng ca lp c to ra Cc phng thc tnh khng th truy xut trc tip cc thuc tnh, phng thc khng tnh (nonstatic) 95
Lp trnh C#.NET

V d s dng thnh phn tnh


namespace StaticFields { public class Cat { private static int instances = 0; public Cat() { instances++; } public static void HowManyCats() { Console.WriteLine("{0} cats adopted",instances); } }
public class Tester { static void Main() { Cat.HowManyCats(); Cat frisky = new Cat(); Cat.HowManyCats(); Cat whiskers = new Cat(); Cat.HowManyCats(); } } }

96

Lp trnh C#.NET

Hy i tng (Destroying Object)


C# h tr c ch t ng thu gom rc (garbage collector) -> ngi lp trnh khng phi hy i tng mt cch tng minh. Nu i tng c s dng cc ti nguyn khc (files) -> ngi lp trnh phi t xy dng hm hy (Destructor) B thu gom rc t ng gi hm hy, cc phng thc khng gi mt cch tng minh.

97

Lp trnh C#.NET

Xy dng hm hy
V mt c php, hm hy trong C# ging vi C++
~Class_Name( )
protected override void Finalize() { try { // do work here. } finally { base.Finalize( ); } } Lp trnh C#.NET

~MyClass() { // do work here }

98

Truyn tham s cho phng thc


Mc nh, tham s truyn cho phng thc l kiu tham tr
Mt bn sao ca tham s c to ra Bn sao s b hy khi kt thc phng thc Gi tr ca tham s c truyn khng thay i sau khi kt thc phng thc public int AddValue(int value1, int value2) { return value1+value2; }
99

Lp trnh C#.NET

Truyn tham chiu


C# h tr truyn tham chiu s dng cc t kha
ref: truyn tham chiu, bin c tham chiu phi c khi gn trc khi truyn out: truyn tham chiu, bin c tham chiu khng cn khi gn trc khi truyn

100

Lp trnh C#.NET

Truyn tham chiu s dng t kha ref


nh ngha phng thc
public void GetTime( ref int h, ref int m, ref int s ) { h = Hour; m = Minute; s = Second; }

Gi phng thc
System.DateTime currentTime = System.DateTime.Now; Time t = new Time( currentTime ); int theHour = 0; int theMinute = 0; int theSecond = 0; t.GetTime( ref theHour, ref theMinute, ref theSecond ); Lp trnh C#.NET

101

Truyn tham chiu s dng t kha out


nh ngha phng thc
public void GetTime( out int h, out int m, out int s ) { h = Hour; m = Minute; s = Second; }

Gi phng thc
System.DateTime currentTime = System.DateTime.Now; Time t = new Time( currentTime ); int theHour; int theMinute; int theSecond; t.GetTime( out theHour, out theMinute, out theSecond ); Lp trnh C#.NET

102

Overloading methods and constructors


Khi mun c nhiu hm cng tn (VD: nhiu hm to (constructor) hay nhiu phng thc vi tham s u vo khc nhau) -> s dng k thut chng hm (Overloading) phn bit c hai hm vi nhau, phi cn c vo mt trong hai yu t
Khc tn Khc s tham s hoc kiu d liu ca tham s
void myMethod(int p1); void myMethod(int p1, int p2); void myMethod(int p1, string s1);
103

Lp trnh C#.NET

ng gi d liu thnh cc thuc tnh


ng gi d liu thnh cc thuc tnh em li hai li ch
Vn m bo mt giao din n gin cho cc i tng khc giao tip. D dng thay i m m khng nh hng ti giao din vi cc i tng khc. Tng tnh an ton d liu, kim tra c d liu khi gn

104

Lp trnh C#.NET

S dng cc thuc tnh (property)


private int hour; public int Hour { get { return hour; } set { hour = value; } }

Ly v gi tr ca thuc tnh

Thit lp gi tr ca thuc tnh


105

Lp trnh C#.NET

Thuc tnh ch c (readonly)


public static readonly int Year; public static readonly int Month; public static readonly int Date; public static readonly int Hour; public static readonly int Minute; public static readonly int Second; -> Ch

c th gn gi tr s dng hm to tnh

(static constructor) hoc khi gn ngay t ban u.


106

Lp trnh C#.NET

Bi thc hnh s 2

107

Lp trnh C#.NET

Bi thc hnh s 2

108

Lp trnh C#.NET

Bi thc hnh s 2

109

Lp trnh C#.NET

Bi thc hnh s 2

110

Lp trnh C#.NET

Bi thc hnh s 2

111

Lp trnh C#.NET

4.3. K tha v a hnh


Tng qut ha v c th ha (generalization and specialization) K tha (inheritance) a hnh (polymorphism) Lp tru tng (abstract class)

112

Lp trnh C#.NET

Tng qut ha v c th ha
C th ha Tng qut ha

Tng qut ha: cc lp i tng c nhng thuc tnh, phng thc chung c tng qut thnh cc lp cha C th ha: cc lp con k tha cc phng thc, thuc tnh ca lp cha v b sung thm thuc tnh, phng thc ca ring n 113
Lp trnh C#.NET

K tha (inheritance)
K tha (inheritance) l k thut th hin quan h c th ha (specialization)
public class ListBox : Control public class Button : Control

114

Lp trnh C#.NET

K tha (Inheritance)
u im ca k thut k tha
Kh nng ti s dng m. VD: lp ListBox c th s dng mt s phng thc, thuc tnh ca lp Control Kh nng s dng k thut a hnh (Polymorphism). VD: lp Control c phng thc Draw(), lp Listbox v Button cng c phng thc Draw().

115

Lp trnh C#.NET

To phng thc h tr a hnh


public virtual void Draw( ) { //Code statements } public override void Draw( ) { //Code statements }
116

Lp trnh C#.NET

V D K thut k tha v a hnh

117

Lp trnh C#.NET

Lp tru tng (abstract class)


S dng lp tru tng khi
Yu cu tt c cc lp con, k tha t n phi ci t mt hoc mt vi phng thc no .

c im ca lp tru tng
Lp tru tng l lp tn ti t nht mt phng thc tru tng Khng th to i tng ca lp tru tng

118

Lp trnh C#.NET

Khai bo lp tru tng


abstract public class Control { protected int top; protected int left; // constructor public Control( int top, int left ) { this.top = top; this.left = left; } abstract public void DrawWindow( ); }
Lp trnh C#.NET

Khai bo lp tru tng

Khai bo phng thc tru tng


119

K tha lp tru tng


public class Button : Control { public Button(int top,int left ):base(top, left) { } // implement the abstract method public override void DrawWindow( ) { Console.WriteLine( "Drawing a button at {0}, {1}\n",top, left ); } }
Lp trnh C#.NET

120

V D Lp tru tng

121

Lp trnh C#.NET

Root class: Object


Trong C#, tt c cc lp, thm ch cc kiu d liu c sn u dn xut, k tha t lp Object. Object l lp cao nht trong cy k tha ca C# Lp Object cung cp mt s cc phng thc o m cc lp con c th ci t v thc thi
Equals() GetType() ToString()

122

Lp trnh C#.NET

Boxing and Unboxing


Boxing v Unboxing l qu trnh cho php kiu gi tr (v d: integer) c th c x l nh l kiu tham chiu (objects)
Qu trnh Boxing din ra ngm nh (implicity): chuyn i ngm nh kiu gi tr sang kiu Object Qu trnh Unboxing din ra tng minh (explicity):chuyn ngc t kiu Object v kiu gi tr.

123

Lp trnh C#.NET

Boxing
using System; class Boxing { public static void Main( ) { int i = 123; Console.WriteLine ("The object value = {0}", i); } }

124

Lp trnh C#.NET

Unboxing
public class UnboxingTest { public static void Main( ) { int i = 123; //Boxing object o = i; // unboxing (must be explicit) int j = ( int ) o; Console.WriteLine( "j: {0}", j ); } }

125

Lp trnh C#.NET

Bi thc hnh s 3
Bi 1: Xy dng cc lp Fish, GoldFish v Shark theo thit k di y

126

Lp trnh C#.NET

4.4. Hm chng ton t


Mc ch ca hm chng ton t (Overloading Operator)
Cho php cc lp do ngi dng nh ngha c th c th c y cc chc nng nh cc kiu do ngn ng nh ngha VD: 1 lp phn s, c th c y cc php ton
Cng Tr Nhn Chia
Lp trnh C#.NET

127

Hm chng ton t

Fraction theSum = firstFraction.Add(secondFraction);

Fraction theSum = firstFraction + secondFraction;

128

Lp trnh C#.NET

S dng t kha operator Khai bo


public static Fraction operator+ (Fraction lhs, Fraction rhs)
S dng Fraction theSum = firstFraction + secondFraction;

Fraction.operator+(firstFraction, secondFraction)

129

Lp trnh C#.NET

Bi thc hnh s 3
Bi 2: Xy dng lp phn s (Fraction) theo thit k di y. S dng k thut chng ton t (Overloading Operator) xy dng cc ton t +, -, *, /, ==, !=

130

Lp trnh C#.NET

4.5.Cu trc struct


Struct l cu trc n gin do ngi dng t nh ngha, kh ging vi class
C hm to, thuc tnh, phng thc, ton t, index

Struct khc class


Struct khng h tr hm hy v c ch k tha Struct l kiu gi tr, khng phi kiu tham chiu Trong struct, cc thuc tnh khng c khi gn d liu khi khai bo
131

Lp trnh C#.NET

nh ngha struct
[attributes] [access-modifiers] struct identifier [:interface-list] { struct-members }
public struct Location { private int xVal; private int yVal; public Location(int x, int y) { xVal = x; yVal = y; } public override string ToString( ) { return ( String.Format( "{0}, {1}", xVal, yVal ) ); } public int x { get { return xVal; } set { xVal = value; } } }

132

Lp trnh C#.NET

To struct
S dng t kha new Location loc1 = new Location(200,300); Khng s dng t kha new (Cc thuc tnh xVal v yVal phi chuyn phm vi truy nhp thnh public) Location loc1; // Khng gi ti hm to loc1.xVal = 75; // Khi gn cc thuc tnh loc1.yVal = 225;
133

Lp trnh C#.NET

Interfaces
Mt lp hay struct thc thi (implement) interface -> m bo h tr y cc thuc tnh, phng thc, s kin v index c nh ngha trong interface Interface thng c so snh vi lp tru tng (abstract class) Khi mt lp hay cu trc thc thi mt interface, n phi thc thi tt c cc thnh phn ca interface (thuc tnh, phng thc, s kin)
134

Lp trnh C#.NET

nh ngha Interface
[attributes] [access-modifier] interface interface-name[:base-list] {interface-body}
Phm vi truy nhp: public, private, protected, internal, protected internal Interface-name: tn ca interface, nn bt u bng ch I V d: ICloneable, IRunable Base-list: danh sch cc interface m n m rng (extend) Interface-body: m t cc phng thc, cc thuc tnh, m lp thc thi cn ci t (Khng xc nh phm vi truy cp mc nh l public) 135
Lp trnh C#.NET

V d
interface IStorable { // no access modifiers, // methods are public // no implementation void Read(); void Write(object obj); int Status { get; set; } }
public class Document : IStorable { // store the value for the property private int status = 0; public Document(string s) {//code} public void Read() {//code} // implement the Write method public void Write(object o) {//code} // implement the property public int Status { get { return status; } set { status = value;} } }
136

Lp trnh C#.NET

Thc thi nhiu interfaces


Cc lp v cu trc c th implement nhiu interfaces khc nhau V d: lp ti liu (Document) va c kh nng lu tr (storable), va c kh nng nn (compressible) public class Document : IStorable, ICompressible

137

Lp trnh C#.NET

M rng Interfaces (extending)


C th m rng interface thm cc thuc tnh v phng thc mi interface ILoggedCompressible : ICompressible { void LogSavedBytes(); }

138

Lp trnh C#.NET

Kt hp interfaces
C th kt hp cc interfaces li vi nhau v thm cc phng thc, thuc tnh nu cn interface IStorableCompressible : IStorable, ILoggedCompressible { void LogOriginalSize(); }

139

Lp trnh C#.NET

Truy nhp cc thnh phn ca interface

Khng th trc tip to th hin ca interface IStorable isDoc = new IStorable(); Truy xut thnh phn ca Interface theo hai bc (hoc gp c hai bc)
To i tng ca mt lp implement interface Document doc = new Document("Test Document"); p kiu i tng ny thnh th hin ca interface IStorable isDoc = doc;
140

Lp trnh C#.NET

Casting to an interface
Khng bit r mt lp implement nhng interface no -> khi p kiu sang interface c th pht sinh li C# h tr 2 ton t s dng cho vic casting v kim tra
Ton t is

expression is type
Ton t as

expression as type
141

Lp trnh C#.NET

So snh interface v lp tru tng


Interface kh ging vi lp tru tng C# s dng interface thc thi k thut a k tha v C# khng h tr a k tha t nhiu lp (C++ c h tr a k tha) public class StorableList : List, IStorable { // List methods here ... public void Read( ) {...} public void Write(object obj) {...} // ... }
Lp trnh C#.NET

142

Overriding Interface Implementations


Mt lp khi thc thi cc phng thc ca interface c th chuyn i phng thc thnh dng phng thc o Cc lp dn xut t lp override phng thc o -> K THUT A HNH

143

Lp trnh C#.NET

Bi thc hnh s 4
Xy dng cc lp phng tin giao thng di y theo thit k

144

Lp trnh C#.NET

4.7. Mng, ch s v tp hp
Mng l mt tp hp c nh ch s (indexed Collection) cc i tng cng kiu Bin mng l i tng, cc i tng mng c khai bo thc t l th hin ca lp System.Array
i tng mng c thuc tnh: IsReadOnly, Length i tng mng c phng thc: Clear(), Copy(), Sort()
145

Lp trnh C#.NET

Khai bo mng

type[ ] array-name;
Cp ngoc vung [ ] bo cho trnh dch C# bit l chng ta khai bo mt mng Type xc nh kiu d liu ca cc phn t trong mng V d: int[ ] myIntArray; //Mng integer Employer[ ] myObjectArray; //Mng i tng
146

Lp trnh C#.NET

Gi tr mc nh khi khi gn mng


Khi khi gn mng cc phn t kiu gi tr (value type), cc phn t c khi gn gi tr mc nh ca n myIntArray=new int[5]; Khi khi gn mng cc phn t kiu tham chiu (reference type), cc phn t mng c khi gn gi tr null -> mun s dng phi to v gn cc i tng c th cho cc phn t ca mng myObjectArray=new Employer[5];
147

Lp trnh C#.NET

Truy nhp phn t mng


Cc phn t mng trong C# c nh ch s, bt u bng 0 Mng l i tng, c thuc tnh Length cho bit s phn t trong mng -> Cc phn t ca mng c nh ch s t 0 n Length -1 Truy nhp phn t mng (VD phn t th 3 ca mng myInt) thng qua ton t ch s [ ] myInt[2]
148

Lp trnh C#.NET

V d
public class Employee { private int empID; public Employee(int empID) { this.empID = empID; } public override string ToString() { return empID.ToString(); } } public class Tester { static void Main() { Employee[] empArray; empArray = new Employee[3]; // populate the array for (int i = 0; i < empArray.Length; i++) { empArray[i] = new Employee(i + 5); } for (int i = 0; i < empArray.Length; i++) { Console.WriteLine(empArray[i].ToStrin g()); } } }

149

Lp trnh C#.NET

Cu lnh foreach
Cu lnh foreach cho php lp qua tt c cc phn t trong trong mt mng hay kiu tp hp bt k no khc foreach (type identifier in expression) statement

Kiu d liu ca phn t trong mng / tp hp

Tn bin lp (tham chiu n phn t mng ti mi vng lp)


Lp trnh C#.NET

Tn mng/ Tp hp

150

V d
Khi cc phn t mng l kiu gi tr
foreach ( int i in intArray ) { Console.WriteLine( i.ToString( ) ); }

Khi cc phn t mng l kiu tham chiu


foreach ( Employee e in empArray ) { Console.WriteLine( e.ToString( ) ); }
151

Lp trnh C#.NET

T kha params
T kha params cho php truyn mt lot cc tham s cho phng thc m khng phi nh ngha mng mt cch tng minh.

public void DisplayVals(params int[] intVals)

152

Lp trnh C#.NET

ng dng t kha params


public class Tester { static void Main() { Tester t = new Tester(); t.DisplayVals(5, 6, 7, 8); int[] explicitArray = new int[5] { 1, 2, 3, 4, 5 }; t.DisplayVals(explicitArray); } public void DisplayVals(params int[] intVals) { foreach (int i in intVals) { Console.WriteLine("DisplayVals {0}", i); } } }
153

Lp trnh C#.NET

Bi thc hnh s 5
Bi 1: Vit mt phng thc FindMinMax in ra gi tr s nguyn ln nht v nh nht trong s cc tham s u vo l mt dy cc s nguyn bt k VD: Gi hm FindMinMax(3,1,5,8,0,9,-2) Kt qu in ra mn hnh - S nguyn nh nht l: -2 - S nguyn ln nht l: 9

154

Lp trnh C#.NET

4.8. Strings
public sealed class String :
IComparable<T>, ICloneable, IConvertible, IEnumerable<T>

String l lp ng -> Khng th to lp k tha lp String String implement 4 interfaces IComparable, ICloneable, IConvertible v IEnumerable cho php c th so snh, sao chp, chuyn i v s dng kiu lit k Mi i tng ca lp String l mt chui c nh cc k t Unicode -> cc phng thc lm thay i i tng ca lp thc cht l to ra mt bn sao c sa i, chui nguyn gc vn c gi trong b nh cho n khi b thu gom rc x l.
155

Lp trnh C#.NET

To chui
Cch thng thng
string literalString = "This is a string literal \n";

To chui ng vi nguyn mu (verbatim string) s dng t kha @


string verbatimString=@"\n Pham Van Thuan \t Tel: 0985905253\\";
public class Test { public static void Main() { String literalString = "Pham Van Thuan \n"; Console.WriteLine(literalString); String verbatimString = @"\n Pham Van Thuan \t Tel: 0985905253\\"; Console.WriteLine(verbatimString); Console.Read(); } }
156

Lp trnh C#.NET

Thao tc chui
Lp string h tr cc phng thc cho php so snh, tm kim v x l chui Thuc tnh, phng thc
Empty Compare() Concat() Copy() Equals() Format()
Lp trnh C#.NET

M t
Thuc tnh cho bit chui rng Phng thc so snh hai chui Phng thc ni chui To bn sao ca mt chui Kim tra hai chui c ging nhau khng nh dng mt chui
157

V d
static void Main() { string str1 = "Hanoi"; string str2 = "La thu do cua Viet Nam"; string str3 = "HANOI"; //So sanh chuoi, tra ve 0 neu giong nhau int result = string.Compare(str1, str3); Console.WriteLine("Ket qua so sanh hai chuoi {0} va {1} la {2}", str1, str3, result); Console.ReadLine(); //Noi chuoi string str4 = string.Concat(str1, " ", str2); string str5 = str1 + " " + str2; Console.WriteLine("Ket qua noi chuoi {0} va {1}: \n + Su dung phuong thuc Concat: {2} \n + Su dung ham chong toan tu +: {3}", str1, str2, str4, str5); Console.ReadLine(); //Lay ve chieu dai chuoi Console.WriteLine("Chieu dai cua chuoi \"{0}\" la {1}", str2, str2.Length); Console.ReadLine(); }
158

Lp trnh C#.NET

X l chui ng (Dynamic string)


Lp System.Text.Stringbuilder c s dng to v chnh sa chui
Khng ging nh string, cc i tng ca lp Stringbuilder c th thay i Khi chnh sa, s thay i c thc hin trn chnh i tng ch khng phi trn bn sao ca i tng

159

Lp trnh C#.NET

V d s dng Stringbuilder
static void Main() { // create some strings to work with string s1 = "Hi, Good morning"; // array of delimiters to split the sentence with char[] delimiters = new char[]{' ',','}; // use a StringBuilder class to build the output string StringBuilder output = new StringBuilder(); int ctr = 1; // split the string and then iterate over the // resulting array of strings foreach (string subString in s1.Split(delimiters)) { // AppendFormat appends a formatted string output.AppendFormat("{0}: {1}\n", ctr++, subString); } Console.WriteLine(output); }

160

Lp trnh C#.NET

4.9. Handling Exceptions


C# x dng k thut bt ngoi l (Handling Exception bt v x l li (errror) cng nh cc ngoi l pht sinh trong qu trnh thc thi chng trnh) Phn loi bug, error v exception
Bug: li do ngi lp trnh, cn c loi b trc khi hon thnh phn mm Error: li pht sinh do ngi dng, v d ngi dng nhp sai nh dng d liu -> phi kim tra d liu u vo Exception: li bt thng, v d nh ht b nh, li chia cho 0s
Lp trnh C#.NET

161

Nm (throwing) v bt (catching) ngoi l

bo hiu mt iu kin bt thng xut hin trong qu trnh thc thi, thc hin nm ngoi l throw new System.Exception(); Khi mt ngoi l c tung ra, chng trnh ngay lp tc s dng li v CLR s tm , kim tra chng trnh bt ngoi l, nu khng tm thy n s kt thc chng trnh

162

Lp trnh C#.NET

Ngoi l c bo trong ch debug

163

Lp trnh C#.NET

Li dng chng trnh khi chy thc t

164

Lp trnh C#.NET

V d
public class Test { public static void Main() { Console.WriteLine("Enter Main..."); Test t = new Test(); t.Func1(); Console.WriteLine("Exit Main..."); } public void Func1() { Console.WriteLine("Enter Func1..."); Func2(); Console.WriteLine("Exit Func1..."); } public void Func2() { Console.WriteLine("Enter Func2...");

throw new System.Exception();


Console.WriteLine("Exit Func2..."); } }
165

Lp trnh C#.NET

Ngoi l xut hin

166

Lp trnh C#.NET

Chi tit ngoi l

167

Lp trnh C#.NET

Cu lnh trycatch
C# s dng cu trc trycatchfinally kim tra, bt v x l ngoi l
try { //Lnh c th pht sinh ngoi l, cn kim tra } catch(Exception e) { //Bt v x l ngoi l nu c } Finally { //on m lun thc thi khi xut hin ngoi l }
168

Lp trnh C#.NET

Cu lnh trycatch
C th c nhiu on lnh catch trong mt cu lnh trycatch tng ng vi nhiu ngoi l khc nhau on lnh trycatch c th t trong phng thc c th pht sinh ngoi l hoc t cp cao hn, phng thc triu gi on m c th pht sinh ngoi l

169

Lp trnh C#.NET

Bi thc hnh s 5
Bi 2: Vit mt phng thc

float Divide(int num1, int num2)


Kim tra v bt ngoi l bng cu lnh trycatch trong hai trng hp
Bt trong thn hm Bt trong li gi hm

170

Lp trnh C#.NET

Ni dung mn hc
Chng 1: Gii thiu C# v .NET Framework Chng 2: Gii thiu mi trng pht trin ng dng Visual Studio .NET 2005 Chng 3: C# cn bn Chng 4: Hng i tng trong C# Chng 5: Lp trnh ng dng vi C#

171

Lp trnh C#.NET

Ni dung chng 5
5.1. M u v lp trnh Windows Form 5.2. Mt s iu khin thng dng cho Windows Form 5.3. Kt ni c s d liu s dng ADO.NET 5.4. Lp bo co s dng Crystal Report.NET 5.5. Lp trnh Socket

172

Lp trnh C#.NET

5.1. M u v lp trnh Windows Form Xy dng ng dng Hello World

173

Lp trnh C#.NET

Xy dng ng dng Hello World


To d n kiu Windows Application Thit k giao din
1 label 1 textbox 2 button: Hello, Good bye

174

Lp trnh C#.NET

Cc file cu thnh
Form1.cs: cha m chng trnh ca ngi dng Form1.Designer.cs: do b VS 2005 t ng sinh trong qu trnh thit k

class frmHello
175

Lp trnh C#.NET

Form1.cs

176

Lp trnh C#.NET

Form1.Designer.cs

177

Lp trnh C#.NET

Vit m
S kin ngi dng click vo nt Hello
private void btnHello_Click(object sender, EventArgs e) { MessageBox.Show("Hello "+txtName.Text); } Phng thc Show ca i tng MessageBox -Hin th thng bo -Hin th cc nt bm ty chn, tng tc ngi dng (OK, Cancel, Yes, No)
178

Lp trnh C#.NET

Vit m (tip)
S kin ngi dng click vo nt Good bye
private void btnGoodBye_Click(object sender, EventArgs e) { MessageBox.Show("Bye bye!"); Application.Exit(); } Lp Application cung cp cc thuc tnh v phng thc tnh lm vic vi ng dng Application.Exit(); //ng ng dng

179

Lp trnh C#.NET

5.2. Mt s iu khin thng dng trong Windows Form


Label v Linklabel Textbox v RichTextBox Button Check box v Radio button Combobox Listbox

180

Lp trnh C#.NET

Label
iu khin label cha vn bn tnh trn form Mt s thuc tnh thng dng
Text Text align

C# h tr iu khin Linklabel (k tha lp Label) cho php link n cc lin kt (website, forum). Mt s thuc tnh thng dng
Text LinkArea LinkBehavior
181

Lp trnh C#.NET

Textbox
iu khin Textbox cho php ngi dng nhp thng tin hoc hin th cc thng tin di dng vn bn
Mt dng Nhiu dng

182

Lp trnh C#.NET

RichTextBox
Cho php kh nng nh dng, chnh sa mnh hn nhiu so vi iu khin textbox

183

Lp trnh C#.NET

Check box v Radio button


Check box: thit lp trng thi ca check box qua thuc tnh CheckState
CheckState=Checked CheckState=Unchecked CheckState=Indeterminate

Radio button: chn duy nht mt trong nhiu ty chn khc nhau

184

Lp trnh C#.NET

List Control
List controls bao gm ba iu khin c bn: Listbox, CheckedListBox v ComboBox
C th a d liu vo bng lnh Add Gn iu khin vi mt ngun d liu sn c (Data binding)

Cc iu khin ny u k tha t lp tru tng ListControl

185

Lp trnh C#.NET

Bi thc hnh s 6

186

Lp trnh C#.NET

5.3. Kt ni c s d liu s dng ADO.NET

M hnh d liu quan h Mt s cu truy vn c bn Kt ni c s d liu s dng ADO.NET

187

Lp trnh C#.NET

C s d liu quan h
C s d liu: L s lu tr d liu c t chc. H qun l c s d liu (DBMS):
Cung cp c ch lu tr, qun l d liu mt cch ph hp vi nh dng d liu. Cho php lu tr v truy cp ti c s d liu m khng cn bit v nhng khai bo bn trong c s d liu. V d nh SQL Server, Microsoft Access l cc h qun l c s d liu.
188

Lp trnh C#.NET

M hnh C s d liu quan h

Biu din d liu mt cch logic


C th xem xt cc mi quan h m khng cn quan tm n cu trc vt l ca d liu

Bao gm cc bng
Cc hng c gi l cc mu tin (records) Cc ct c gi l cc trng ( fields) Kho chnh (Primary key) mt hng phi c kha chnh nhm phn bit n vi cc hng khc. Do kha chnh phi c gi tr duy nht v khng c gi tr null
189

Lp trnh C#.NET

M hnh C s d liu quan h


Kha ngoi (foreign key): trong trng hp mt nhn vin mua nhiu hng ha th trn bng Order, ngoi kha chnh (thng l s hiu hng ha) cn lp li s th nhn vin (trong bng Employee). Lc ny s th nhn vin gi l kha ngoi ca bng Order. Kha ngoi dng tm kim cc gi tr trong bng con (bng Order).

190

Lp trnh C#.NET

M hnh C s d liu quan h


Ta c c s d liu ca bng Employee v bng Product nh sau:
kha chnh ca bng Employee

kha chnh ca bng Product

kha ngoi ca bng Product


191

Lp trnh C#.NET

M hnh C s d liu quan h


Quan h (relationship): c thit lp gia hai bng d liu vi
nhau, c ba loi quan h chnh.

Quan h 1-1: quan h trc tip gia 2 bng d liu. V d bn c 2 bng Person1, Person2 th quan h Kt hn l quan h 1-1. Mt cch khc khi m 2 bng c quan h thng qua 2 kha chnh th quan h l 1-1. Quan h 1-N: ng vi mt hng trong bng ny c nhiu hng trong bng khc. Chng hn nh quan h gia 2 bng Employee v Order nh va ri l quan h 1-N. Quan h N-N: c thit lp khi mt hng trong Parent table c nhiu hng trong Child table v ngc li.
192

Lp trnh C#.NET

M hnh C s d liu quan h


Tnh ton vn d liu (Data Integrity), c nh ngha l khng tn ti d liu d tha, bao gm:
D liu nhp (Entity Integrity): mi hng phi c mt gi tr duy nht trong trng kha chnh ca n. Rng buc ton vn (Referential Integrity): mi gi tr trng kha ngoi ca bng ny phi xut hin trong trng kha chnh ca bng khc. Ton vn min (Domain Integrity): d liu nhp vo trong ct phi ph hp vi nh dng v kiu d liu khai bo.

193

Lp trnh C#.NET

V d
tblUsers

tblMemos

tblMeetings

194

Lp trnh C#.NET

V d

195

Lp trnh C#.NET

SQL-Ngn ng truy vn c cu trc

c dng yu cu d liu (thc hin truy vn ) v thao tc trn d liu thc hin cc lnh SQL, bn s dng SQL Query Analyzer. C th m trc tip t ca s SQL Server Enterprise Manager bng cch chn Tools\SQL Query Analyzer nh sau

196

Lp trnh C#.NET

SQL-Ngn ng truy vn c cu trc

197

Lp trnh C#.NET

Truy vn SELECT

Chc nng:
Trch thng tin t mt hay nhiu bng trong mt CSDL.

C php:
SELECT danh_sch_cc_ct FROM tn_bng (Du * cho php trch mu tin vi tt c cc ct trong bng.)

198

Lp trnh C#.NET

Mnh WHERE
Chc nng: Truy xut d liu trong bng theo cc iu kin no . C php: SELECT tn_ct FROM tn_bng WHERE tn_ct php_ton gi_tr
Php ton = <> > < >= <= BETWEEN LIKE M t So snh bng So snh khng bng Ln hn Nh hn Ln hn hoc bng Nh hn hoc bng Nm gia mt khong So snh mu chui
199

Lp trnh C#.NET

Mnh ORDER BY
Chc nng: Sp xp kt qu tr v theo mt tiu chun bt k. V d: Ta c bng Orders sau:

Lnh

SELECT Company, OrderNumber FROM Orders ORDER BY Company

cho kt qu

200

Lp trnh C#.NET

Mnh ORDER BY
Ta cng c th sp xp theo th t gim dn ca OrderNumber bng cch nh lnh: SELECT Company, OrderNumber FROM Orders ORDER BY OrderNumber DESC Kt qu tr v:

Ngc li, ASC sp xp theo th t tng dn.


Lp trnh C#.NET

201

Truy vn thm mi INSERT


Chc nng: Chn mt hng vo trong bng. C php: INSERT INTO tn_bng VALUES (gi_tr_1, gi_tr_2,....) Ta cng c th ch r cc ct/trng no cn chn d liu: INSERT INTO tn_bng (ct_1, ct_2,...) VALUES (gi_tr_1, gi_tr_2,....)
Lp trnh C#.NET

202

Truy vn thm mi INSERT


V d: Ta c bng Persons nh sau:

Cu lnh SQL sau: INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') s to ra kt qu trong bng Persons :

203

Lp trnh C#.NET

Truy vn cp nht UPDATE

Chc nng: Cp nht hay sa i d liu c trong bng. C php: UPDATE tn_bng SET tn_ct = gi_tr_mi WHERE tn_ct = gi_tr

204

Lp trnh C#.NET

Truy vn cp nht UPDATE


V d ta c bng Person sau:

b xung thm phn tn cho ngi c h l Rasmussen ta nh lnh sau: UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen Kt qu tr v:

205

Lp trnh C#.NET

Truy vn xa DELETE
Chc nng: Xo cc dng ra khi bng. C php: DELETE FROM tn_bng WHERE tn_ct = gi_tr V d xo ngi c tn Nina Rasmussen:
DELETE FROM Person WHERE LastName = 'Rasmussen'

206

Lp trnh C#.NET

ADO.NET
ADO (Active Data Object) ang l mt i tng ph bin trong lp trnh c s d liu, bn s dng ADO kt ni vi bt k c s d liu tng thch. N cung cp h giao tip lp trnh ng dng API (application program interface) truy nhp vo c s d liu h thng. ADO.NET l i tng c s dng trong .NET

207

Lp trnh C#.NET

Lp Connection
.NET Data Provider l mt phn ca m hnh lp trnh ADO.NET, bao gm 4 lp sau: Connection: lp kt ni c s d liu. DataAdapter: lp cha d liu. Command: lp cha lnh. DataReader: lp c d liu. Bn cn khai bo Connection khi mun truy cp loi d liu ngun. C 3 loi kt ni Microsoft cung cp trong .Net Framework bao gm OdbcConnection, OleDbConnection ,SqlConnection. SqlConnection ti u ha cho qu trnh kt ni vi CSDL SQL Server 7.0 v phin bn mi hn. Trong khi Odbc v OleDb c s dng cho MS Access hay MySQL,
Lp trnh C#.NET

208

Lp DataAdapter
Lp DataAdapter dng nhn d liu t d liu ngun, sau chuyn vo DataSet v cc lp quan h nh DataTable (xem v lp khng kt ni phn sau). N cng c trch nhim cp nht d liu thay i vo d liu ngun. Cc pht biu trong SQL c nhng vo C# bng i tng Command. B iu hp s s dng i tng Command truy vn v cp nht d liu. V th lm vic c vi DataAdapter, bn phi ch r v s dng i tng Command. DataAdapter chia thnh 3 lp c th: OleDbDataAdapter , OdbcDataAdapter, 209 SqlDataAdapter
Lp trnh C#.NET

5.4. Lp bo co s dng Crystal Report

S dng ngun d liu qua ODBC S dng ngun d liu qua ADO.NET

210

Lp trnh C#.NET

5.5. Lp trnh socket


Socket l g?

Socket
a ch IP (IP Address) S hiu cng (Port Number)

211

Lp trnh C#.NET

Mt s port thng dng


S hiu cng 20 21 25 80 110
212

Giao thc s dng FTP Data FTP Control SMTP HTTP POP3

Lp trnh C#.NET

Giao thc truyn tin


Cc gi tin c truyn theo hai giao thc chnh
UDP (User Datagram Protocol): khng m bo c thng tin n c ch v ng th t -> Truyn thng tin cn tc nhanh, khng cn tuyt i chnh xc (Voice over IP, Game online) TCP (Transmission Control Protocol):m bo chuyn giao d liu n ni nhn mt cch ng tin cy v ng th t. (Web, email, truyn file)

213

Lp trnh C#.NET

V d giao thc UDP

214

Lp trnh C#.NET