You are on page 1of 139

NGN NG C#

C#
Ngn ng lp trnh thun hng i tng

70% Java, 10% C++, 5% Visual Basic,


15% mi

Trnh bin dch C# l mt trong nhng trnh


bin dch hiu qu nht trong dng sn
phm .NET.

2 Lp Trnh mi trng Windows


24/02/2009
c im ca ngn ng C#
Khong 80 t kha
H tr lp trnh cu trc, lp trnh hng i tng,
hng thnh phn (Component oriented)
C t kha khai bo dnh cho thuc tnh (property)
Cho php to su liu trc tip bn trong m ngun
(dng tool m ngun m NDoc pht sinh ra su liu)
H tr khi nim interface (tng t java)
C ch t ng dn rc (tng t java)
Truyn tham s kiu: in(), out, ref

3 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

Cu trc chng trnh C#

4 Lp Trnh mi trng Windows


Hello World

using System;

class Hello
{
public static void Main()
{
Console.WriteLine("Hello, World");
}
}

5 Lp Trnh mi trng Windows


24/02/2009
Namespace
Namespace cung cp cho cch t chc quan
h gia cc lp v cc kiu khc.
Namespace l cch m .NET trnh n vic
cc tn lp, tn bin, tn hm trng tn gia
cc lp.
namespace CustomerPhoneBookApp
{
using System;
public struct Subscriber
{ // Code for struct here... }
} 6 Lp Trnh mi trng Windows
24/02/2009
Namespace
T kho using gip gim vic phi g
nhng namespace trc cc hm hnh vi
hoc thuc tnh
using Wrox.ProCSharp;
Ta c th gn b danh cho namespace
C php :
using alias = NamespaceName;

7 Lp Trnh mi trng Windows


24/02/2009
V d 1
01 /* Chng trnh c bn ca C#*/
02
03 class Hello
04 {
05 static void Main(string[] args)
06 {
07 System.Console.WriteLine(Hello C Sharp);
08 System.Console.ReadLine();
09 }
10 }
bin dch tng Class, c th s dng tp tin csc.exe trong ca
s Command Prompt vi khai bo nh sau:
D:\csc CSharp\ Hello.cs

8 Lp Trnh mi trng Windows


24/02/2009
V d 2
01 /* Chng trnh c bn ca C#*/
02 using System;
03 class Hello
04 {
05 static void Main(string[] args)
06 {
07 Console.WriteLine(Hello C Sharp);
08 Console.ReadLine();
09 }
10 }

bin dch tng Class, c th s dng tp tin csc.exe trong ca


s Command Prompt vi khai bo nh sau:
D:\csc CSharp\ Hello.cs
9 Lp Trnh mi trng Windows
24/02/2009
V d 3
01 /* Chng trnh c bn ca C#*/
02 using Con=System.Console;
03 class Hello
04 {
05 static void Main(string[] args)
06 {
07 Con.WriteLine(Hello C Sharp);
08 Con.ReadLine();
09 }
10 }

bin dch tng Class, c th s dng tp tin csc.exe trong ca


s Command Prompt vi khai bo nh sau:
D:\csc CSharp\ Hello.cs
10 Lp Trnh mi trng Windows
24/02/2009
Console.WriteLine
public static void Main() {
int a = 1509; int b = 744; int c = a + b;
Console.Write("The sum of ");
Console.Write(a);
Console.Write(" and ") ;
Console.Write(b);
Console.Write(" equals ");
Console.WriteLine(c);
Console.WriteLine("The sum of " + a + " and " + b + "="+c) ;
Console.WriteLine(" {0} + {1} = {2}", a, b, c);
Console.ReadLine();
}

11 Lp Trnh mi trng Windows


24/02/2009
Console.WriteLine

Console.WriteLine("Standard Numeric Format Specifiers");


Console.WriteLine(
"(C) Currency: . . . . . . . . {0:C}\n" +
"(D) Decimal:. . . . . . . . . {0:D}\n" +
"(E) Scientific: . . . . . . . {1:E}\n" +
"(F) Fixed point:. . . . . . . {1:F}\n" +
"(G) General:. . . . . . . . . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(N) Number: . . . . . . . . . {0:N}\n" +
"(P) Percent:. . . . . . . . . {1:P}\n" +
"(R) Round-trip: . . . . . . . {1:R}\n" +
"(X) Hexadecimal:. . . . . . . {0:X}\n",
-123, -123.45f);

12 Lp Trnh mi trng Windows


24/02/2009
Console.WriteLine
Console.WriteLine("Standard DateTime Format Specifiers");
Console.WriteLine(
"(d) Short date: . . . . . . . {0:d}\n" +
"(D) Long date:. . . . . . . . {0:D}\n" +
"(t) Short time: . . . . . . . {0:t}\n" +
"(T) Long time:. . . . . . . . {0:T}\n" +
"(f) Full date/short time: . . {0:f}\n" +
"(F) Full date/long time:. . . {0:F}\n" +
"(g) General date/short time:. {0:g}\n" +
"(G) General date/long time: . {0:G}\n" +
" (default):. . . . . . . . {0} (default = 'G')\n" +
"(M) Month:. . . . . . . . . . {0:M}\n" +
"(R) RFC1123:. . . . . . . . . {0:R}\n" +
"(s) Sortable: . . . . . . . . {0:s}\n" +
"(u) Universal sortable: . . . {0:u} (invariant)\n" +
"(U) Universal sortable: . . . {0:U}\n" +
"(Y) Year: . . . . . . . . . . {0:Y}\n",
thisDate);
13 Lp Trnh mi trng Windows
24/02/2009
Console.ReadLine()
public static string ReadLine ()

Convert.ToBoolean();
Convert.ToByte();
Convert.ToInt16();

Byte.Parse();
Int64.Parse();
Double.Parse()

14 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

Kiu d liu trong C#

15 Lp Trnh mi trng Windows


24/02/2009

Kiu d liu nh sn
Kiu C# S byte Kiu .NET M t
byte 1 Byte S nguyn dng
khng du t 0-255
char 2 Char K t Unicode
bool 1 Boolean Gi tr logic true/ false
sbyte 1 Sbyte S nguyn c du
( t -128 n 127)
short 2 Int16 S nguyn c du gi
tr t -32768 n 32767
ushort 2 UInt16 S nguyn khng du
0 65.535
16 Lp Trnh mi trng Windows
24/02/2009

Kiu d liu nh sn
Kiu C# S byte Kiu .NET M t
int 4 Int32 S nguyn c du
- 2.147.483.647 n
2.147.483.647
uint 4 Uint32 S nguyn khng du
0 4.294.967.295
float 4 Single Kiu du chm ng,
3,4E-38 n 3,4E+38,
vi 7 ch s c ngha..
double 8 Double Kiu du chm ng c
chnh xc gp i
1,7E-308 n 1,7E+308
vi 15,16 ch s c ngha.
17 Lp Trnh mi trng Windows
24/02/2009

Kiu d liu nh sn
Kiu C# S byte Kiu .NET M t
decimal 8 Decimal C chnh xc n 28 con
s
dng trong tnh ton ti chnh
phi c hu t m hay M
theo sau gi tr
long 8 Int64 Kiu s nguyn c du
-9.223.370.036.854.775.808
n
9.223.372.036.854.775.807
ulong 8 Uint64 S nguyn khng du
t 0 n 0xffffffffffffffff
18 Lp Trnh mi trng Windows
24/02/2009

Kiu d liu nh sn

Console.WriteLine("sbyte:{0} to {1},sbyte.MinValue,sbyte.MaxValue);
Console.WriteLine("byte:{0} to {1}", byte.MinValue, byte.MaxValue);
Console.WriteLine("short:{0} to {1}", short.MinValue, short.MaxValue);
Console.WriteLine("ushort:{0} to {1}", ushort.MinValue,
ushort.MaxValue);
Console.WriteLine("int:{0} to {1}", int.MinValue, int.MaxValue);
Console.WriteLine("long:{0} to {1}", long.MinValue, long.MaxValue);
Console.WriteLine("decimal:{0} to {1}", decimal.MinValue,
decimal.MaxValue);
Console.ReadLine();

19 Lp Trnh mi trng Windows


Chuyn i kiu d liu
Chuyn i d liu l cho php mt biu
thc ca kiu d liu ny c xem xt
nh mt kiu d liu khc.
Chuyn i c th: n ngm nh
(implicit) hay tng minh (explicit),
v d,
int a = 123;
long b = a;
// t int sang long (implicit)
int c = (int) b;
// t long sang int (explicit)
20 Lp Trnh mi trng Windows
24/02/2009
24/02/2009

Enum(eration) kiu tp hp

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

Days d = Days.Mon;

switch (d) {
case Days.Tue:
case Days.Wed:
}

R hn cch dng hng truyn thng ca C


const int Sat = 1;

const int Fri = 6;

21 Lp Trnh mi trng Windows


24/02/2009

Value type vs reference type


A ? 105
A 105

B ? 55
B 55

A ? 105

B ?

22 Lp Trnh mi trng Windows


24/02/2009

struct
struct : value type (class : reference type)
Dng cho cc i tng nh nh
Point, Rectangle, Color,

public struct MyPoint {


public int x, y;
public MyPoint(int p1, int p2) {
x = p1;
y = p2;
}
}

23 Lp Trnh mi trng Windows


24/02/2009

Box v Unbox
i qua li gia value type v reference
type.
Box: value => reference (object).
Thng dng trong cc hm, cu trc d
liu s dng tham s l kiu object tng
qut.

int i = 123;
object o = i; // implicit boxing
object o = (object) i; // explicit boxing
int j = (int) o; // unboxing

24 Lp Trnh mi trng Windows


24/02/2009

Box v Unbox

25 Lp Trnh mi trng Windows


Cc nhm ton t trong C#
Nhm ton t Ton t
Ton hc +-*/%
Logic & | ^ ! ~ && || true false
Ghp chui +
Tng, gim ++, --
Dch bit << >>
Quan h == != < > <= >=
Gn = += -= *= /= %= &= |= ^=
<<= >>=
Ch s []
p kiu ()
Indirection v Address * -> [ ] &

26 Lp Trnh mi trng Windows


24/02/2009
Th t u tin ca ton t
Nhm ton t Ton t
Primary {x} x.y f(x) a[x] x++ x--
Unary + - ! ~ ++x -x (T)x
Nhn * / %
Cng + -
Dch bit << >>
Quan h < > <= >= is
Bng == !=
Logic trn bit &
AND
XOR ^
OR |
iu kin AND &&
iu kin OR ||
iu kin ?:
Assignment = *= /= %= += -= <<= >>= &= ^= |=
27 Lp Trnh mi trng Windows
24/02/2009
Kiu mng
1 mng l 1 tp cc im d liu (ca
cng kiu c s), c truy cp dng 1 s
ch mc
Cc mng trong C# pht sinh t lp c s
System.Array
Mng c th cha bt c kiu no m C#
nh ngha, bao gm cc mng i tng,
cc giao din, hoc cc cu trc
Mng c th 1 chiu hay nhiu chiu, v
c khai bo bng du ngoc vung ([ ]
) t sau kiu d liu ca mng
VD:
24/02/2009
int [] a; 28 Lp Trnh mi trng Windows
Kiu mng
Khai bo bin mng c hai cch nh sau
1) Khai bo v khi to mng
int[] yourarr=new int[ptu];
2) Khai bo sau khi to mng
int[] myarr;
myarr=new int[ptu];
Khai bo mng vi s phn t cho trc v
khi to gi tr cho cc phn t ca mng:
int[] me={1,2,3,4,5};
float[] arr = { 3.14f, 2.17f, 100 };
float[] arr = new float [3] { 3.14f, 2.17f, 100 };

29 Lp Trnh mi trng Windows


24/02/2009
Kiu mng
arr.length: s phn t ca mng

Khai bo mng 2 chiu:


int [,] Mang2chieu;
Mang2chieu = new int[3,4]

Khai bo mng ca mng:


int [][] M=new int[2][];
M[0]=new int[4];
M[1]= new int[30];
30 Lp Trnh mi trng Windows
24/02/2009
Kiu string
Kiu string l 1 kiu d liu tham chiu trong
C#
System.String cung cp cc hm tin ch nh:
Concat(), CompareTo(), Copy(), Insert(),
ToUpper(), ToLower(), Length, Replace(),
Cc ton t == v != c nh ngha so
snh cc gi tr ca cc i tng chui, ch
khng phi l b nh m chng tham chiu
n
Ton t & l cch tc k thay cho Concat()
C th truy cp cc k t ring l ca 1 chui
dng ton t ch mc ([ ])

31 Lp Trnh mi trng Windows


24/02/2009
Kiu pointer
Kiu pointer c khai bo vi du * ngay
sau loi d liu v trc tn bin cng vi
t kho unsafe.
Bin dch ng dng C# c s dng kiu d
liu pointer:
D:\csc pointer.cs /unsafe

32 Lp Trnh mi trng Windows


24/02/2009
Kiu pointer
Khng ging nh hai kiu d liu value v
reference, kiu pointer khng chu s kim
sot ca garbage collector
Garbage collector khng dng cho kiu d
liu ny do chng khng bit d liu m
con tr tr n
V vy, pointer khng cho php tham
chiu n reference hay mt struct c
cha cc kiu references v kiu tham
chiu ca pointer thuc loi kiu khng
qun l (unmanaged-type).

33 Lp Trnh mi trng Windows


24/02/2009
Tham s
Tham tr: tham s c gi tr khng thay i
trc v sau khi thc hin phng thc
Tham bin: tham s c gi tr thay i trc
v sau khi thc hin phng thc, c th i
sau cc t kha: ref, out, params
- ref: tham s i theo sau phi khi to trc
khi truyn vo phng thc
- out: tham s khng cn khi to trc khi
truyn vo phng thc
- params: tham s nhn i s m s lng
i s l bin, t kho ny thng s dng
tham s l mng.
34 Lp Trnh mi trng Windows
24/02/2009
T Kha ref

void MyMethod()
{
int num1 = 7, num2 = 9;
Swap(ref num1, ref num2);
// num1 = 9, num2 = 7
}
void Swap(ref int x, ref int y)
{
int temp = x; x = y; y = temp;
}
35 Lp Trnh mi trng Windows
24/02/2009
Keyword out

void MyMethod()
{ uninitialise
d
int num1 = 7, num2;
Subtraction(num1, out num2);
// num1 = 7, num2 = 5
}
void Subtraction(int x, out int y)
{
y = x - 2;
// y must be assigned a value
}
36 Lp Trnh mi trng Windows
24/02/2009
Keyword params

void MyMethod()
{
int sum = Addition(1, 2, 3); // sum = 6

}
int Addition(params int[] integers)
{
int result = 0;
for (int i = 0; i < integers.Length; i++)
result += integers[i];
return result;
}
37 Lp Trnh mi trng Windows
24/02/2009
Pht biu chn

Pht biu chn (selection statement) trong C#


bao gm cc pht biu (if, ifelse,
switchcase). Pht biu ifelse
if (expression)
statement1
Pht biu if
else
if (expression) statement2
statement
if (expression)
{
statement1
statement1
} 38 Lp Trnh mi trng Windows
24/02/2009
Pht biu switchcase
Pht biu switchcase l pht biu iu khin
nhiu chn la bng cch truyn iu khin n
pht biu case bn trong.

switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
24/02/2009
} 39 Lp Trnh mi trng Windows
Pht biu lp
Pht biu vng lp trong C# bao gm do, for,
foreach, while.

Vng lp do
do
statement
while (expression);

Vng lp while
while (expression)
statement

40 Lp Trnh mi trng Windows


24/02/2009
Vng lp for
for ([initializers]; [expression];
[iterators])
statement

Vng lp foreach in
foreach (type identifier in expression)
statement
Vng lp foreach lp li mt nhm pht biu cho
mi phn t trong mng hay tp i tng.
Pht biu dng duyt qua tt c cc phn t
trong mng hay tp i tng v thc thi mt tp
lnh
41 Lp Trnh mi trng Windows
24/02/2009
Pht biu nhy
Pht biu nhy s c s dng khi
chng trnh mun chuyn i iu
khin.
Pht biu nhy: break, continue, default,
goto, return

42 Lp Trnh mi trng Windows


24/02/2009
Tm tt
Statement Example

Local variable static void Main() {


declaration int a;
int b = 2, c = 3;
a = 1;
Console.WriteLine(a + b + c);
}
Local constant static void Main() {
declaration const float pi = 3.1415927f;
const int r = 25;
Console.WriteLine(pi * r * r);
}
Expression statement static void Main() {
int i; i = 123;
Console.WriteLine(i);
i++; // tng i ln 1
Console.WriteLine(i);
}
43 Lp Trnh mi trng Windows
24/02/2009
Tm tt
Statement Example

if statement static void Main(string[] args) {


if (args.Length == 0) {
Console.WriteLine("No arguments");
} else { Console.WriteLine("One or more
arguments"); }
}
switch static void Main(string[] args) {
statement int n = args.Length;
switch (n) {
case 0: Console.WriteLine("No
arguments");
break;
case 1: Console.WriteLine("One
argument");
break;
default: Console.WriteLine("{0}
arguments", n);
break;
}
24/02/2009
} 44 Lp Trnh mi trng Windows
Tm tt
Statement Example

while static void Main(string[] args) {


statement int i = 0;
while (i < args.Length) {
Console.WriteLine(args[i]);
i++; }
}
do statement static void Main() {
string s;
do {
s = Console.ReadLine();
if (s != null) Console.WriteLine(s);
} while (s != null);
}
for statement static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);
}
45 Lp Trnh mi trng Windows
24/02/2009
Tm tt
Statement Example

foreach statement static void Main(string[] args) {


foreach (string s in args)
Console.WriteLine(s);
}
break statement static void Main() {
while (true) {
string s =
Console.ReadLine();
if (s == null) break;
Console.WriteLine(s);
}
}
continue static void Main(string[] args) {
statement for (int i = 0; i < args.Length; i++) {
if (args[i].StartsWith("/")) continue;
Console.WriteLine(args[i]);
}
}
46 Lp Trnh mi trng Windows
24/02/2009
Tm tt
Statement Example

goto statement static void Main(string[] args) {


int i = 0;
goto check;
loop: Console.WriteLine(args[i++]);
check: if (i < args.Length) goto loop;
}

return static int Add(int a, int b) { return a + b; }


statement static void Main() {
Console.WriteLine(Add(1, 2));
return;
}

checked static void Main() {


and unchecked int i = int.MaxValue;
statements checked { Console.WriteLine(i + 1);//
Exception }
unchecked { Console.WriteLine(i + 1);//
Overflow }
24/02/2009
} 47 Lp Trnh mi trng Windows
Tm tt
Statement Example

lock statement class Account {


decimal balance;
public void Withdraw(decimal amount) {
lock (this) {
if (amount > balance)
throw new
Exception("Insufficient funds");
balance -= amount;
}
}
}
using statement static void Main() {
using (TextWriter w = File.CreateText("test.txt"))
{
w.WriteLine("Line one");
w.WriteLine("Line two");
w.WriteLine("Line three");
}
24/02/2009 } 48 Lp Trnh mi trng Windows
Tm tt
Statement Example

throw and try static double Divide(double x, double y) {


statements if (y == 0) throw new DivideByZeroException();
return x / y;
}
static void Main(string[] args) {
try {
if (args.Length != 2)
throw new Exception("Two numbers
required");
double x = double.Parse(args[0]);
double y = double.Parse(args[1]);
Console.WriteLine(Divide(x, y));
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}

49 Lp Trnh mi trng Windows


24/02/2009
OOP in C#

50 Lp Trnh mi trng Windows


24/02/2009
Khai bo lp
[Thuc tnh] [B t truy cp]
class <nh danh lp> [: Lp c
s]
{
<Phn thn ca lp:
cc thuc tnh
phng thc >

51 Lp Trnh mi trng Windows


24/02/2009
V d
using System;
public class ThoiGian
{
public void ThoiGianHienHanh()
{
Console.WriteLine(Hien thi thoi gian hien hanh);
}
// Cc bin thnh vin
int Nam;
int Thang;
int Ngay;
int Gio;
int Phut;
int Giay;
}

52 Lp Trnh mi trng Windows


24/02/2009
public class Tester
{
static void Main()
{
ThoiGian t = new ThoiGian();
t.ThoiGianHienHanh();
}
}

53 Lp Trnh mi trng Windows


24/02/2009
Thuc tnh truy cp
Thuc tnh Gii hn truy vp
public Khng hn ch
private Ch trong lp (mc nh)
protected Trong lp v lp con(lp dn
xut)
internal Trong chng trnh
protected Trong chng trnh v trong
internal lp con

54 Lp Trnh mi trng Windows


24/02/2009
Khi to gi tr cho thuc tnh
public class ThoiGian
{
public void ThoiGianHienHanh()
{
System.DateTime now = System.DateTime.Now;
System.Console.WriteLine(\n Hien tai: \t {0}/{1}/{2}
{3}:{4}:{5},now.Day, now.Month, now.Year,
now.Hour, now.Minute, now.Second);
System.Console.WriteLine( Thoi Gian:\t {0}/{1}/{2}
{3}:{4}:{5},
Ngay, Thang, Nam, Gio, Phut, Giay);
}
public ThoiGian( System.DateTime dt)
{
Nam = dt.Year; Thang = dt.Month;Ngay = dt.Day;
Gio = dt.Hour;Phut = dt.Minute;
Giay = dt.Second;
}
55 Lp Trnh mi trng Windows
24/02/2009
Khi to gi tr cho thuc tnh
public ThoiGian(int Year, int Month, int Date, int Hour, int Minute)
{
Nam = Year;Thang = Month;Ngay = Date;
Gio = Hour;Phut = Minute;
}
private int Nam;
private int Thang;
private int Ngay;
private int Gio;
private int Phut;
private int Giay = 30 ; // bin c khi to.
}

56 Lp Trnh mi trng Windows


24/02/2009
Khi to gi tr cho thuc tnh
public class Tester
{
static void Main()
{
System.DateTime currentTime =
System.DateTime.Now;
ThoiGian t1 = new ThoiGian( currentTime );
t1.ThoiGianHienHanh();
ThoiGian t2 = new ThoiGian(2001,7,3,10,5);
t2.ThoiGianHienHanh();
}
}

57 Lp Trnh mi trng Windows


24/02/2009
Phng thc khi to

Hm to mc nh: ging C++


Hm to c i s: tng t C++ nhng khng
c tham s mc nh
public class MyClass
{
public MyClass() // zero-parameter constructor
{
// construction code
}
public MyClass(int number) // another overload
{
// construction code
}
}

58 Lp Trnh mi trng Windows


24/02/2009
Phng thc khi to sao chp

C# khng cung cp phng thc khi to sao


chp
public ThoiGian( ThoiGian tg)
{
Nam = tg.Nam;
Thang = tg.Thang;
Ngay = tg.Ngay;
Gio = tg.Gio;
Phut = tg.Phut;
Giay = tg.Giay;
}

59 Lp Trnh mi trng Windows


24/02/2009
Phng thc hy b
C# cung cp c ch thu dn (garbage
collection) v do vy khng cn phi khai
bo tng minh cc phng thc hy.
Phng thc Finalize s c gi bi c
ch thu dn khi i tng b hy.
Phng thc kt thc ch gii phng cc
ti nguyn m i tng nm gi, v
khng tham chiu n cc i tng khc

60 Lp Trnh mi trng Windows


24/02/2009
Phng thc hy b
~Class1()
{
// Thc hin mt s cng vic
}

Class1.Finalize()
{
// Thc hin mt s cng vic
base.Finalize();
}

61 Lp Trnh mi trng Windows


24/02/2009
Hm hy
class MyClass : IDisposable
{
public void Dispose()
{
// implementation
}
}

62 Lp Trnh mi trng Windows


24/02/2009
Hm hy
Lp s thc thi giao din System.IDisposable, tc
l thc thi phng thc IDisposable.Dispose().

Khng bit trc c khi no mt Destructor


c gi.

C th ch ng gi thu dn rc bng cch gi


phng thc System.GC.Collect().

System.GC l mt lp c s .NET m t b thu


gom rc v phng thc Collect() dng gi b
thu gom rc.
63 Lp Trnh mi trng Windows
24/02/2009
Con tr this
T kha this dng tham chiu n th
hin hin hnh ca mt i tng
public void SetYear( int Nam)
{
this.Nam = Nam;
}
Tham chiu this ny c xem l con tr
n n tt cc phng thc khng c
thuc tnh tnh trong mt lp

64 Lp Trnh mi trng Windows


24/02/2009
Thnh vin static
Thnh vin tnh c xem nh mt phn
ca lp.
C th truy cp n thnh vin tnh ca
mt lp thng qua tn lp
C# khng cho php truy cp n cc
phng thc tnh v cc bin thnh vin
tnh thng qua mt th hin.
Khng c friend
Phng thc tnh hot ng t nhiu ging
nh phng thc ton cc

65 Lp Trnh mi trng Windows


24/02/2009
Thnh vin static

66 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

Thuc tnh (property)


Thuc tnh cho php to ra cc field read-only, write-only.

Thuc tnh cho php to ra cc field o vi bn ngoi

class Student {
protected DateTime _Birthday;

public int Age {


get {
return DateTime.Today().Year _Birthday.Year;
}
}
}

Console.Writeline(Age: {0}, chau.Age);

67 Lp Trnh mi trng Windows


Thuc tnh (property) 24/02/2009

Cho php filter cc gi tr c ghi vo field m khng phi


dng c ch hm set_xxx nh C++.
Bn ngoi c th dng nh field (dng trong biu thc)

class Student {
protected DateTime _Birthday;
public int Birthday {
get {
return _Birthday;
}
set {
if ()
throw new
_Birthday = value;
}
}
}
chau.Birthday = new DateTime(2007,09,23);
Console.Writeline(Birthday: {0}, chau.Birthday);

68 Lp Trnh mi trng Windows


Thuc tnh (property)
protected string foreName; //foreName l attribute ca mt lp
public string ForeName //ForeName l mt Property
{
get
{
return foreName;
}
set
{
if (value.Length > 20)
// code here to take error recovery action
// (eg. throw an exception)
else
foreName = value;
}
}

69 Lp Trnh mi trng Windows


24/02/2009
Thuc tnh (property)
Nu cu lnh Property ch c on lnh
get -> thuc tnh ch c (Read Only)
Nu cu lnh Property ch c on lnh set
-> thuc tnh ch ghi (Write Only)

70 Lp Trnh mi trng Windows


24/02/2009
Thuc tnh c v ghi
Cho php gn (set) gi tr vo thuc tnh hay ly
(get) gi tr ra t thuc tnh.

public int liA


{
get
{
return LiA;
}
set
{
LiA = value; // value l t
kha
}
}
71 Lp Trnh mi trng Windows
24/02/2009
Thuc tnh ch c
Nu mun thuc tnh ch c, ch s dng
phng thc get

public int liA


{
get
{
return LiA;
}
}
72 Lp Trnh mi trng Windows
24/02/2009
24/02/2009

Hng i tng
public class BankAccount {
protected string ID;
protected string Owner; Fields
protected decimal _Balance;
public BankAccount(string ID, string Owner) {
this.ID = ID;
this.Owner = Owner;
this._Balance = 0;
}
public void Deposit(decimal Amount) {
_Balance+=Amount;
}
public void Withdraw(decimal Amount) {
_Balance-=Amount; // what if Amount > Balance?
}
public decimal Balance {
get {
Thuc tnh ch c
return _Balance;
} Read-only property
}
};
73 Lp Trnh mi trng Windows
24/02/2009

Hng i tng
class Program
{
static void Main(string[] args)
{
BankAccount myAcct = new Account(
"100120023003", "Nguyen Van An");
myAcct.Deposit(1000);
myAcct.Withdraw(100);
Console.WriteLine("Balance: {0}", myAcct.Balance);
//myAcct.Balance=10000;
Console.ReadLine();

}
}

74 Lp Trnh mi trng Windows


24/02/2009

Indexer
Cho php to ra cc thuc tnh ging nh array (nhng cch
ci t bn trong khng nht thit dng array). Lu l ch
mc khng nht thit phi l integer.
C th c nhiu ch mc
vd: Marks[string SubjectID, string SemesterID]
class Student {
protected string StudentID;
protected Database MarkDB;
public double Marks[string SubjectID] {
get {
return MarkDB.GetMark(StudentID,SubjectID);
}
set {
MarDB.UpdateMark(StudentID,value);
}
}
}


Console.Writeline(Physic mark: {0},chau.Marks[physic]);
75 Lp Trnh mi trng Windows
Chng hm (overload)
Khng chp nhn hai phng thc ch
khc nhau v kiu tr v.
Khng chp nhn hai phng thc ch
khc nhau v c tnh ca mt thng s
ang c khai bo nh ref hay out.

76 Lp Trnh mi trng Windows


24/02/2009
K THA A HNH

77 Lp Trnh mi trng Windows


24/02/2009
S k tha
1 class ch c th k tha t 1 class c s
1 class c th k tha t nhiu Interface
T kha sealed c dng trong trng
hp khai bo class m khng cho php
class khc k tha.

78 Lp Trnh mi trng Windows


24/02/2009
n tha k
class MyDerivedClass : MyBaseClass
{
// functions and data members here
}

79 Lp Trnh mi trng Windows


24/02/2009
public class Window
{
// Hm khi dng ly hai s nguyn ch n v tr ca ca s trn console
public Window( int top, int left)
{
this.top = top;
this.left = left;
}
public void DrawWindow() // m phng v ca s

{
Console.WriteLine(Drawing Window at {0}, {1}, top, left);
}
// C hai bin thnh vin private do hai bin ny s khng
thy bn trong lp dn xut.
private int top;
private int left;
}

80 Lp Trnh mi trng Windows


24/02/2009
public class ListBox: Window
{
// Khi dng c tham s
public ListBox(int top, int left,string theContents) : base(top, left)
//gi khi dng ca lp c s
{
mListBoxContents = theContents;
}
// To mt phin bn mi cho phng thc DrawWindow
// v trong lp dn xut mun thay i hnh vi thc hin
// bn trong phng thc ny
public new void DrawWindow()
{
base.DrawWindow();
Console.WriteLine( ListBox write: {0}, mListBoxContents);
}
// bin thnh vin private
private string mListBoxContents;
}

81 Lp Trnh mi trng Windows


24/02/2009
public class Tester
{
public static void Main()
{
// to i tng cho lp c s
Window w = new Window(5, 10);
w.DrawWindow();
// to i tng cho lp dn xut
ListBox lb = new ListBox( 20, 10, Hello world!);
lb.DrawWindow();
}
}

82 Lp Trnh mi trng Windows


24/02/2009
a hnh
to mt phng thc h tnh a hnh:
khai bo kha virtual trong phng
thc ca lp c s
nh ngha li cc hm virtual, hm
tng ng lp dn xut phi c t kha
Override

83 Lp Trnh mi trng Windows


24/02/2009
Phng thc Override
class MyBaseClass
{
public virtual string VirtualMethod()
{
return "This method is virtual and defined in
MyBaseClass";
}
}
class MyDerivedClass : MyBaseClass
{
public override string VirtualMethod()
{
return "This method is an override defined in
MyDerivedClass";
}
}

84 Lp Trnh mi trng Windows


24/02/2009
Phng thc Override

Lp Window
public virtual void DrawWindow() // m phng v ca s

{
Console.WriteLine(Drawing Window at {0}, {1}, top, left);
}

Lp Listbox
public override void DrawWindow()
{
base.DrawWindow();
Console.WriteLine( ListBox write: {0}, mListBoxContents);
}

85 Lp Trnh mi trng Windows


24/02/2009
Gi cc hm ca lp c s
C php : base.<methodname>()
class CustomerAccount
{
public virtual decimal CalculatePrice()
{
// implementation
}
}
class GoldAccount : CustomerAccount
{
public override decimal CalculatePrice()
{
return base.CalculatePrice() * 0.9M;
}
}

86 Lp Trnh mi trng Windows


24/02/2009
V d

Window[] winArray = new Window[3];


winArray[0] = new Window( 1, 2 );
winArray[1] = new ListBox( 3, 4, List box is array);
winArray[2] = new Button( 5, 6 );

for( int i = 0; i < 3 ; i++)


{
winArray[i].DrawWindow();
}

87 Lp Trnh mi trng Windows


24/02/2009
Lp c s tru tng
abstract class Building
{
public abstract decimal CalculateHeatingCost();
// abstract method
}
Mt lp abstract khng c th hin v mt phng
thc abstract khng c thc thi m phi c
overriden trong bt k lp tha hng khng abstract
n
Nu mt lp c phng thc abstract th n cng l
lp abstract
Mt phng thc abstract s t ng c khai bo
virtual

88 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

Abstract class
public abstract class BankAccount {

public abstract bool IsSufficientFund(decimal Amount);
public abstract void AddInterest();

Khng th new mt abstract class


Ch c lp abstract mi c th cha abstract method

89 Lp Trnh mi trng Windows


Lp c lp (sealed class)
Mt lp c lp th khng cho php cc lp
dn xut t n
khai bo mt lp c lp dng t kha
sealed

90 Lp Trnh mi trng Windows


24/02/2009
Lp Object
Phng thc Chc nng
Equal( ) So snh bng nhau gia hai i
tng
GetHashCode( ) Cho php nhng i tng
cung cp ring nhng hm bm
cho s dng tp hp.
GetType( ) Cung cp kiu ca i tng
ToString( ) Cung cp chui th hin ca i
tng
Finalize( ) Dn dp cc ti nguyn
MemberwiseClone( To mt bn sao t i tng.
)
91 Lp Trnh mi trng Windows
24/02/2009
public class SomeClass
{
public SomeClass(int val)
{
value = val;
}
public override string ToString()
{
return value.ToString();
}
private int value;
}

92 Lp Trnh mi trng Windows


24/02/2009
public class Tester
{
static void Main()
{
int i = 5;
Console.WriteLine("The value of i is: {0}", i.ToString());
SomeClass s = new SomeClass(7);
Console.WriteLine("The value of s is {0}", s.ToString());
Console.WriteLine("The value of 5 is {0}", 5.ToString());
}
}

93 Lp Trnh mi trng Windows


24/02/2009
Lp trong lp
class Nguoi
{
public class Date {
private int ngay;
private int thang;
public Date() { ngay = 1; thang = 1; }
public void Xuat() {Console.WriteLine(ngay + "/" + thang); }
}
private string ten;
private string ho;
private Date ns;
public Nguoi() { ten = "An"; ho = "Nguyen Van"; ns = new Date(); }
public void Xuat()
{
ns.Xuat();Console.WriteLine(ho + " " + ten);
}
}

94 Lp Trnh mi trng Windows


24/02/2009
Lp trong lp
class Progarm
{

static void Main(string[] args)


{
Nguoi a=new Nguoi();
a.Xuat();
ConsoleApplication7.Nguoi.Date ns = new
ConsoleApplication7.Nguoi.Date();
ns.Xuat();
}
}

95 Lp Trnh mi trng Windows


24/02/2009
public class Fraction
{
public Fraction( int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public override string ToString()
{
StringBuilder s = new StringBuilder();
s.AppendFormat({0}/{1},numerator, denominator);
return s.ToString();
}
internal class FractionArtist
{.}
private int numerator;
private int denominator;
}

96 Lp Trnh mi trng Windows


24/02/2009
internal class FractionArtist
{
public void Draw( Fraction f)
{
Console.WriteLine(Drawing the numerator {0},
f.numerator);
Console.WriteLine(Drawing the denominator {0},
f.denominator);
}
}

97 Lp Trnh mi trng Windows


24/02/2009
public class Tester
{
static void Main()
{
Fraction f1 = new Fraction( 3, 4);
Console.WriteLine(f1: {0}, f1.ToString());
Fraction.FractionArtist fa = new
Fraction.FractionArtist();
fa.Draw( f1 );
}
}

98 Lp Trnh mi trng Windows


24/02/2009
Overload Operator

public static Fraction operator + ( Fraction lhs, Fraction rhs)

firstFraction + secondFraction

Fraction.operator+(firstFraction, secondFraction)

np chng ton t (+) th nn cung cp mt phng thc


Add() cng lm cng chc nng l cng hai i tng

99 Lp Trnh mi trng Windows


24/02/2009
Overload Operator
Overload == th phi overload !=
Overload > th phi overload <
Overload >= th phi overload <=
Phi cung cp cc phng thc thay th
cho ton t c np chng

100 Lp Trnh mi trng Windows


24/02/2009
Overload Operator

Biu Tn phng thc thay


tng th
+ Add
- Subtract
* Multiply
/ Divide
== Equals
> Compare

101 Lp Trnh mi trng Windows


24/02/2009
Phng thc Equals

public override bool Equals( object o )

pubic override bool Equals( object o)


{
if ( !(o is Phanso) )
{
return false;
}
return this == (Phanso) o;
}

102 Lp Trnh mi trng Windows


24/02/2009
Ton t chuyn i
int myInt = 5;
long myLong;
myLong = myInt; // ngm nh
myInt = (int) myLong; // tng minh

103 Lp Trnh mi trng Windows


24/02/2009
public class Phanso
{
public Phanso(int ts, int ms)
{
this.ts = ts;
this.ms = ms;
}
public Phanso(int wholeNumber)
{
ts = wholeNumber;
ms = 1;
}
public static implicit operator Phanso(int theInt)
{
return new Phanso(theInt);
}

104 Lp Trnh mi trng Windows


24/02/2009
public static explicit operator int(Phanso thePhanso)
{
return thePhanso.ts / thePhanso.ms;
}
public static bool operator ==(Phanso lhs, Phanso rhs)
{
if (lhs.ts == rhs.ts && lhs.ms == rhs.ms)
{
return true;
}
return false;
}
public static bool operator !=(Phanso lhs, Phanso rhs)
{
return !(lhs == rhs);
}

105 Lp Trnh mi trng Windows


24/02/2009
public override bool Equals(object o)
{
if (!(o is Phanso))
{
return false;
}
return this == (Phanso)o;
}
public static Phanso operator +(Phanso lhs, Phanso rhs)
{
if (lhs.ms == rhs.ms)
{
return new Phanso(lhs.ts + rhs.ts, lhs.ms);
}
int firstProduct = lhs.ts * rhs.ms;
int secondProduct = rhs.ts * lhs.ms;
return new Phanso(firstProduct + secondProduct, lhs.ms * rhs.ms);
}
}

106 Lp Trnh mi trng Windows


24/02/2009
public override string ToString()
{
string s = ts.ToString() + "/" + ms.ToString();
return s;
}
private int ts;
private int ms;
}

107 Lp Trnh mi trng Windows


24/02/2009
public class Tester
{
static void Main()
{
Phanso f1 = new Phanso(3, 4);
Console.WriteLine("f1:{0}", f1.ToString());
Phanso f2 = new Phanso(2, 4);
Console.WriteLine("f2:{0}", f2.ToString());
Phanso f3 = f1 + f2;
Console.WriteLine("f1 + f2 = f3:{0}", f3.ToString());
Phanso f4 = f3 + 5;
Console.WriteLine("f4 = f3 + 5:{0}", f4.ToString());
Phanso f6 = 5+ f3 ;
Console.WriteLine("f6 = 5 + f3:{0}", f6.ToString());
Phanso f5 = new Phanso(2, 4);
if (f5 == f2)
{
Console.WriteLine("f5:{0}==f2:{1}",f5.ToString(), f2.ToString());
}
}
}
108 Lp Trnh mi trng Windows
24/02/2009
Interface(giao din)
Interface l rng buc, giao c m bo cho cc
lp hay cc cu trc s thc hin mt iu g .
Khi mt lp thc thi mt giao din, th lp ny
bo cho cc thnh phn client bit rng lp ny
c h tr cc phng thc, thuc tnh, s
kin v cc ch mc khai bo trong giao
din.
Giao din chnh l phn c t (khng bao hm
phn ci t c th ni dung) ca 1 lp.
Mt lp i tng c th a ra cng lc nhiu
giao din cc chng trnh bn ngoi truy xut

109 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)
Ging m khng ging abstract class! (kh phn
bit)
Interface ch c method hoc property, KHNG
c field (Abstract c th c tt c)
Tt c member ca interface KHNG c php
ci t, ch l khai bo (Abstract class c th c
mt s phng thc c ci t)
Tn cc interface nn bt u bng I
V d: ICollection, ISortable

110 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)
C php nh ngha mt giao din:
[thuc tnh] [b t truy cp] interface <tn
giao din> [: danh sch c s]
{
<phn thn giao din>
}

111 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)
Mt giao din th khng c Constructor
Mt giao din th khng cho php cha cc
phng thc np chng.
N cng khng cho php khai bo nhng
b t trn cc thnh phn trong khi nh
ngha mt giao din.
Cc thnh phn bn trong mt giao din
lun lun l public v khng th khai bo
virtual hay static.

112 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)
Khi mt class khai bo l implement mt
interface, n phi implement tt c method hoc
thuc tnh ca interface
Nu hai interface c trng tn method hoc
property, trong class phi ch r (explicit
interface)
V d: IMovable v IEngine u c thuc tnh MaxSpeed

class ToyotaCar: Car, IMovable, IEngine {


public IMovable.MaxSpeed {

}
public IEngine.MaxSpeed {
}
}

113 Lp Trnh mi trng Windows


24/02/2009
V d

To mt giao din nhm m t nhng phng


thc v thuc tnh ca mt lp cn thit
lu tr
truy cp
t mt c s d liu hay cc thnh phn lu tr d liu
khc nh l mt tp tin

interface IStorable
{
void Read();
void Write(object);
}

114 Lp Trnh mi trng Windows


24/02/2009
public class Document : IStorable
{
public void Read()
{
....
}
public void Write()
{
....
}
}

115 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)

Thc thi nhiu giao din:


public class Document : IStorable, Icompressible
M rng giao din
interface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}
Kt hp cc giao din:
interface IStorableCompressible : IStoreable, ILoggedCompressible
{
void LogOriginalSize();
}

116 Lp Trnh mi trng Windows


24/02/2009
Interface(giao din)
Ton t is
<biu thc> is <kiu d liu>
Ton t as
<biu thc> as <kiu d liu>

117 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

Interface vs Abstract
Abstract: phn nh tt c c im (k c cu trc ni ti)
chung nht ca mt tp i tng no .

Interface: phn nh mt phn c im (bn ngoi) ca mt


loi i tng. Hai i tng v mt bn cht c th rt khc
nhau nhng vn c th c chung mt phn c im no
ging nhau.

V d: xe hi Toyota v hc sinh u c tnh cht chung l di


chuyn c

interface IMovable
{
public 3DPoint Position { get; set; }
public double MaxSpeed { get; set; }
public MoveTo(3DPoint newPosition);
}

118 Lp Trnh mi trng Windows


24/02/2009

Interface vs Abstract
Mt class ch c tha k t mt lp c s

Nhng c php implement (ci t, hin thc ha) nhiu


loi interface khc nhau.

public class ToyotaCar: Car, IMovable, IUsePower


{

}

public class Student: People, IMovable, IBreathable


{

}

119 Lp Trnh mi trng Windows


X l li
Chng trnh no cng c kh nng gp
phi cc tnh hung khng mong mun
ngi dng nhp d liu khng hp l
a cng b y
file cn m b kha
i s cho hm khng hp l
X l nh th no?
Mt chng trnh khng quan trng c th dng li
Chng trnh iu khin khng lu? iu khin my
bay?
X l li truyn thng

X l li truyn thng thng l mi hm li


thng bo trng thi thnh cng/tht bi
qua mt m li
bin ton cc (chng hn errno)
gi tr tr v
int remove ( const char * filename );
tham s ph l tham chiu
double MyDivide(double numerator,
double denominator, int& status);
exception
Exception ngoi l l c ch thng bo
v x l li gii quyt c cc vn k
trn
Tch c phn x l li ra khi phn
thut ton chnh
cho php 1 hm thng bo v nhiu loi
ngoi l
Khng phi hm no cng phi x l li nu c mt
s hm gi thnh chui, ngoi l ch ln c x l
ti mt hm l
khng th b qua ngoi l, nu khng,
chng trnh s kt thc
Tm li, c ch ngoi l mm do hn
X l ngoi l
C# cho php x l nhng li v cc iu kin
khng bnh thng vi nhng ngoi l.
Ngoi l l mt i tng ng gi nhng thng
tin v s c ca mt chng trnh khng bnh
thng
Khi mt chng trnh gp mt tnh hung ngoi
l to mt ngoi l. Khi mt ngoi l c to
ra, vic thc thi ca cc chc nng hin hnh s
b treo cho n khi no vic x l ngoi l tng
ng c tm thy
Mt trnh x l ngoi l l mt khi lnh chng
trnh c thit k x l cc ngoi l m chng
trnh pht sinh
123 Lp Trnh mi trng Windows
24/02/2009
X l ngoi l
nu mt ngoi l c bt v c x l:
chng trnh c th sa cha c vn
v tip tc thc hin hot ng
in ra nhng thng ip c ngha

124 Lp Trnh mi trng Windows


24/02/2009
Pht biu throw
Pht biu throw dng pht ra tn hiu
ca s c bt thng trong khi chng
trnh thc thi vi c php:
throw [expression];
using System;
public class ThrowTest
{
public static void Main()
{
string s = null;
if (s == null)
{
throw(new ArgumentNullException());
}
Console.Write("The string s is null");
// not executed
}
}
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...);
}
}
24/02/2009 128 Lp Trnh mi trng Windows
Enter Main....
Enter Func1...
Enter Func2...
Exception occurred: System.Exception: An exception of type
System.Exception was throw.
at Programming_CSharp.Test.Func2() in ... exception01.cs:line
26
at Programming_CSharp.Test.Func1() in ... exception01.cs:line
20
at Programming_CSharp.Test.Main() in ... exception01.cs:line 12

129 Lp Trnh mi trng Windows


24/02/2009
Pht biu try catch
Trong C#, mt
trnh x l ngoi l
hay mt on
chng trnh x l
cc ngoi l c
gi l mt khi
catch v c to ra
vi t kha catch..
V d: cu lnh
throw c thc thi
bn trong khi try,
v mt khi catch
c s dng
cng b rng mt
public void Func2()
{
Console.WriteLine(Enter Func2...);
try
{
Console.WriteLine(Entering try block...);
throw new System.Exception();
Console.WriteLine(Exiting try block...);
}
catch
{
Console.WriteLine(Exception caught and handled.);
}
Console.WriteLine(Exit Func2...);
}

131 Lp Trnh mi trng Windows


24/02/2009
Enter Main...
Enter Func1...
Enter Func2...
Entering try block...
Exception caught and handled.
Exit Func2...
Exit Func1...
Exit Main...

132 Lp Trnh mi trng Windows


24/02/2009
public void Func1()
{
Console.WriteLine(Enter Func1...);
try
{
Console.WriteLine(Entering try block...);
Func2();
Console.WriteLine(Exiting try block...);
}
catch
{
Console.WriteLine(Exception caught and handled.);
}
Console.WriteLine(Exit Func1...);
}

133 Lp Trnh mi trng Windows


24/02/2009
24/02/2009

public void Func2()


{
Console.WriteLine(Enter Func2...);
throw new System.Exception();
Console.WriteLine(Exit Func2...);
}

Enter Main...
Enter Func1...
Entering try block...
Enter Func2...
Exception caught and handled.
Exit Func1...
Exit Main...

134 Lp Trnh mi trng Windows


24/02/2009

V d
class Test
{
static void Main(string[] args)
{
Test t = new Test();
t.TestFunc();
}
public double DoDivide(double a, double b)
{
if ( b == 0)
throw new System.DivideByZeroException();
if ( a == 0)
throw new System.ArithmeticException();
return a/b;
}

135 Lp Trnh mi trng Windows


public void TestFunc()
24/02/2009
{
try
{
double a = 5;
double b = 0;
Console.WriteLine("{0} / {1} = {2}", a, b, DoDivide(a,b));
}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException caught!");
}
catch (System.ArithmeticException)
{
Console.WriteLine("ArithmeticException caught!");
}
catch
{
Console.WriteLine("Unknown exception caught");
}
}
136 Lp Trnh mi trng Windows
Cu lnh finally
on chng trnh bn trong khi finally c m bo
thc thi m khng quan tm n vic khi no th mt
ngoi l c pht sinh
try
try-block
catch
catch-block
finally
finally-block

137 Lp Trnh mi trng Windows


24/02/2009
Cu lnh finally
1. Dng thc thi bc vo khi try.
2. Nu khng c li xut hin,
- tin hnh mt cch bnh thng
xuyn sut khi try, v khi n cui khi
try, dng thc thi s nhy n khi finally
( bc 5),
- nu mt li xut hin trong khi
try,thc thi s nhy n khi catch (
bc tip theo)
3. Trng thi li c x l trong khi catch
4. vo cui ca khi catch , vic thc thi
c chuyn mt cch t ng n khi
finally
24/02/2009 138 Lp Trnh mi trng Windows
To ring ngoi l
phi c dn xut t
System.ApplicationException

139 Lp Trnh mi trng Windows


24/02/2009

You might also like