Upload
trung-tran
View
30
Download
1
Embed Size (px)
Citation preview
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 using System;
02
03 class Hello
04 {
05 public static void Main()
06 {
07 Console.WriteLine("Hello, World");
08 }
09 }
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 gnhng namespace trc cc hm hnh vihoc thuc tnh
using Wrox.ProCSharp;
Ta c th gn b danh cho namespace
C php :
using alias = NamespaceName;
V d
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
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 }
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: . . . . . . . . {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);
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# 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
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 i1,7E-308 n 1,7E+308vi 15,16 ch s c ngha.
Kiu d liu nh sn
Kiu C# S byte Kiu .NET M t
decimal 8 Decimal C chnh xc n 28 con sdng trong tnh ton ti chnh
phi c hu t m hay Mtheo sau gi tr
long 8 Int64 Kiu s nguyn c du-9.223.370.036.854.775.808
n9.223.372.036.854.775.807
ulong 8 Uint64 S nguyn khng du t 0 n 0xffffffffffffffff
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();
07/03/2013 Lp Trnh mi trng Windows 20
Kiu d liu nh sn
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 Cconst int Sat = 1;
const int Fri = 6;
Value type vs reference type
55
105A
B ?
?A
B
105
55
?
?A
B
105
struct
struct : value type (class : reference type)
Dng cho cc i tng nh nhPoint, 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 t
Ton hc + - * / %
Logic & | ^ ! ~ && || true false
Ghp chui +
Tng, gim ++, --
Dch bit >
Quan h == != < > =
Gn = += -= *= /= %= &= |= ^= =
Ch s [ ]
p kiu ( )
Indirection v Address * -> [ ] &
Th t u tin ca ton tNhm 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 = *= /= %= += -= = &= ^= |=
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 (unmanaged-type).
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()
{
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
}
uninitialised
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 sdng t kha var khai bo bin kiu ngm nh. Mtbin c khai bo bng t kha ny vn c kiu c th, chkhc 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 ifelseif (expression)
statement1else
statement2
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 switchcase
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
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 ttrong mng hay tp i tng.
Pht biu dng duyt qua tt c cc phn t trong mnghay tp i tng v thc thi mt tp lnh
Pht biu lp
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
Statement Example
Local variable declaration static void Main() { int a; int b = 2, c = 3; a = 1; Console.WriteLine(a + b + c);
}
Local constant declaration static void Main() { 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 1Console.WriteLine(i);
}
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 statement 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;
} }
Tm tt
Statement Example
while statement 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); }
for statement static void Main(string[] args) { for (int i = 0; i < args.Length; i++)
Console.WriteLine(args[i]);}
07/03/2013 Lp Trnh mi trng Windows 48
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 statement static void Main(string[] args) { for (int i = 0; i < args.Length; i++) {
if (args[i].StartsWith("/")) continue; Console.WriteLine(args[i]);
} } 07/03/2013 Lp Trnh mi trng Windows 49
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 statement static int Add(int a, int b) { return a + b; } static void Main() {
Console.WriteLine(Add(1, 2)); return;
}
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 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");
} }
07/03/2013 Lp Trnh mi trng Windows 51
Tm tt
Statement Example
throw and trystatements
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);
} }
Tm tt
OOP in C#
Khai bo lp
[Thuc tnh] [B t truy cp]
class [: Lp c s]
{
}
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 internal
Trong chng trnh v trong lp con
V d
01 using System;
02 public class ThoiGian
03 {
04 public void ThoiGianHienHanh()
05 {
06 Console.WriteLine("Hien thi thoi gian
hien hanh");
07 }
08 // Cc bin thnh vin
09 int Nam;
10 int Thang;
11 int Ngay;
12 int Gio;
13 int Phut;
14 int Giay;
15 }
16 public class Tester
17 {
18 static void Main()
19 {
20 ThoiGian t = new ThoiGian();
21 t.ThoiGianHienHanh();
22 }
23 }
V d
Khi to gi tr cho thuc tnh
01 public class ThoiGian
02 {
03 public void ThoiGianHienHanh()
04 {
05 System.DateTime now = System.DateTime.Now;
06 System.Console.WriteLine("\n Hien tai: \t
{0}/{1}/{2}{3}:{4}:{5}",
07 now.Day, now.Month, now.Year, now.Hour,
now.Minute, now.Second);
08 System.Console.WriteLine(" Thoi Gian:\t
{0}/{1}/{2}{3}:{4}:{5}",
09 Ngay, Thang, Nam, Gio, Phut, Giay);
10 }
11 public ThoiGian( System.DateTime dt)
12 {
13 Nam = dt.Year;Thang = dt.Month;Ngay = dt.Day;
14 Gio = dt.Hour;Phut = dt.Minute;
15 Giay = dt.Second;
16 }
Khi to gi tr cho thuc tnh
17 public ThoiGian(int Year, int Month, int Date,
int Hour, int Minute)
18 {
19 Nam = Year;Thang = Month;Ngay = Date;
20 Gio = Hour;Phut = Minute;
21 }
22 private int Nam;
23 private int Thang;
24 private int Ngay;
25 private int Gio;
26 private int Phut;
27 private int Giay = 30 ; // bin c khi to.
28 }
Khi to gi tr cho thuc tnh
29 public class Tester
30 {
31 static void Main()
32 {
33 System.DateTime currentTime =
System.DateTime.Now;
34 ThoiGian t1 = new ThoiGian( currentTime );
35 t1.ThoiGianHienHanh();
36 ThoiGian t2 = new ThoiGian(2001,7,3,10,5);
37 t2.ThoiGianHienHanh();
38 }
39 }
Phng thc khi to
07/03/2013 Lp Trnh mi trng Windows 61
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 }
}
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 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);
Named Arguments v Optional Parameters
Phng thc hy b
C# cung cp c ch thu dn (garbage collection) v do vy khng cn phi khaibo 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 lpthng qua tn lp
C# khng cho php truy cp n cc phng thctnh v cc bin thnh vin tnh thng qua mt thhin.
Khng c friend
Phng thc tnh hot ng t nhiu ging nhphng 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 using System;
02
03 partial class Person
04 {
05 public void Walk()
06 {
07 Console.WriteLine("Person is Walking");
08 }
09 }
10 partial class Person
11 {
12 public void Swim()
13 {
14 Console.WriteLine("Person is Swimming");
15 }
16 }
SVN
07/03/2013 Lp Trnh mi trng Windows 73
Partial Classes v Parial Methods
17 class Program
18 {
19 static void Main(string[] args)
20 {
21 Person person = new Person();
22 person.Walk();
23 person.Swim();
24 }
25 }
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 class01 using System;
02
03 partial class Person
04 {
05 partial void Sing();
06 }
07 partial class Person
08 {
09 partial void Sing()
10 {
11 Console.WriteLine("Person is Singing");
12 }
13 public void MethodInvoker()
14 {
15 Sing();
16 }
17 }
Khi dng partial, ta khng th dng chung vi cc t kha public,private, protected, virual, abstract, override Do nu mun gipartial method th ta phi thng qua mt method khc. Trong trnghp trn l MethodInvoker().
18 class Program
19 {
20 static void Main(string[] args)
21 {
22 Person person = new Person();
23 person.MethodInvoker();
24 }
25 }
Partial Classes v Parial Methods
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 rat 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 phngthc get
public int liA
{
get
{
return LiA;
}
}
01 using System;
02 public class BankAccount
03 {
04 protected string ID;
05 protected string Owner;
06 protected decimal _Balance;
07 public BankAccount(string ID, string Owner)
08 {
09 this.ID = ID;
10 this.Owner = Owner;
11 this._Balance = 0;
12 }
13 public void Deposit(decimal Amount)
14 {
15 _Balance += Amount;
16 }
17 public void Withdraw(decimal Amount)
18 {
19 _Balance -= Amount; // what if Amount > Balance?
20 }
21 public decimal Balance
22 {
23 get
24 {
25 return _Balance;
26 }
27 }
28 };
Thuc tnh ch c
Read-only property
Fields
Thuc tnh ch c
29 class Program
30 {
31 static void Main(string[] args)
32 {
33 BankAccount myAcct = new BankAccount("100120023003",
"Nguyen Van An");
34 myAcct.Deposit(1000);
35 myAcct.Withdraw(100);
36 Console.WriteLine("Balance: {0}", myAcct.Balance);
37 //myAcct.Balance=10000;
38 Console.ReadLine();
39 }
40 }
Thuc tnh ch c
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 khcnhau v kiu tr v.
Khng chp nhn hai phng thc ch khcnhau v c tnh ca mt thng s ang ckhai 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 hpkhai bo class m khng cho php class khck tha.
n tha k
class MyDerivedClass : MyBaseClass
{
// functions and data members here
}
public class Window
{
// Hm khi dng ly hai s nguyn ch n v tr ca ca s trn consolepublic 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 khngthy bn trong lp dn xut.
private int top;
private int left;
}
n tha k
public class ListBox: Window
{
// Khi dng c tham spublic 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 nypublic new void DrawWindow()
{
base.DrawWindow();
Console.WriteLine( ListBox write: {0}, mListBoxContents);}
// bin thnh vin privateprivate string mListBoxContents;
}
n tha k
public class Tester
{
public static void Main()
{
// to i tng cho lp c sWindow w = new Window(5, 10);
w.DrawWindow();
// to i tng cho lp dn xutListBox lb = new ListBox( 20, 10, Hello world!);lb.DrawWindow();
}
}
n tha k
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 tngng 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 Windowpublic virtual void DrawWindow() // m phng v ca s
{
Console.WriteLine(Drawing Window at {0}, {1}, top, left);}
Lp Listboxpublic override void DrawWindow()
{
base.DrawWindow();
Console.WriteLine( ListBox write: {0}, mListBoxContents);}
Gi cc hm ca lp c s
C php : base.()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 dnxut t n
khai bo mt lp c lp dng t khasealed
Extension MethodsTnh 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 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.
01 using System;
02 public class SomeClass
03 {
04 public SomeClass(int val)
05 {
06 value = val;
07 }
08 public override string ToString()
09 {
10 return value.ToString();
11 }
12 private int value;
13 }
Lp Object
14 public class Tester
15 {
16 static void Main()
17 {
18 int i = 5;
19 Console.WriteLine("The value of i is: {0}",
i.ToString());
20 SomeClass s = new SomeClass(7);
21 Console.WriteLine("The value of s is {0}",
s.ToString());
22 Console.WriteLine("The value of 5 is {0}",
5.ToString());
23 }
24 }
Lp Object
Lp trong lp
01 using System;
02 class Nguoi
03 {
04 public class Date
05 {
06 private int ngay;
07 private int thang;
08 public Date() { ngay = 1; thang = 1; }
09 public void Xuat() { Console.WriteLine(ngay + "/" +
thang); }
10 }
11 private string ten;
12 private string ho;
13 private Date ns;
14 public Nguoi() { ten = "An"; ho = "Nguyen Van"; ns = new
Date(); }
15 public void Xuat()
16 {
17 ns.Xuat(); Console.WriteLine(ho + " " + ten);
18 }
19 }
Lp trong lp
20 class Progarm
21 {
22
23 static void Main(string[] args)
24 {
25 Nguoi a = new Nguoi();
26 a.Xuat();
27 Nguoi.Date ns = new Nguoi.Date();
28 ns.Xuat();
29 }
30 }
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 );
}
}
Lp trong lp
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 thcAdd() cng lm cng chc nng l cng hai i tng
Overload Operator
Overload == th phi overload !=
Overload > th phi overload = th phi overload
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
01 using System;
02 public class Phanso
03 {
04 public Phanso(int ts, int ms)
05 {
06 this.ts = ts;
07 this.ms = ms;
08 }
09 public Phanso(int wholeNumber)
10 {
11 ts = wholeNumber;
12 ms = 1;
13 }
14 public static implicit operator Phanso(int theInt)
15 {
16 return new Phanso(theInt);
17 }
Ton t chuyn i
18 public static explicit operator int(Phanso thePhanso)
19 {
20 return thePhanso.ts / thePhanso.ms;
21 }
22 public static bool operator ==(Phanso lhs, Phanso rhs)
23 {
24 if (lhs.ts == rhs.ts && lhs.ms == rhs.ms)
25 {
26 return true;
27 }
28 return false;
29 }
30 public static bool operator !=(Phanso lhs, Phanso rhs)
31 {
32 return !(lhs == rhs);
33 }
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 public override string ToString()
53 {
54 string s = ts.ToString() + "/" + ms.ToString();
55 return s;
56 }
57 private int ts;
58 private int ms;
59 }
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
Ton t chuyn i
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 [: danh sch c s]
{
}
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 phiimplement tt c method hoc thuc tnh ca interface
Nu hai interface c trng tn method hoc property, trongclass 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 dininterface ILoggedCompressible : ICompressible
{
void LogSavedBytes();
}
Kt hp cc giao din:interface IStorableCompressible : IStoreable, ILoggedCompressible
{
void LogOriginalSize();
}
Interface(giao din)
Ton t is
is
Ton t as
as
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);
}
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 ligii quyt c cc vn k trn
Tch c phn x l li ra khi phn thut tonchnh
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 timt hm l
khng th b qua ngoi l, nu khng, chng trnhs kt thc
Tm li, c ch ngoi l mm do hn kiu x l litruyn 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 cbt thng trong khi chng trnh thc thi vi cphp:
throw [expression];
01 using System;
02 public class ThrowTest
03 {
04 public static void Main()
05 {
06 string s = null;
07 if (s == null)
08 {
09 throw (new ArgumentNullException());
10 }
11 Console.Write("The string s is null");
12 // not executed
13 }
14 }
Pht biu throw
01 using System;
02 public class Test
03 {
04 public static void Main()
05 {
06 Console.WriteLine("Enter Main....");
07 Test t = new Test();
08 t.Func1();
09 Console.WriteLine("Exit Main...");
10 }
11 public void Func1()
12 {
13 Console.WriteLine("Enter Func1...");
14 Func2();
15 Console.WriteLine("Exit Func1...");
16 }
17 public void Func2()
18 {
19 Console.WriteLine("Enter Func2...");
20 throw new System.Exception();
21 Console.WriteLine("Exit Func2...");
22 }
23 }
Pht biu throw
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
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
Pht biu try catch
V d
01 using System;
02 class Test
03 {
04 static void Main(string[] args)
05 {
06 Test t = new Test();
07 t.TestFunc();
08 }
09 public double DoDivide(double a, double b)
10 {
11 if (b == 0)
12 throw new System.DivideByZeroException();
13 if (a == 0)
14 throw new System.ArithmeticException();
15 return a / b;
16 }
17 public void TestFunc()
18 {
19 try
20 {
21 double a = 5;
22 double b = 0;
23 Console.WriteLine("{0} / {1} = {2}", a, b,
DoDivide(a, b));
24 }
25 catch (System.DivideByZeroException)
26 {
27 Console.WriteLine("DivideByZeroException caught!");
28 }
29 catch (System.ArithmeticException)
30 {
31 Console.WriteLine("ArithmeticException caught!");
32 }
33 catch
34 {
35 Console.WriteLine("Unknown exception caught");
36 }
37 }
38 }
V d
V d
Cu lnh finally
try
try-block
catch
catch-block
finally
finally-block
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
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 using System;
02 class Person
03 {
04 public string Name { get; set; }
05 public void Swim()
06 {
07 Console.WriteLine("Person is swimming");
08 }
09 }
10 class Duck
11 {
12 public string Weight { get; set; }
13 public void Swim()
14 {
15 Console.WriteLine("The Duck is swimming");
16 }
17 }
18 class Program
19 {
20 //Hm c paramater l mt object dynamic
21 static void InvokeSwim(dynamic obj)
22 {
23 obj.Swim();
24 }
Dynamic Binding
Dynamic Binding
25 static void Main(string[] args)
26 {
27 //Khai bo 2 object dynamic khc nhau
28 dynamic person = new Person();
29 dynamic duck = new Duck();
30 //Truyn 2 object khc kiu vo cng 1 hm
31 InvokeSwim(person);
32 InvokeSwim(duck);
33 }
34 }
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 using System;
02 delegate void MethodDelegate();
03 class Person
04 {
05 public void Hello()
06 {
07 Console.WriteLine("Hello Delegate");
08 }
09 }
Delegates
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 Person person = new Person();
15 MethodDelegate helloDelegate =
new MethodDelegate(person.Hello);
16 helloDelegate(); //gi hm
17 }
18 }
Delegates01 using System;
02 delegate void FunctionToCall(ref int x);
03 class Delegate2
04 {
05 public static void Add2(ref int x)
06 {
07 x += 2;
08 }
09 public static void Add3(ref int x)
10 {
11 x += 3;
12 }
13 static void Main(string[] args)
14 {
15 // Khai bo ng thi gn bng Add2
16 FunctionToCall functionDelegate = Add2;
17 functionDelegate += Add3;
18 functionDelegate += Add2;
19 functionDelegate += Add2;
Delegates20 int x = 5;
21 functionDelegate(ref x); // Gi delegate
22 Console.WriteLine("Value: {0}", x);
23 int y = 5;
24 functionDelegate = Add2;
25 functionDelegate += Add3;
26 functionDelegate -= Add2;
27 functionDelegate(ref y); // Gi delegate
28 Console.WriteLine("Value: {0}", y);
29 Console.ReadLine();
30 }
31 }
Gi private static method t lp khc01 using System;
02 delegate void MethodDelegate();
03 class Person
04 {
05 public void Hello(MethodDelegate mDelegate)
06 {
07 Console.WriteLine("Hello Delegate");
08 //Gi Method c truyn vo
09 if (mDelegate != null)
10 mDelegate();
11 }
12 }
13 class Program
14 {
15 private static void priMethod()
16 {
17 Console.WriteLine("Private Method");
18 }
Gi private static method t lp khc
19 static void Main(string[] args)
20 {
21 Person person = new Person();
22
23 //Khai bo delegate tr ti privateMethod
24 MethodDelegate helloDelegate = new
MethodDelegate(priMethod);
25
26 //Truyn delegate vo method Hello nh mt i
s
27 person.Hello(helloDelegate);
28 }
29 }
30
Multicasting
Khng nhng i din cho mt method, delegate cn c kh nng tr ti nhiu method cng lc.01 using System;
02 delegate void MethodDelegate();
03 class Person
04 {
05 public void Hello()
06 {
07 Console.WriteLine("Hello Delegate");
08 }
09 public void Swim()
10 {
11 Console.WriteLine("Person is swimming");
12 }
13 }
Multicasting14 class Program
15 {
16 static void Main(string[] args)
17 {
18 Person person = new Person();
19 MethodDelegate multicastDelegate = null;
20
21 //Multicasting delegate
22 multicastDelegate += new
MethodDelegate(person.Hello);
23 multicastDelegate += new
MethodDelegate(person.Swim);
24
25 multicastDelegate();
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 using System;
02 internal delegate void TextChanged();
03 class Person
04 {
05 public event TextChanged TextChanged
06 {
07 add { Console.WriteLine("Event added"); }
08 remove { Console.WriteLine("Event removed"); }
09 }
10 }
11 class Program
12 {
13 static void Main(string[] args)
14 {
15 Person person = new Person();
16 person.TextChanged += new
TextChanged(person_TextChanged);
17 person.TextChanged -= new
TextChanged(person_TextChanged);
18 }
19
20 private static void person_TextChanged()
21 {
22 Console.WriteLine("Event Called");
23 }
24 }
Events
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 using System;
02 public delegate int MyDelegate(int n);
03 class LambdaExpresion
04 {
05 static void Main()
06 {
07 // Anonymous method that returns the argument
multiplied by 10:
08 MyDelegate Obj1 = new MyDelegate(delegate(int
n) { return n * 10; });
09 // Display the result:
10 Console.WriteLine("The value using an
anonymous method is: {0}", Obj1(5));
11 // Using lambda expression to do the
same job:
12 MyDelegate Obj2 = (int n) => n * 10;
13 // Display the result:
14 Console.WriteLine("The value using a
lambda expression is: {0}", Obj2(5));
15 Console.ReadLine();
16 }
17 }
Lambda Expressions
Mi trng .NET cung cp nhng giao din chun cho vic lit k, so snh, v to cc tp hp.
Giao din 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.
IComparer So snh gia hai i tng lu gi trong tp hp
sp xp cc i tng trong tp hp.
IList S dng bi nhng tp hp mng c ch mc
IDictionary Dng trong cc tp hp da trn key va value
IDictionaryEnumerator Cho php lit k dng cu lnh foreach qua tp hp
h tr IDictionary.
Interface ny ch c mt phng thc duynht l GetEnumerator(), cng vic caphng thc l tr v mt s thc thi c bitca IEnumerator.
Mc ch ca interface IEnumerable l chophp chng ta c th s dng t kha foreachtrn i tng ca class ci t interface ny.
Interface IEnumerable
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.
Interface IEnumerator
01 using System;
02 using System.Collections;
03 public class Person
04 {
05 public Person(string fName, string lName)
06 {
07 this.firstName = fName;
08 this.lastName = lName;
09 }
10 public string firstName;
11 public string lastName;
12 }
13 public class People : IEnumerable
14 {
15 private Person[] _people;
16 // Khi to
17 public People(Person[] pArray)
18 {
19 _people = new Person[pArray.Length];
20
21 for (int i = 0; i < pArray.Length; i++)
22 {
23 _people[i] = pArray[i];
24 }
25 }
V d
26 IEnumerator IEnumerable.GetEnumerator()
27 {
28 return (IEnumerator)GetEnumerator();
29 }
30 public PeopleEnum GetEnumerator()
31 {
32 return new PeopleEnum(_people);
33 }
34 }
35
36 public class PeopleEnum : IEnumerator
37 {
38 public Person[] _people;
39 int position = -1;
40 // Khi to
41 public PeopleEnum(Person[] list)
42 {
43 _people = list;
44 }
45 // Tng v tr
46 public bool MoveNext()
47 {
48 position++;
49 return (position < _people.Length);
50 }
V d
51 public void Reset()
52 {
53 position = -1;
54 }
55 object IEnumerator.Current
56 {
57 get
58 {
59 return Current;
60 }
61 }
62 public Person Current
63 {
64 get
65 {
66 try
67 {
68 return _people[position];
69 }
70 catch (IndexOutOfRangeException)
71 {
72 throw new InvalidOperationException();
73 }
74 }
75 }
76 }
V d
77 class Program
78 {
79 static void Main()
80 {
81 Person[] peopleArray = new Person[3]
82 {
83 new Person("John", "Smith"),
84 new Person("Jim", "Johnson"),
85 new Person("Sue", "Rabon"),
86 };
87 People peopleList = new People(peopleArray);
88 // lit k danh sch dng foreach
89 foreach (Person p in peopleList)
90 Console.WriteLine(p.firstName + " " + p.lastName);
91 PeopleEnum peopleEnum = peopleList.GetEnumerator();
92 peopleEnum.Reset();
93 // ly ngi u tin trong danh sch
94 peopleEnum.MoveNext();
95 Person firstPerson = peopleEnum.Current;
96 Console.WriteLine("First Person: {0} {1}",
firstPerson.firstName , firstPerson.lastName);
97 }
98 }
V d
V d
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 ICollection
Vai tr ca IComparable l cung cp mt phng php ComparteTo() dng so snh hai i tng.
Interface IComparable
01 using System;
02 using System.Collections;
03 public class Employee : IComparable
04 {
05 private int empID;
06 public Employee(int empID)
07 {
08 this.empID = empID;
09 }
10 public override string ToString()
11 {
12 return empID.ToString();
13 }
14 public int EmpID
15 {
16 get
17 {
18 return empID;
19 }
20 set
21 {
22 this.empID = value;
23 }
24 }
Interface IComparable
25 public int CompareTo(Object o)
26 {
27 Employee r = (Employee)o;
28 return this.empID.CompareTo(r.empID);
29 }
30 }
31 public class Tester
32 {
33 static void Main()
34 {
35 ArrayList empArray = new ArrayList();
36 Random r = new Random();
37 for (int i = 0; i < 5; i++)
38 {
39 empArray.Add(new Employee(r.Next(10) + 100));
40 }
Interface IComparable
41 // In tt c ni dung ca mng
42 for (int i = 0; i < empArray.Count; i++)
43 {
44 Console.Write("{0} ", empArray[i].ToString());
45 }
46 Console.WriteLine("\n");
47 // Sp xp li mng Employee da theo phng thc
CompareTo()
48 empArray.Sort();
49 // Hin th tt c ni dung ca mng Employee
50 for (int i = 0; i < empArray.Count; i++)
51 {
52 Console.Write("{0} ", empArray[i].ToString());
53 }
54 Console.WriteLine("\n");
55 }
56 }
Interface IComparable
Interface IComparable
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 using System;
002 using System.Collections;
003 public class Employee: IComparable
004 {
005 private int empID;
006 private int yearsOfSvc = 1;
007 public Employee(int empID)
008 {
009 this.empID = empID;
010 }
011 public Employee(int empID, int yearsOfSvc)
012 {
013 this.empID = empID;
014 this.yearsOfSvc = yearsOfSvc;
015 }
016 public override string ToString()
017 {
018 return "ID: " + empID.ToString() + ". Years of Svc: " +
yearsOfSvc.ToString();
019 }
020 // Phng thc tnh nhn i tng Comparer
021 public static EmployeeComparer GetComparer()
022 {
023 return new Employee.EmployeeComparer();
024 }
Interface IComparer
025 public int CompareTo(Object rhs)
026 {
027 Employee r = (Employee)rhs;
028 return this.empID.CompareTo(r.empID);
029 }
030 // Thc thi c bit c gi bi custom comparer
031 public int CompareTo(Employee rhs,
Employee.EmployeeComparer.ComparisionType which)
032 {
033 switch (which)
034 {
035 case Employee.EmployeeComparer.ComparisionType.EmpID:
036 return this.empID.CompareTo(rhs.empID);
037 case Employee.EmployeeComparer.ComparisionType.Yrs:
038 return this.yearsOfSvc.CompareTo(rhs.yearsOfSvc);
039 }
040 return 0;
041 }
042
043 // Lp bn trong thc thi IComparer
044 public class EmployeeComparer : IComparer
045 {
046 private Employee.EmployeeComparer.ComparisionType
whichComparision;
Interface IComparer
047 // nh ngha kiu lit k
048 public enum ComparisionType
049 {
050 EmpID, Yrs
051 };
052 // Yu cu nhng i tng Employee t so snh vi nhau
053 public int Compare(object lhs, object rhs)
054 {
055 Employee l = (Employee)lhs;
056 Employee r = (Employee)rhs;
057 return l.CompareTo(r, WhichComparision);
058 }
059 public Employee.EmployeeComparer.ComparisionType
WhichComparision
060 {
061 get
062 {
063 return whichComparision;
064 }
065 set
066 {
067 whichComparision = value;
068 }
069 }
070 }
071 }
072
Interface IComparer
073 public class Teser
074 {
075 static void Main()
076 {
077 ArrayList empArray = new ArrayList(); Random r = new
Random();
078 for (int i = 0; i < 5; i++)
079 {
080 empArray.Add(new Employee(r.Next(10) + 100,
r.Next(20)));
081 }
082 // Hin th tt c ni dung ca mng Employee
083 for (int i = 0; i < empArray.Count; i++)
084 {
085 Console.Write("\n{0} ", empArray[i].ToString());
086 }
087 Console.WriteLine("\n");
088 // Sp xp mng theo empID
089 Employee.EmployeeComparer c = Employee.GetComparer();
090 c.WhichComparision =
Employee.EmployeeComparer.ComparisionType.EmpID;
091 empArray.Sort(c);
Interface IComparer
092 // Hin th ni dung ca mng
093 for (int i = 0; i < empArray.Count; i++)
094 {
095 Console.Write("\n{0} ", empArray[i].ToString());
096 }
097 Console.WriteLine("\n");
098 // Sp xp mng theo yearsOfSvc
099 c.WhichComparision =
Employee.EmployeeComparer.ComparisionType.Yrs;
100 empArray.Sort(c);
101 // Hin th ni dung ca mng
102 for (int i = 0; i < empArray.Count; i++)
103 {
104 Console.Write("\n{0} ", empArray[i].ToString());
105 }
106 Console.WriteLine("\n");
107 }
108 }
Interface IComparer
Interface IComparer
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.
Interface IDictionary
Nhng i tng IDictionary cng h tr vng lp foreach bng vic thc thi phng thc GetEnumerator(), phng thc ny tr v mt IDictionaryEnumerator.
IDictionaryEnumerator
ArrayList
Lp ArrayList l mt kiu d liu ging nh kiumng nhng kch thc ca n c th c thayi ng theo yu cu.
Thuc tnh M t
Capacity Thuc tnh get hay set s thnh phn trong ArrayList.
Count Thuc tnh dng xc nh s phn t c trong ArrayList
IsFixedSize Thuc tnh kim tra xem kch thc ca ArrayList c c nh hay khng
IsReadOnly Thuc tnh kim tra xem ArrayList c thuc tnh ch c hay khng.
Phng thc M t
Add() Phng thc public thm mt i tng vo ArrayList
AddRange() Phng thc public thm nhiu thnh phn ca mt ICollection vo cui ca ArrayList
Clear() Xa tt c cc thnh phn t ArrayList
Clone() To mt bn copy
Contains() Kim tra mt thnh phn xem c cha trong mnghay khng
CopyTo() Phng thc public np chng sao chp mtArrayList n mt mng mt chiu.
GetEnumerator() Phng thc public np chng tr v mtenumerator dng lp qua mng
Item() Thit lp hay truy cp thnh phn trong mng ti v tr xc nh. y l b ch mc cho lp ArrayList.
ArrayList
ArrayList Phng thc M t
IndexOf() Phng thc public np chng tr v ch mc v tr u tinxut hin gi tr
Insert() Chn mt thnh phn vo trong ArrayList
InsertRange(0 Chn mt dy tp hp vo trong ArrayList
LastIndexOf() Phng thc public np chng tr v ch mc tr tr cuicng xut hin gi tr.
Remove() Xa s xut hin u tin ca mt i tng xc nh.
RemoveAt() Xa mt thnh phn v tr xc nh.
RemoveRange() Xa mt dy cc thnh phn.
Reverse() o th t cc thnh phn trong mng.
SetRange() Sao chp nhng thnh phn ca tp hp qua dynhng thnh phn trong ArrayList.
Sort() Sp xp ArrayList.
ToArray() Sao chp nhng thnh phn ca ArrayList n mt mngmi.
TrimToSize() Thit lp kch thc tht s cha cc thnh phn trongArrayList
01 using System;
02 using System.Collections;
03 public class Employee
04 {
05 private int empID;
06 public Employee(int empID)
07 {
08 this.empID = empID;
09 }
10 public override string ToString()
11 {
12 return empID.ToString();
13 }
14 public int EmpID
15 {
16 get
17 {
18 return empID;
19 }
20 set
21 {
22 empID = value;
23 }
24 }
25 }
ArrayList
26 class Program
27 {
28 static void Main(string[] args)
29 {
30 ArrayList empArray = new ArrayList();
31 ArrayList intArray = new ArrayList();
32 // a vo mng
33 for (int i = 0; i < 5; i++)
34 {
35 empArray.Add(new Employee(i + 100));
36 intArray.Add(i * 5);
37 }
38 // in tt c ni dung
39 for (int i = 0; i < intArray.Count; i++)
40 {
41 Console.Write("{0} ", intArray[i].ToString());
42 }
43 Console.WriteLine("\n");
ArrayList
44 // in tt c ni dung ca mng
45 for (int i = 0; i < empArray.Count; i++)
46 {
47 Console.Write("{0} ", empArray[i].ToString());
48 }
49 Console.WriteLine("\n");
50 Console.WriteLine("empArray.Count: {0}", empArray.Count);
51 Console.WriteLine("empArray.Capacity: {0}",
empArray.Capacity);
52 }
53 }
ArrayList
Hng i l mt tp hp trong c th t votrc v ra trc (FIFO).
Queue (Hng i)
Thuc tnh M t
Count Thuc tnh tr v s thnh phn trong hng
i
IsReadOnly Thuc tnh xc nh hng i l ch c
IsSynchronized Thuc tnh xc nh hng i c ng b
SyncRoot Thuc tnh tr v i tng c th c s
dng
ng b truy cp Queue.
Phng thc M t
Clear() Xa tt c cc thnh phn trong hng i
Clone() To ra mt bn sao
Contains() Xc nh xem mt thnh phn c trong mng.
CopyTo() Sao chp nhng thnh phn ca hng i n
mng mt chiu tn ti
Dequeue() Xa v tr v thnh phn bt u ca hng i.
Enqueue() Thm mt thnh phn vo hng i.
GetEnumerator() Tr v mt enumerator cho hng i.
Peek() Tr v phn t u tin ca hng i v khng
xa n.
ToArray() Sao chp nhng thnh phn qua mt mng mi
Queue (Hng i)
01 using System;
02 using System.Collections;
03 class Program
04 {
05 public static void Main()
06 {
07 Queue intQueue = new Queue();
08 // a vo trong mng
09 for(int i=0; i
25 // hin th hng i
26 Console.Write("intQueue values: "); PrintValues(intQueue);
27 }
28 public static void PrintValues(IEnumerable myCollection)
29 {
30 foreach (Object obj in myCollection)
31 Console.Write("{0} ", obj);
32 Console.WriteLine();
33 }
34 }
Queue (Hng i)
Ngn xp l mt tp hp m th t l vo trc ra sau hayvo sao ra trc (LIFO)
Hai phng thc chnh cho vic thm v xa t stack l Pushv Pop, ngoi ra ngn xp cng a ra phng thc Peektng t nh Peek trong hng i.
Stack (Ngn xp)
Thuc tnh M t
Count Thuc tnh tr v s thnh phn trong ngn xp
IsReadOnly Thuc tnh xc nh ngn xp l ch c
IsSynchronized Thuc tnh xc nh ngn xp c ng b
SyncRoot Thuc tnh tr v i tng c th c s dng
ng b truy cp Stack.
Stack (Ngn xp)
Phng thc M t
Clear() Xa tt c cc thnh phn trong ngn xp
Clone() To ra mt bn sao
Contains() Xc nh xem mt thnh phn c trong mng.
CopyTo() Sao chp nhng thnh phn ca ngn xp n
mng mt chiu tn ti
Pop() Xa v tr v phn t u Stack
Push() a mt i tng vo u ngn xp
Peek() Tr v phn t u tin ca ngn xp v khng
xa n.
ToArray() Sao chp nhng thnh phn qua mt mng mi
01 using System;
02 using System.Collections;
03 public class Program
04 {
05 static void Main()
06 {
07 Stack intStack = new Stack();
08 // a vo ngn xp
09 for (int i = 0; i < 8; i++)
10 {
11 intStack.Push(i * 5);
12 }
13 // hin th stack
14 Console.Write("intStack values: "); PrintValues( intStack
);
15 // xa phn t u tin
16 Console.WriteLine("\nPop: {0}", intStack.Pop());
17 // hin th stack
18 Console.Write("intStack values: "); PrintValues( intStack
);
19 // xa tip phn t khc
20 Console.WriteLine("\nPop: {0}", intStack.Pop());
21 // hin th stack
22 Console.Write("intStack values: "); PrintValues( intStack
);
Stack (Ngn xp)
23 // xem thnh phn u tin stack
24 Console.WriteLine("\nPeek: {0}", intStack.Peek());
25 // hin th stack
26 Console.Write("intStack values: "); PrintValues( intStack);
27 // khai bo mng vi 12 phn t
28 Array targetArray = Array.CreateInstance(typeof(int), 12);
29 for (int i = 0; i
44 public static void PrintValues(IEnumerable myCollection)
45 {
46 foreach (Object obj in myCollection)
47 Console.Write("{0} ", obj);
48 Console.WriteLine();
49 }
50 }
Stack (Ngn xp)
Hashtable l mt kiu t in trong c hai thnh phnchnh lin h vi nhau l key v value
Hashtable l kiu t in c ti u cho php vic truycp nhanh chng.
Hashtables
Thuc tnh M t
Count Thuc tnh tr v s thnh phn trong hashtable
IsReadOnly Thuc tnh xc nh hashtable l ch c
Keys Thuc tnh tr v mt ICollection cha nhngkha trong hashtable.
Values Thuc tnh tr v mt ICollection cha nhnggi
tr trong hashtable.
Phng thc M t
Add() Thm mt thnh phn mi vi kha v gi trxc
nh.Clear() Xa tt c i tng trong hashtable.
Item() Ch mc cho hastable
Clone() To ra mt bn sao
Contains() Xc nh xem mt thnh phn c tronghashtable.
ContainsKey() Xc nh xem hashtable c cha mt kha xc
nhCopyTo() Sao chp nhng thnh phn ca hashtable
n
mng mt chiu tn tiGetEnumerator() Tr v mt enumerator cho hashtable.
Remove() Xa mt thnh phn vi kha xc nh.
Hashtables
Hashtables
01 using System;
02 using System.Collections;
03 public class Tester
04 {
05 static void Main()
06 {
07 // to v khi to hashtable
08 Hashtable hashTable = new Hashtable();
09 hashTable.Add("00440123","Ngoc Thao");
10 hashTable.Add("00123001","My Tien");
11 hashTable.Add("00330124","Thanh Tung");
12 // truy cp qua thuc tnh Item
13 Console.WriteLine("myHashtable[\"00440123\"]: {0}",
hashTable["00440123"]);
14 }
15 }
16
Th vin System.IO cung cp nhiu lp dng cho vic c, ghifile cng nh vic thao tc vi file v th mc
Mt s lp chnh ca System.IO
System.IO
DriveInfo
Thuc tnh/ Phng thc c bn
M t
DriveFormat Tn ca file system, v d: NTFS/ FAT32
DriveType Cho bit lai a. Kiu d liu tr v l DriveType: CDRom, Fixed, Network, Ram,
Removable, Unknown
IsReady Cho bit a sn sng Read/Write.
Name Tn a
TotalFreeSpace Xem dung lng a trng
TotalSize Xem tng dung lng a
GetDrives() Ly danh sch a hin c
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 DriveInfo[] allDrives = DriveInfo.GetDrives();
08 foreach (DriveInfo d in allDrives)
09 {
10 Console.WriteLine("Drive {0}", d.Name);
11 Console.WriteLine(" File type: {0}", d.DriveType);
12 if (d.IsReady == true)
13 {
14 Console.WriteLine(" Volume label: {0}",
d.VolumeLabel);
15 Console.WriteLine(" File system: {0}",
d.DriveFormat);
16 Console.WriteLine(
17 " Available space to current user:{0, 15}
bytes",
18 d.AvailableFreeSpace);
DriveInfo
19 Console.WriteLine(
20 " Total available space: {0, 15} bytes",
21 d.TotalFreeSpace);
22 Console.WriteLine(
23 " Total size of drive: {0, 15} bytes",
24 d.TotalSize);
25 }
26 }
27 }
28 }
DriveInfo
Thuc tnh/ phng thc c bn
M t
CreationTime Xem hoc thit lp thi gian to th mc
Exists Kim tra th mc tn ti trn a
FullName Ly ng dn ca ti th mc
LastAccessTime Cho bit thi gian cui cng th mc (file) c truy cp
Name Cho bit tn ca th mc
Parent Tr v th mc cha.
FileAttributes Attributes Cho bit thuc tnh ca th mc (file) FileAttributes l 1 enum gm cc gi tr nh: Directory, Readonly, Hidden,
Create() To th mc
Delete() Xa th mc
MoveTo() Di chuyn th mc
GetDirectories() Ly cc th mc con trong th mc
GetFiles Ly tt c cc tp tin trong th mc
DirectoryInfo
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 // Specify the directories you want to manipulate.
08 DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
09 try
10 {
11 // Determine whether the directory exists.
12 if (di.Exists)
13 {
14 // Indicate that the directory already exists.
15 Console.WriteLine("That path exists already.");
16 return;
17 }
18 // Try to create the directory.
19 di.Create();
20 Console.WriteLine("The directory was created
successfully.");
DirectoryInfo
21 // Delete the directory.
22 di.Delete();
23 Console.WriteLine("The directory was deleted
successfully.");
24 }
25 catch (Exception e)
26 {
27 Console.WriteLine("The process failed: {0}",
e.ToString());
28 }
29 finally { }
30 }
31 }
DirectoryInfo
FileInfoThuc tnh/Phng thc c bn
M t
CreationTime Xem hoc thit lp thi gian to th mc
Exists Kim tra th mc tn ti trn a
Directory Tr v i tng th mc cha
DirectoryName Tr v chui ng dn (full path) ca th mc cha
Extension Tr v tn ui file (txt,bat,exe,)
Name Cho bit tn ca file
Attributes Cho bit thuc tnh ca file
CopyTo() Copy file n 1 ni khc
Create() To file
Delete() Xa file
MoveTo() Di chuyn file hoc i tn file
CreateText To StreamWriter ghi file
OpenText To StreamReader c file
ReplaceFile Thay i ni dung file
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 string path = Path.GetTempFileName();
08 FileInfo fi1 = new FileInfo(path);
09 //Create a file to write to.
10 using (StreamWriter sw = fi1.CreateText())
11 {
12 sw.WriteLine("Hello");
13 sw.WriteLine("And");
14 sw.WriteLine("Welcome");
15 }
16 //Open the file to read from.
17 using (StreamReader sr = fi1.OpenText())
18 {
19 string s = "";
20 while ((s = sr.ReadLine()) != null)
21 {
22 Console.WriteLine(s);
23 }
24 }
FileInfo
25 try
26 {
27 string path2 = Path.GetTempFileName();
28 FileInfo fi2 = new FileInfo(path2);
29 //Ensure that the target does not exist.
30 fi2.Delete();
31 //Copy the file.
32 fi1.CopyTo(path2);
33 Console.WriteLine("{0} was copied to {1}.", path,
path2);
34 //Delete the newly created file.
35 fi2.Delete();
36 Console.WriteLine("{0} was successfully deleted.",
path2);
37 }
38 catch (Exception e)
39 {
40 Console.WriteLine("The process failed: {0}",
e.ToString());
41 }
42 }
43 }
FileInfo
c v vit d liu s c thc hin thng qualp Stream.
Stream l 1 lung d liu, n a d liu tim bt u n im cui.
System.IO.Stream l mt lp abstract nhngha mt s thnh vin c kh nng h tr vicc/vit ng b (synchronus) hoc khng ngb (asynchronous) i vi khi tr tin
X l c/ghi file
Thuc tnh/Phng thc c bn
M t
CanRead Lung c h tr c
CanSeek Lun c h tr di chuyn con tr
CanTimeOut Xc nh xem lung c timeout hay khng
CanWrite Lung c h tr ghi
Length Chiu di (theo bytes) ca lung
ReadTimeout Thit lp timeout cho phng thc Read
WriteTimeout Thit lp timeout cho phng thc Write
Position Ly hoc xc lp v tr con tr trong lung
Close() ng lung v gii phng ti ngun
Flush() y ton b d liu buffer trong lung ln trn thit b
Read() Thc thi phng thc c mng byte trn lung.
Seek() Di chuyn v tr con tr c
Write() Ghi mng byte ln trn lung
Stream Class
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 Ly tn ca file
Lock() Kha file, trnh truy xut ng thi ln File
Unlock M kha file, c th truy xutng thi ln file
StreamReader
Thuc Tnh M t
BaseStream Tr v lung c
CurrentEncoding Ly thng tin nh dng ca lung ang s dng
EndOfStream Xc nh con tr c n cui lung cha
Phng thc M t
Close ng lung v gii phng ti nguyn
Peek Tr v gi tr k t tip theo trong lung, khng di chuyn con tr c.
Read Thc thi phng thc c mng cc k t trn lung.
ReadBlock c khi k t tip theo trn lung.
ReadLine c nguyn dng trn lung
ReadToEnd c tt c cc k t ti cui lung
StreamReader c th dng c vn bn
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 try
08 {
09 // To mt Strea