You are on page 1of 233

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.

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

Cu trc chng trnh C#

Hello World
01 02 03 04 05 06 07 08 09 using System; class Hello { public static void Main() { Console.WriteLine("Hello, World"); } }

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... } }

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;

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

Sharp");

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

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(); }

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

{0:C}\n" {0:D}\n" {1:E}\n" {1:F}\n" {0:G}\n" {0}

+ + + + +

{0:N}\n" + {1:P}\n" + {1:R}\n" + {0:X}\n",

Console.WriteLine

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);

Console.WriteLine

Console.ReadLine()
public static string ReadLine ()
Convert.ToBoolean(); Convert.ToByte(); Convert.ToInt16(); Byte.Parse(); Int64.Parse(); Double.Parse()

Kiu d liu trong C#

Kiu d liu nh sn
Kiu C#
byte char bool sbyte short ushort

S byte
1 2 1 1 2 2

Kiu .NET
Byte Char Boolean Sbyte Int16 UInt16

M t
S nguyn dng khng du t 0-255 K t Unicode Gi tr logic true/ false S nguyn c du ( t -128 n 127) S nguyn c du gi tr t -32768 n 32767 S nguyn khng du 0 65.535

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.. Kiu du chm ng c chnh xc gp i 1,7E-308 n 1,7E+308 vi 15,16 ch s c ngha.

double

Double

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 Kiu s nguyn c du -9.223.370.036.854.775.808 n 9.223.372.036.854.775.807 S nguyn khng du t 0 n 0xffffffffffffffff

long

Int64

ulong

Uint64

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();

Kiu d liu nh sn

07/03/2013

Lp Trnh mi trng Windows

20

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)

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;

Value type vs reference type


A 105

105

55

55

105

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; } }

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

Box v Unbox

Cc nhm ton t trong C#


Nhm ton t Ton hc Logic Ghp chui Tng, gim Dch bit Quan h Gn +-*/% & | ^ ! ~ && || true false + ++, -<< >> == != < > <= >= = += -= *= /= %= &= |= ^= <<= >>= Ton t

Ch s p kiu Indirection v Address

[] () * -> [ ] &

Th t u tin ca ton t
Nhm ton t Primary {x} x.y f(x) a[x] x++ x-Ton t

Unary
Nhn Cng Dch bit

+ - ! ~ ++x -x (T)x
* / % + << >>

Quan h
Bng Logic trn bit AND XOR

< > <= >= is


== != & ^

OR
iu kin AND iu kin OR iu kin

|
&& || ?:

Assignment

= *= /= %= += -= <<= >>= &= ^= |=

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: int [] a;

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 };

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];

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 ([ ])

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

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 (unmanagedtype).

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.

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; }

Keyword out
void MyMethod() uninitialised { 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 }

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; }

Keyword var
Thay v s dng khai bo bin thng thng ta c th s dng t kha var khai bo bin kiu ngm nh. Mt bin c khai bo bng t kha ny vn c kiu c th, ch khc l kiu ny trnh bin dch xc nh t gi tr c gn. V d: var int_variable = 6; // int_variable is compiled as an int var string_variable = "Mony"; // string_variable is compiled as a string var int_array = new[] { 0, 1, 2 }; // int_array is compiled as int[]

Anonymous Type
To ra 1 kiu mi trong lc chy (khng tn ti cp source code). Kiu mi bao gm mt tp nhng thuc tnh read-only. V d: var obj1 = new { Name = "Mony Hamza", SSN ="12345678" }; // Display the contents: Console.WriteLine("Name: {0}\nSSN: {1}", obj1.Name,obj1.SSN); Console.ReadLine();

Pht biu chn


Pht biu chn (selection statement) trong C# bao gm cc pht biu (if, ifelse, switchcase). Pht biu if if (expression) statement if (expression) { statement1 statement1 } Pht biu ifelse if (expression) statement1 else statement2

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] }

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

Pht biu lp
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

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

Tm tt
Statement Example

Local variable declaration

static void Main() { int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c); }


static void Main() { const float pi = 3.1415927f; const int r = 25; Console.WriteLine(pi * r * r); } static void Main() { int i; i = 123; Console.WriteLine(i); i++; // tng i ln 1 Console.WriteLine(i); }

Local constant declaration

Expression statement

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"); } }
static void Main(string[] args) { 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; } }

switch statement

Tm tt
Statement while statement Example static void Main(string[] args) { 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); }


static void Main(string[] args) { for (int i = 0; i < args.Length; i++) Console.WriteLine(args[i]); }
Lp Trnh mi trng Windows

for statement

07/03/2013

48

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

break statement

continue statement

07/03/2013

49

Tm tt
Statement goto statement Example static void Main(string[] args) { int i = 0; goto check; loop: Console.WriteLine(args[i++]); check: if (i < args.Length) goto loop; } static int Add(int a, int b) { return a + b; } static void Main() { Console.WriteLine(Add(1, 2)); return; }

return statement

checked and unchecked statements

static void Main() { int i = int.MaxValue; checked { Console.WriteLine(i + 1);// Exception } unchecked { Console.WriteLine(i + 1);// Overflow } }

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

using statement

07/03/2013

Tm tt
Statement Example

throw and try statements

static double Divide(double x, double y) { 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); } }

OOP in C#

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 > }

Thuc tnh truy cp


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

V d
01 02 03 04 05 06 hien 07 08 09 10 11 12 13 14 15 using System; public class ThoiGian { public void ThoiGianHienHanh() { Console.WriteLine("Hien thi thoi gian hanh"); } // Cc bin thnh vin int Nam; int Thang; int Ngay; int Gio; int Phut; int Giay; }

V d
16 17 18 19 20 21 22 23 public class Tester { static void Main() { ThoiGian t = new ThoiGian(); t.ThoiGianHienHanh(); } }

Khi to gi tr cho thuc tnh


01 02 03 04 05 06
07 08

09 10 11 12 13 14 15 16

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; }

Khi to gi tr cho thuc tnh


17 18 19 20 21 22 23 24 25 26 27 28 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. }

Khi to gi tr cho thuc tnh


29 30 31 32 33 34 35 36 37 38 39 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(); } }

Phng thc khi to


Hm to mc nh: ging C++
Hm to c i s: tng t C++ public class MyClass { public MyClass() // zero-parameter constructor { // construction code } public MyClass(int number) // another overload { // construction code } }
07/03/2013 Lp Trnh mi trng Windows 61

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; }

Object Initializer
Tnh nng ny gip ta gim thiu s di dng khi khai bo mi mt i tng. Thay v dng cch nh gi tr member thng qua instance ca i tng, ta c th nh trc tip ngay khi va khai bo i tng V d: public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { static void Main(string[] args) { var person = new Person() {Name = John", Age = 25}; } }

Named Arguments v Optional Parameters


Optional parameters: Mt tham s c khai bo l ty chn bng cch t mt gi tr cho n: V d: public MyClass(int x, int y = 5, int z = 7) { ..... } MyClass myClass = new MyClass(1, 2, 3); // gi constructor ca lp MyClass MyClass myClass = new MyClass(1, 2); // thiu tham s z MyClass myClass = new MyClass(1); // thiu tham s y v z

Named Arguments v Optional Parameters


Named and optional arguments: C# khng cho php khng cho php trng cc tham s gia v d MyClass(1, , 3). Nu mun b trng cc tham s gia, mi tham s cn phi gn vi mt ci tn. V d: MyClass myClass = new MyClass(1, z: 3); // passing z by name MyClass myClass = new MyClass(x: 1, z: 3); hay MyClass myClass = new MyClass(z: 3, x: 1);

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

Phng thc hy b
~Class1() { // Thc hin mt s cng vic }
Class1.Finalize() { // Thc hin mt s cng vic base.Finalize(); }

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

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.

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

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

Partial Classes v Parial Methods


C# Cho php ta dng t kha patial phn chia lp thnh nhiu phn c th cha trn nhiu file.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 using System; partial class Person { public void Walk() { Console.WriteLine("Person is Walking"); } } partial class Person { public void Swim() { Console.WriteLine("Person is Swimming"); } }

SVN

07/03/2013

Lp Trnh mi trng Windows

73

Partial Classes v Parial Methods


17 18 19 20 21 22 23 24 25 class Program { static void Main(string[] args) { Person person = new Person(); person.Walk(); person.Swim(); } }

Partial Classes v Parial Methods


Ta cng c th s dng t kha partial khai bo method nhng ta khng th xy dng method c hai ni ca partial class
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 using System; partial class Person { partial void Sing(); } partial class Person { partial void Sing() { Console.WriteLine("Person is Singing"); } public void MethodInvoker() { Sing(); } }

Partial Classes v Parial Methods


Khi dng partial, ta khng th dng chung vi cc t kha public, private, protected, virual, abstract, override Do nu mun gi partial method th ta phi thng qua mt method khc. Trong trng hp trn l MethodInvoker().
18 19 20 21 22 23 24 25 class Program { static void Main(string[] args) { Person person = new Person(); person.MethodInvoker(); } }

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);

Thuc tnh (property)


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);

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; } }

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)

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 }

Thuc tnh ch c
Nu mun thuc tnh ch c, ch s dng phng thc get public int liA { get { return LiA; } }

01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

using System; 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 { Thuc tnh ch c get { Read-only property return _Balance; } } };

Thuc tnh ch c

Thuc tnh ch c
29 30 31 32 33 34 35 36 37 38 39 40 class Program { static void Main(string[] args) { BankAccount myAcct = new BankAccount("100120023003", "Nguyen Van An"); myAcct.Deposit(1000); myAcct.Withdraw(100); Console.WriteLine("Balance: {0}", myAcct.Balance); //myAcct.Balance=10000; Console.ReadLine(); } }

Auto-Implemented Properties
Khi khng cn ci t g c bit cho get v set ca property, Auto-Implemented Properties lm cho vic khai bo property ngn gn hn. V d: class Employee { public int ID{ get; private set; } // read-only public string FirstName { get; set; } public int LastName { get; set; } }

Collection Initializers
n gin ha vic b sung cc phn t ca danh sch thay v dng phng thc Add V d: public class Person { string _Name; List _Intersets = new List(); public string Name { get { return _Name; } set { _Name =value; } } public List Interests { get { return _Intersets; } } }

Collection Initializers
Thay v vit: List PersonList = new List(); Person p1 = new Person(); p1.Name = "Mony Hamza"; p1.Interests.Add("Reading"); p1.Interests.Add("Running"); PersonList.Add(p1); Person p2 = new Person(); p2.Name = "John Luke"; p2.Interests.Add("Swimming"); PersonList.Add(p2); Ta c th vit var PersonList = new List{ new Person{ Name = "Mony Hamza", Interests = { "Reading", "Running" } }, new Person { Name = "John Luke", Interests = { "Swimming"} };

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]);

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.

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.

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

n tha k
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; }

n tha k
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; }

n tha k
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(); } }

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

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"; } }

Phng thc Override


Lp Window public virtual void DrawWindow() { Console.WriteLine(Drawing Window at {0}, {1}, top, left);

// m phng v ca s

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

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; } }

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(); }

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

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

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

Extension Methods
Tnh nng ny cho php ta thm method vo mt lp c xy dng sn m khng lm nh hng n cu trc ca lp. //Lp b nim phong, khng th k tha sealed class Person { public string Name { get; set; } } static class Utility { //Extension method thm vo lp Person static public void ExMethod(this Person person) { person.Name = John"; Console.WriteLine("Name: " + person.Name); } }

Extension Methods
class Program { static void Main(string[] args) { //To instance ca lp Person var person = new Person(); //Gi Extension Method person.ExMethod(); } }

Lp Object
Phng thc Equal( ) GetHashCode( ) Chc nng So snh bng nhau gia hai i tng Cho php nhng i tng cung cp ring nhng hm bm cho s dng tp hp. Cung cp kiu ca i tng Cung cp chui th hin ca i tng Dn dp cc ti nguyn To mt bn sao t i tng.

GetType( ) ToString( ) Finalize( ) MemberwiseClone( )

Lp Object
01 02 03 04 05 06 07 08 09 10 11 12 13 using System; public class SomeClass { public SomeClass(int val) { value = val; } public override string ToString() { return value.ToString(); } private int value; }

Lp Object
14 15 16 17 18 19 20 21 22 23 24 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()); } }

Lp trong lp
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 using System; 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); } }

Lp trong lp
20 21 22 23 24 25 26 27 28 29 30 class Progarm { static void Main(string[] args) { Nguoi a = new Nguoi(); a.Xuat(); Nguoi.Date ns = new Nguoi.Date(); ns.Xuat(); } }

Lp trong lp
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; }

Lp trong lp
internal class FractionArtist { public void Draw( Fraction f) { Console.WriteLine(Drawing the numerator {0}, f.numerator); Console.WriteLine(Drawing the denominator {0}, f.denominator); } }

Lp trong lp
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 ); } }

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

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

Overload Operator
Biu tng + * / == > Tn phng thc thay th Add Subtract Multiply Divide Equals Compare

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; }

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

Ton t chuyn i
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 using System; 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); }

Ton t chuyn i
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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); }

Ton t chuyn i
34 public override bool Equals(object o) 35 { 36 if (!(o is Phanso)) 37 { 38 return false; 39 } 40 return this == (Phanso)o; 41 } 42 public static Phanso operator +(Phanso lhs, Phanso rhs) 43 { 44 if (lhs.ms == rhs.ms) 45 { 46 return new Phanso(lhs.ts + rhs.ts, lhs.ms); 47 } 48 int firstProduct = lhs.ts * rhs.ms; 49 int secondProduct = rhs.ts * lhs.ms; 50 return new Phanso(firstProduct + secondProduct, lhs.ms * rhs.ms); 51 }

Ton t chuyn i
52 53 54 55 56 57 58 59 public override string ToString() { string s = ts.ToString() + "/" + ms.ToString(); return s; } private int ts; private int ms;

Ton t chuyn i
60 public class Tester 61 { 62 static void Main() 63 { 64 Phanso f1 = new Phanso(3, 4); 65 Console.WriteLine("f1:{0}", f1.ToString()); 66 Phanso f2 = new Phanso(2, 4); 67 Console.WriteLine("f2:{0}", f2.ToString()); 68 Phanso f3 = f1 + f2; 69 Console.WriteLine("f1 + f2 = f3:{0}", f3.ToString()); 70 Phanso f4 = f3 + 5; 71 Console.WriteLine("f4 = f3 + 5:{0}", f4.ToString()); 72 Phanso f6 = 5+ f3 ; 73 Console.WriteLine("f6 = 5 + f3:{0}", f6.ToString()); 74 Phanso f5 = new Phanso(2, 4); 75 if (f5 == f2) 76 { 77 Console.WriteLine("f5:{0}==f2:{1}",f5.ToString(), f2.ToString()); 78 } 79 } 80 }

Ton t chuyn i

07/03/2013

Lp Trnh mi trng Windows

123

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

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

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>

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.

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 { } }

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); }

public class Document : IStorable { public void Read() { .... } public void Write() { .... } }

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(); }

Interface(giao din)
Ton t is
<biu thc> is <kiu d liu>

Ton t as
<biu thc> as <kiu d liu>

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 { public public public } IMovable
3DPoint Position { get; set; } double MaxSpeed { get; set; } MoveTo(3DPoint newPosition);

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


{ }

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 kiu x l li truyn thng

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

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

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];

Pht biu throw


01 02 03 04 05 06 07 08 09 10 11 12 13 14 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 } }

Pht biu throw


01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 using System; 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..."); } }

Pht biu throw

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 li c x l

Pht biu try catch


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...); }

Pht biu try catch


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...); }

Pht biu try catch

V d
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 using System; 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; }

V d
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public void TestFunc() { 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"); } } }

V d

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

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 5. khi finally c thc thi

To ring ngoi l
phi c dn xut t System.ApplicationException

Dynamic Binding
Vi dynamic binding, khi nhn c mt i tng, chng ta khng cn phi quan tm kiu ca i tng . Mi trng thc thi s quyt nh phng thc hay php ton no s p dng cho i tng no. iu ny to to s linh hot v n gin khi code V d:
01 02 03 04 05 06 07 08 09 using System; class Person { public string Name { get; set; } public void Swim() { Console.WriteLine("Person is swimming"); } }

Dynamic Binding
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Duck { public string Weight { get; set; } public void Swim() { Console.WriteLine("The Duck is swimming"); } } class Program { //Hm c paramater l mt object dynamic static void InvokeSwim(dynamic obj) { obj.Swim(); }

Dynamic Binding
25 26 27 28 29 30 31 32 33 34 static void Main(string[] args) { //Khai bo 2 object dynamic khc nhau dynamic person = new Person(); dynamic duck = new Duck(); //Truyn 2 object khc kiu vo cng 1 hm InvokeSwim(person); InvokeSwim(duck); } }

Dynamic Binding
Dynamic h tr tt cc Operator +, -, *, / static dynamic Sum(dynamic obj1, dynamic obj2) { return obj1 + obj2; } static void Main(string[] args) { Console.WriteLine(Sum(5, 10)); Console.WriteLine(Sum(5.2, 10.2)); }

Delegates
Mt i tng kiu delegate s cha cc thng tin v method m n tr ti. Nh vy delegate cng ging nh con tr hm trong C++. V d:
01 02 03 04 05 06 07 08 09 using System; delegate void MethodDelegate(); class Person { public void Hello() { Console.WriteLine("Hello Delegate"); } }

Delegates
10 11 12 13 14 15 16 17 18 class Program { static void Main(string[] args) { Person person = new Person(); MethodDelegate helloDelegate = new MethodDelegate(person.Hello); helloDelegate(); //gi hm } }

Delegates
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 using System; delegate void FunctionToCall(ref int x); class Delegate2 { public static void Add2(ref int x) { x += 2; } public static void Add3(ref int x) { x += 3; } static void Main(string[] args) { // Khai bo ng thi gn bng Add2 FunctionToCall functionDelegate = Add2; functionDelegate += Add3; functionDelegate += Add2; functionDelegate += Add2;

Delegates
20 21 22 23 24 25 26 27 28 29 30 31 int x = 5; functionDelegate(ref x); // Gi Console.WriteLine("Value: {0}", int y = 5; functionDelegate = Add2; functionDelegate += Add3; functionDelegate -= Add2; functionDelegate(ref y); // Gi Console.WriteLine("Value: {0}", Console.ReadLine(); } delegate x);

delegate y);

Gi private static method t lp khc


01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 using System; delegate void MethodDelegate(); class Person { public void Hello(MethodDelegate mDelegate) { Console.WriteLine("Hello Delegate"); //Gi Method c truyn vo if (mDelegate != null) mDelegate(); } } class Program { private static void priMethod() { Console.WriteLine("Private Method");

Gi private static method t lp khc


19 20 21 22 23 24 25 26 s 27 28 29 30 static void Main(string[] args) { Person person = new Person(); //Khai bo delegate tr ti privateMethod MethodDelegate helloDelegate = new MethodDelegate(priMethod); //Truyn delegate vo method Hello nh mt i

person.Hello(helloDelegate);
} }

Multicasting
Khng nhng i din cho mt method, delegate cn c kh nng tr ti nhiu method cng lc.
01 02 03 04 05 06 07 08 09 10 11 12 13 using System; delegate void MethodDelegate(); class Person { public void Hello() { Console.WriteLine("Hello Delegate"); } public void Swim() { Console.WriteLine("Person is swimming"); } }

Multicasting
14 15 16 17 18 19 20 21 22 23 class Program { static void Main(string[] args) { Person person = new Person(); MethodDelegate multicastDelegate = null;

//Multicasting delegate multicastDelegate += new MethodDelegate(person.Hello); multicastDelegate += new MethodDelegate(person.Swim);


multicastDelegate(); } }

24 25 26 27

Events
Event l cc s kin xy ra khi chy chng trnh (s kin click ca button, s kin gi tr ca comboBox thay i,). Event gip x l code lnh hot v n gin hn. Khi s dng Event th chng ta khng cn quan tm n vic khi no th t hm x l v khi event pht sinh n s t ng gi hm x l ra thc hin. V d:
01 02 03 04 05 06 07 08 09 10 using System; internal delegate void TextChanged(); class Person { public event TextChanged TextChanged { add { Console.WriteLine("Event added"); } remove { Console.WriteLine("Event removed"); } } }

Events
11 12 13 14 15 16 class Program { static void Main(string[] args) { Person person = new Person(); person.TextChanged += new TextChanged(person_TextChanged); person.TextChanged -= new TextChanged(person_TextChanged); } private static void person_TextChanged() { Console.WriteLine("Event Called"); } }

17
18 19 20 21 22 23 24

Anonymous Method
Thay v khai bo mt event nh sau person.TextChanged += new TextChanged(person_TextChanged); Event tr ti method private static void person_TextChanged() { Console.WriteLine("Event Called"); } By gi vi tnh nng anonymous method, ta c th n gin ha nh sau person.TextChanged += delegate() { Console.WriteLine("Event Called"); };

Lambda Expressions
Lambda Expression c dng vit nhng phng thc anonymous ngn gn dng to ra cc delegate V d:
01 02 03 04 05 06 07 08 09 10 using System; public delegate int MyDelegate(int n); class LambdaExpresion { static void Main() { // Anonymous method that returns the argument multiplied by 10: MyDelegate Obj1 = new MyDelegate(delegate(int n) { return n * 10; }); // Display the result: Console.WriteLine("The value using an anonymous method is: {0}", Obj1(5));

Lambda Expressions
11 12 13 14 15 16 17 // Using lambda expression to do the same job: MyDelegate Obj2 = (int n) => n * 10; // Display the result: Console.WriteLine("The value using a lambda expression is: {0}", Obj2(5)); Console.ReadLine(); } }

Giao din tp hp
Mi trng .NET cung cp nhng giao din chun cho vic lit k, so snh, v to cc tp hp.
IEnumerable Khi mt lp ci t giao din ny, i tng thuc lp c th dng trong cu lnh foreach.

ICollection

Thc thi bi tt c cc tp hp cung cp phng thc


CopyTo() cng nh cc thuc tnh Count, ISReadOnly, ISSynchronized, v SyncRoot. So snh gia hai i tng lu gi trong tp hp

IComparer IList IDictionary IDictionaryEnumerator

sp xp cc i tng trong tp hp. S dng bi nhng tp hp mng c ch mc Dng trong cc tp hp da trn key va value
Cho php lit k dng cu lnh foreach qua tp hp h tr IDictionary.

Interface IEnumerable
Interface ny ch c mt phng thc duy nht l GetEnumerator(), cng vic ca phng thc l tr v mt s thc thi c bit ca IEnumerator. Mc ch ca interface IEnumerable l cho php chng ta c th s dng t kha foreach trn i tng ca class ci t interface ny.

Interface IEnumerator
Interface IEnumerator bao gm 2 phng thc quan trng l
MoveNext, Reset v thuc tnh Current. Thuc tnh Current tr v phn t hin ti ang c duyt ti trong danh sch. MoveNext dng i n phn t tip theo trong danh sch (hay ni cch khc thay i gi tr ca Property Current). Phng thc ny tr v gi tr true nu nh vic di chuyn n i tng tip theo thnh cng, tr v false nu tht bi (trong trng hp n cui danh sch). Reset dng a con tr hin ti v v tr ban u. V tr ban u ny l v tr nm ngy trc phn t u tin trong danh sch.

V d
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System; using System.Collections; public class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } public class People : IEnumerable { private Person[] _people; // Khi to public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } }

V d
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)GetEnumerator(); } public PeopleEnum GetEnumerator() { return new PeopleEnum(_people); } } public class PeopleEnum : IEnumerator { public Person[] _people; int position = -1; // Khi to public PeopleEnum(Person[] list) { _people = list; } // Tng v tr public bool MoveNext() { position++; return (position < _people.Length); }

V d
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 public void Reset() { position = -1; } object IEnumerator.Current { get { return Current; } } public Person Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } }

V d
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 class Program { static void Main() { Person[] peopleArray = new Person[3] { new Person("John", "Smith"), new Person("Jim", "Johnson"), new Person("Sue", "Rabon"), }; People peopleList = new People(peopleArray); // lit k danh sch dng foreach foreach (Person p in peopleList) Console.WriteLine(p.firstName + " " + p.lastName); PeopleEnum peopleEnum = peopleList.GetEnumerator(); peopleEnum.Reset(); // ly ngi u tin trong danh sch peopleEnum.MoveNext(); Person firstPerson = peopleEnum.Current; Console.WriteLine("First Person: {0} {1}", firstPerson.firstName , firstPerson.lastName); } }

V d

Interface ICollection
Interface ICollection cung cp cc thuc tnh: Count, IsSynchronized, v SyncRoot. Ngoi ra ICollection cng cung cp mt phng thc CopyTo(). Thuc tnh thng c s dng l Count, thuc tnh ny tr v s thnh phn trong tp hp.

Interface IComparable
Vai tr ca IComparable l cung cp mt phng php ComparteTo() dng so snh hai i tng.

Interface IComparable
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.Collections; public class Employee : IComparable { private int empID; public Employee(int empID) { this.empID = empID; } public override string ToString() { return empID.ToString(); } public int EmpID { get { return empID; } set { this.empID = value; } }

Interface IComparable
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public int CompareTo(Object o) { Employee r = (Employee)o; return this.empID.CompareTo(r.empID); } } public class Tester { static void Main() { ArrayList empArray = new ArrayList(); Random r = new Random(); for (int i = 0; i < 5; i++) { empArray.Add(new Employee(r.Next(10) + 100)); }

Interface IComparable
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 // In tt c ni dung ca mng for (int i = 0; i < empArray.Count; i++) { Console.Write("{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); // Sp xp li mng Employee da theo phng thc CompareTo() empArray.Sort(); // Hin th tt c ni dung ca mng Employee for (int i = 0; i < empArray.Count; i++) { Console.Write("{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); } }

Interface IComparable

Interface IComparer
Interface IComparer cung cp phng thc Compare(), so snh hai phn t trong mt tp hp c th t. Phng thc Compare() thng c thc thi bng cch gi phng thc CompareTo() ca mt trong nhng i tng. Nu chng ta mun to ra nhng lp c th c sp xp bn trong mt tp hp th chng ta cn thit phi thc thi IComparable.

Interface IComparer
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 using System; using System.Collections; public class Employee: IComparable { private int empID; private int yearsOfSvc = 1; public Employee(int empID) { this.empID = empID; } public Employee(int empID, int yearsOfSvc) { this.empID = empID; this.yearsOfSvc = yearsOfSvc; } public override string ToString() { return "ID: " + empID.ToString() + ". Years of Svc: " + yearsOfSvc.ToString(); } // Phng thc tnh nhn i tng Comparer public static EmployeeComparer GetComparer() { return new Employee.EmployeeComparer(); }

Interface IComparer
025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 public int CompareTo(Object rhs) { Employee r = (Employee)rhs; return this.empID.CompareTo(r.empID); } // Thc thi c bit c gi bi custom comparer public int CompareTo(Employee rhs, Employee.EmployeeComparer.ComparisionType which) { switch (which) { case Employee.EmployeeComparer.ComparisionType.EmpID: return this.empID.CompareTo(rhs.empID); case Employee.EmployeeComparer.ComparisionType.Yrs: return this.yearsOfSvc.CompareTo(rhs.yearsOfSvc); } return 0; } // Lp bn trong thc thi IComparer public class EmployeeComparer : IComparer { private Employee.EmployeeComparer.ComparisionType whichComparision;

Interface IComparer
047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 // nh ngha kiu lit k public enum ComparisionType { EmpID, Yrs }; // Yu cu nhng i tng Employee t so snh vi nhau public int Compare(object lhs, object rhs) { Employee l = (Employee)lhs; Employee r = (Employee)rhs; return l.CompareTo(r, WhichComparision); } public Employee.EmployeeComparer.ComparisionType WhichComparision { get { return whichComparision; } set { whichComparision = value; } } } }

Interface IComparer
073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 public class Teser { static void Main() { ArrayList empArray = new ArrayList(); Random r = new Random(); for (int i = 0; i < 5; i++) { empArray.Add(new Employee(r.Next(10) + 100, r.Next(20))); } // Hin th tt c ni dung ca mng Employee for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); // Sp xp mng theo empID Employee.EmployeeComparer c = Employee.GetComparer(); c.WhichComparision = Employee.EmployeeComparer.ComparisionType.EmpID; empArray.Sort(c);

091

Interface IComparer
092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 // Hin th ni dung ca mng for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); // Sp xp mng theo yearsOfSvc c.WhichComparision = Employee.EmployeeComparer.ComparisionType.Yrs; empArray.Sort(c); // Hin th ni dung ca mng for (int i = 0; i < empArray.Count; i++) { Console.Write("\n{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); } }

Interface IComparer

Interface IDictionary
Interface IDictionary l Interface i din chung cho
kiu tp hp dng cp key v value

IDictionary cung cp mt thuc tnh public l Item.


Thuc tnh Item cho php truy cp phn t trong tp

hp thng qua ton t ch mc ([]) ging nh truy cp


mng.

IDictionaryEnumerator
Nhng i tng IDictionary cng h tr vng lp foreach bng vic thc thi phng thc GetEnumerator(), phng thc ny tr v mt IDictionaryEnumerator.

ArrayList
Lp ArrayList l mt kiu d liu ging nh kiu mng nhng kch thc ca n c th c thay i ng theo yu cu.
Thuc tnh
Capacity Count IsFixedSize IsReadOnly

M t
Thuc tnh get hay set s thnh phn trong ArrayList. Thuc tnh dng xc nh s phn t c trong ArrayList Thuc tnh kim tra xem kch thc ca ArrayList c c nh hay khng Thuc tnh kim tra xem ArrayList c thuc tnh ch c hay khng.

ArrayList
Phng thc M t

Add()
AddRange()

Phng thc public thm mt i tng vo ArrayList


Phng thc public thm nhiu thnh phn ca mt ICollection vo cui ca ArrayList

Clear()
Clone() Contains()

Xa tt c cc thnh phn t ArrayList


To mt bn copy Kim tra mt thnh phn xem c cha trong mng hay khng Phng thc public np chng sao chp mt ArrayList n mt mng mt chiu. Phng thc public np chng tr v mt enumerator dng lp qua mng Thit lp hay truy cp thnh phn trong mng ti v tr xc nh. y l b ch mc cho lp ArrayList.

CopyTo()
GetEnumerator() Item()

ArrayList
Phng thc IndexOf() Insert() InsertRange(0 LastIndexOf() M t Phng thc public np chng tr v ch mc v tr u tin xut hin gi tr Chn mt thnh phn vo trong ArrayList Chn mt dy tp hp vo trong ArrayList Phng thc public np chng tr v ch mc tr tr cui cng xut hin gi tr. Xa s xut hin u tin ca mt i tng xc nh.

Remove() RemoveAt()
RemoveRange() Reverse() SetRange() Sort()

Xa mt thnh phn v tr xc nh.


Xa mt dy cc thnh phn. o th t cc thnh phn trong mng. Sao chp nhng thnh phn ca tp hp qua dy nhng thnh phn trong ArrayList. Sp xp ArrayList.

ToArray()
TrimToSize()

Sao chp nhng thnh phn ca ArrayList n mt mng mi. Thit lp kch thc tht s cha cc thnh phn trong ArrayList

ArrayList
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 using System; using System.Collections; public class Employee { private int empID; public Employee(int empID) { this.empID = empID; } public override string ToString() { return empID.ToString(); } public int EmpID { get { return empID; } set { empID = value; } } }

ArrayList
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 class Program { static void Main(string[] args) { ArrayList empArray = new ArrayList(); ArrayList intArray = new ArrayList(); // a vo mng for (int i = 0; i < 5; i++) { empArray.Add(new Employee(i + 100)); intArray.Add(i * 5); } // in tt c ni dung for (int i = 0; i < intArray.Count; i++) { Console.Write("{0} ", intArray[i].ToString()); } Console.WriteLine("\n");

ArrayList
44 45 46 47 48 49 50 51 52 53 // in tt c ni dung ca mng for (int i = 0; i < empArray.Count; i++) { Console.Write("{0} ", empArray[i].ToString()); } Console.WriteLine("\n"); Console.WriteLine("empArray.Count: {0}", empArray.Count); Console.WriteLine("empArray.Capacity: {0}", empArray.Capacity); } }

Queue (Hng i)
Hng i l mt tp hp trong c th t vo trc v ra trc (FIFO).
Thuc tnh Count IsReadOnly IsSynchronized SyncRoot M t Thuc tnh tr v s thnh phn trong hng i Thuc tnh xc nh hng i l ch c Thuc tnh xc nh hng i c ng b Thuc tnh tr v i tng c th c s dng

ng b truy cp Queue.

Queue (Hng i)
Phng thc Clear() Clone() Contains() CopyTo() Dequeue() Enqueue() GetEnumerator() Peek() ToArray() M t Xa tt c cc thnh phn trong hng i To ra mt bn sao Xc nh xem mt thnh phn c trong mng. Sao chp nhng thnh phn ca hng i n mng mt chiu tn ti Xa v tr v thnh phn bt u ca hng i. Thm mt thnh phn vo hng i. Tr v mt enumerator cho hng i. Tr v phn t u tin ca hng i v khng xa n. Sao chp nhng thnh phn qua mt mng mi

Queue (Hng i)
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.Collections; class Program { public static void Main() { Queue intQueue = new Queue(); // a vo trong mng for(int i=0; i <5; i++) { intQueue.Enqueue(i * 5); } // hin th hng i Console.Write("intQueue values: "); PrintValues( intQueue); // xa thnh phn ra khi hng i Console.WriteLine("\nDequeue: {0}", intQueue.Dequeue()); // hin th hng i Console.Write("intQueue values: "); PrintValues(intQueue); // xa thnh phn khi hng i Console.WriteLine("\nDequeue: {0}", intQueue.Dequeue()); // hin th hng i Console.Write("intQueue values: "); PrintValues(intQueue); // Xem thnh phn u tin trong hng i. Console.WriteLine("\nPeek: {0}", intQueue.Peek());

Queue (Hng i)
25 26 27 28 29 30 31 32 33 34 // hin th hng i Console.Write("intQueue values: "); PrintValues(intQueue); } public static void PrintValues(IEnumerable myCollection) { foreach (Object obj in myCollection) Console.Write("{0} ", obj); Console.WriteLine(); } }

Stack (Ngn xp)


Ngn xp l mt tp hp m th t l vo trc ra sau hay vo sao ra trc (LIFO) Hai phng thc chnh cho vic thm v xa t stack l Push v Pop, ngoi ra ngn xp cng a ra phng thc Peek tng t nh Peek trong hng i.
Thuc tnh Count IsReadOnly IsSynchronized SyncRoot M t Thuc tnh tr v s thnh phn trong ngn xp Thuc tnh xc nh ngn xp l ch c Thuc tnh xc nh ngn xp c ng b Thuc tnh tr v i tng c th c s dng ng b truy cp Stack.

Stack (Ngn xp)


Phng thc Clear() Clone() Contains() CopyTo() M t Xa tt c cc thnh phn trong ngn xp To ra mt bn sao Xc nh xem mt thnh phn c trong mng. Sao chp nhng thnh phn ca ngn xp n mng mt chiu tn ti Pop() Push() Peek() Xa v tr v phn t u Stack a mt i tng vo u ngn xp Tr v phn t u tin ca ngn xp v khng

xa n.
ToArray() Sao chp nhng thnh phn qua mt mng mi

Stack (Ngn xp)


01 02 03 04 05 06 07 08 09 10 11 12 13 14 ); 15 16 17 18 ); 19 20 21 22 using System; using System.Collections; public class Program { static void Main() { Stack intStack = new Stack(); // a vo ngn xp for (int i = 0; i < 8; i++) { intStack.Push(i * 5); } // hin th stack Console.Write("intStack values: "); PrintValues( intStack // xa phn t u tin Console.WriteLine("\nPop: {0}", intStack.Pop()); // hin th stack Console.Write("intStack values: "); PrintValues( intStack // xa tip phn t khc Console.WriteLine("\nPop: {0}", intStack.Pop()); // hin th stack Console.Write("intStack values: "); PrintValues( intStack );

Stack (Ngn xp)


23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // xem thnh phn u tin stack Console.WriteLine("\nPeek: {0}", intStack.Peek()); // hin th stack Console.Write("intStack values: "); PrintValues( intStack); // khai bo mng vi 12 phn t Array targetArray = Array.CreateInstance(typeof(int), 12); for (int i = 0; i <= 8; i++) { targetArray.SetValue(100 * i, i); } // hin th gi tr ca mng Console.WriteLine("\nTarget array: "); PrintValues( targetArray ); // chp ton b stack vo mng ti v tr 6 intStack.CopyTo( targetArray, 6); // hin th gi tr ca mng sau copy Console.WriteLine("\nTarget array after copy: "); PrintValues( targetArray ); // chp ton b stack vo mng mi Object[] myArray = intStack.ToArray(); // hin th gi tr ca mng mi Console.WriteLine("\nThe new array: "); PrintValues( myArray ); }

Stack (Ngn xp)


44 45 46 47 48 49 50 public static void PrintValues(IEnumerable myCollection) { foreach (Object obj in myCollection) Console.Write("{0} ", obj); Console.WriteLine(); } }

Hashtables
Hashtable l mt kiu t in trong c hai thnh phn chnh lin h vi nhau l key v value Hashtable l kiu t in c ti u cho php vic truy cp nhanh chng.
Thuc tnh Count IsReadOnly Keys Values M t Thuc tnh tr v s thnh phn trong hashtable Thuc tnh xc nh hashtable l ch c Thuc tnh tr v mt ICollection cha nhng kha trong hashtable. Thuc tnh tr v mt ICollection cha nhng gi tr trong hashtable.

Hashtables
Phng thc Add() M t Thm mt thnh phn mi vi kha v gi tr xc nh. Xa tt c i tng trong hashtable. Ch mc cho hastable To ra mt bn sao Xc nh xem mt thnh phn c trong hashtable. Xc nh xem hashtable c cha mt kha xc nh Sao chp nhng thnh phn ca hashtable n mng mt chiu tn ti Tr v mt enumerator cho hashtable. Xa mt thnh phn vi kha xc nh.

Clear() Item() Clone() Contains() ContainsKey()

CopyTo()

GetEnumerator() Remove()

Hashtables
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 using System; using System.Collections; public class Tester { static void Main() { // to v khi to hashtable Hashtable hashTable = new Hashtable(); hashTable.Add("00440123","Ngoc Thao"); hashTable.Add("00123001","My Tien"); hashTable.Add("00330124","Thanh Tung"); // truy cp qua thuc tnh Item Console.WriteLine("myHashtable[\"00440123\"]: {0}", hashTable["00440123"]); } }

System.IO
Th vin System.IO cung cp nhiu lp dng cho vic c, ghi file cng nh vic thao tc vi file v th mc Mt s lp chnh ca System.IO

DriveInfo
Thuc tnh/ Phng thc c bn
DriveFormat DriveType

M t

Tn ca file system, v d: NTFS/ FAT32 Cho bit lai a. Kiu d liu tr v l DriveType: CDRom, Fixed, Network, Ram, Removable, Unknown Cho bit a sn sng Read/Write. Tn a Xem dung lng a trng Xem tng dung lng a Ly danh sch a hin c

IsReady Name TotalFreeSpace TotalSize GetDrives()

DriveInfo
01 02 03 04 05 06 07 08 09 10 11 12 13 14 using System; using System.IO; class Test { public static void Main() { DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" File type: {0}", d.DriveType); if (d.IsReady == true) { Console.WriteLine(" Volume label: {0}", d.VolumeLabel); Console.WriteLine(" File system: {0}", d.DriveFormat); Console.WriteLine( " Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);

15
16 17 18

DriveInfo
19 20 21 22 23 24 25 26 27 28 Console.WriteLine( " Total available space: d.TotalFreeSpace); Console.WriteLine( " Total size of drive: d.TotalSize); } } {0, 15} bytes",

{0, 15} bytes",

}
}

DirectoryInfo
Thuc tnh/ phng thc c bn CreationTime Exists FullName LastAccessTime Name Parent FileAttributes Attributes Create() Delete() MoveTo() GetDirectories() GetFiles M t Xem hoc thit lp thi gian to th mc Kim tra th mc tn ti trn a Ly ng dn ca ti th mc Cho bit thi gian cui cng th mc (file) c truy cp Cho bit tn ca th mc Tr v th mc cha. Cho bit thuc tnh ca th mc (file) FileAttributes l 1 enum gm cc gi tr nh: Directory, Readonly, Hidden, To th mc Xa th mc Di chuyn th mc Ly cc th mc con trong th mc Ly tt c cc tp tin trong th mc

DirectoryInfo
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 using System; using System.IO; class Test { public static void Main() { // Specify the directories you want to manipulate. DirectoryInfo di = new DirectoryInfo(@"c:\MyDir"); try { // Determine whether the directory exists. if (di.Exists) { // Indicate that the directory already exists. Console.WriteLine("That path exists already."); return; } // Try to create the directory. di.Create(); Console.WriteLine("The directory was created successfully.");

DirectoryInfo
21 22 23 24 25 26 27 28 29 30 31 // Delete the directory. di.Delete(); Console.WriteLine("The directory was deleted successfully."); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } finally { } } }

FileInfo
Thuc tnh/Phng thc c bn CreationTime Exists Directory DirectoryName Extension Name Attributes CopyTo() Create() Delete() MoveTo() M t Xem hoc thit lp thi gian to th mc Kim tra th mc tn ti trn a Tr v i tng th mc cha Tr v chui ng dn (full path) ca th mc cha Tr v tn ui file (txt,bat,exe,) Cho bit tn ca file Cho bit thuc tnh ca file Copy file n 1 ni khc To file Xa file Di chuyn file hoc i tn file

CreateText OpenText
ReplaceFile

To StreamWriter ghi file To StreamReader c file


Thay i ni dung file

FileInfo
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 using System; using System.IO; class Test { public static void Main() { string path = Path.GetTempFileName(); FileInfo fi1 = new FileInfo(path); //Create a file to write to. using (StreamWriter sw = fi1.CreateText()) { sw.WriteLine("Hello"); sw.WriteLine("And"); sw.WriteLine("Welcome"); } //Open the file to read from. using (StreamReader sr = fi1.OpenText()) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } }

FileInfo
25 26 27 28 29 30 31 32 33 try { string path2 = Path.GetTempFileName(); FileInfo fi2 = new FileInfo(path2); //Ensure that the target does not exist. fi2.Delete(); //Copy the file. fi1.CopyTo(path2); Console.WriteLine("{0} was copied to {1}.", path, path2);

34 35 36
37 38 39 40 41 42 43

//Delete the newly created file. fi2.Delete(); Console.WriteLine("{0} was successfully deleted.",
path2); } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } } }

X l c/ghi file
c v vit d liu s c thc hin thng qua lp Stream. Stream l 1 lung d liu, n a d liu t im bt u n im cui. System.IO.Stream l mt lp abstract nh ngha mt s thnh vin c kh nng h tr vic c/vit ng b (synchronus) hoc khng ng b (asynchronous) i vi khi tr tin

Stream Class
Thuc tnh/Phng thc c bn
CanRead CanSeek CanTimeOut CanWrite Length ReadTimeout

M t
Lung c h tr c Lun c h tr di chuyn con tr Xc nh xem lung c timeout hay khng Lung c h tr ghi Chiu di (theo bytes) ca lung Thit lp timeout cho phng thc Read

WriteTimeout
Position Close() Flush() Read() Seek()

Thit lp timeout cho phng thc Write


Ly hoc xc lp v tr con tr trong lung ng lung v gii phng ti ngun y ton b d liu buffer trong lung ln trn thit b Thc thi phng thc c mng byte trn lung. Di chuyn v tr con tr c

Write()

Ghi mng byte ln trn lung

FileStream Class
Lp FileStream l lp dn xut t lp Stream. FileStream c mt s phng thc v thuc tnh ring.
Thuc tnh/Phng thc c bn M t

Name
Lock() Unlock

Ly tn ca file
Kha file, trnh truy xut ng thi ln File M kha file, c th truy xut ng thi ln file

StreamReader
StreamReader c th dng c vn bn
Thuc Tnh BaseStream
CurrentEncoding EndOfStream Phng thc Close Peek Read ReadBlock ReadLine ReadToEnd

M t Tr v lung c
Ly thng tin nh dng ca lung ang s dng Xc nh con tr c n cui lung cha M t ng lung v gii phng ti nguyn Tr v gi tr k t tip theo trong lung, khng di chuyn con tr c. Thc thi phng thc c mng cc k t trn lung. c khi k t tip theo trn lung. c nguyn dng trn lung c tt c cc k t ti cui lung

V d
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 using System; using System.IO; class Test { public static void Main() { try { // To mt StreamReader c file using (StreamReader sr = new StreamReader("TestFile.txt")) { string line; // c tng dng ca File while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Hin th thng ip li Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } } }

StreamWriter
StreamWriter c th dng ghi vn bn
Thuc tnh AutoFlush BaseStream M t Thit lp c ch t ng Flush, sau mi lnh Write Tr v lung bn di

Encoding

Ly ch m ha hin hnh ca lung

Phng thc

M t

Close
Write WriteLine

ng lung v gii phng ti nguyn


Ghi vo lung Ghi mt chui k t vo lung v xung hng

V d
01 02 03 04 05 06 07 08 09 10 using System; using System.IO; class Program { static void Main(string[] args) { // Ly cc th mc hin hnh trn a DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories(); // Vit tn cc th mc vo file using (StreamWriter sw = new StreamWriter("CDriveDirs.txt")) { foreach (DirectoryInfo dir in cDirs) { sw.WriteLine(dir.Name);

11 12 13 14 15 16 17

}
}

V d
18 19 20 21 22 23 24 25 26 27 28 29 // c v hin thi tn th mc t file string line = ""; using (StreamReader sr = new StreamReader("CDriveDirs.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } }

V d

BinaryReader v BinaryWriter
Tng t nh StreamReader v StreamWriter, BinaryReader v BinaryWriter c th dng d c file nh phn
FileStream theFile = File.Open(@"c:\somefile.bin", FileMode.Open); BinaryReader reader = new BinaryReader(theFile); long number = reader.ReadInt64(); byte[] bytes = reader.ReadBytes(4); string s = reader.ReadString(); reader.Close(); FileStream theFile = File.Open(@"c:\somefile.bin", FileMode.OpenOrCreate, FileAccess.Write); BinaryWriter writer = new BinaryWriter(theFile); long number = 100; byte[] bytes = new byte[] { 10, 20, 50, 100 }; string s = Toi di hoc"; writer.Write(number); writer.Write(bytes); writer.Write(s);

BufferedStream
BufferedStream thng c s dng tng hiu qu c ghi d liu
FileStream newFile = File.Create(@"c:\test.txt"); BufferedStream buffered = new BufferedStream(newFile); StreamWriter writer = new StreamWriter(buffered); writer.WriteLine("Some data"); streamWriter.Close(); bufferedStream.Close(); fileStream.Close();

You might also like