Professional Documents
Culture Documents
Tài Liệu Lập Trình C# Tiếng Việt
Tài Liệu Lập Trình C# Tiếng Việt
jsp
Copyright vietjack.com
Mc lc
Hc C# c bn v nng cao ................................................................................................. 8
i vi c gi ...................................................................................................................... 8
iu kin tin ................................................................................................................... 8
Tng quan v C# .................................................................................................................. 8
Cc c im lp trnh mnh m ca C# .......................................................................... 9
Ci t mi trng C# .......................................................................................................... 9
Gii thiu .Net Framework .............................................................................................. 10
Integrated Development Environment (IDE) cho C# ....................................................... 10
Vit chng trnh C# trn Linux hoc Mac OS................................................................ 11
Cu trc chng trnh C# ................................................................................................... 11
To chng trnh Hello World trong C# .......................................................................... 11
Bin dch v thc thi chng trnh C# ............................................................................. 13
C php C# c bn ............................................................................................................ 14
T kha using trong C# .................................................................................................. 16
T kha class trong C#................................................................................................... 16
Comments trong C# ....................................................................................................... 16
Bin thnh vin trong C#................................................................................................. 16
Hm thnh vin trong C# ................................................................................................ 16
Thuyt minh mt Class trong C#..................................................................................... 16
nh danh (Identifier) trong C# ........................................................................................ 17
T kha trong C#............................................................................................................ 17
Kiu d liu trong C# .......................................................................................................... 18
Kiu gi tr trong C#......................................................................................................... 19
Kiu tham chiu trong C#................................................................................................ 21
Kiu object trong C# ............................................................................................... 21
Kiu Dynamic trong C# .......................................................................................... 21
Kiu string trong C# ................................................................................................ 22
http://vietjack.com/ Trang chia s cc bi hc online min ph
Trang 1
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 2
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 3
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 4
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 5
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 6
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 7
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Hc C# c bn v nng cao
C# l mt ngn ng lp trnh n gin, hin i, mc ch tng qut, hng i tng c pht
trin bi Microsoft bn trong phn khi u .NET ca h, c pht trin ch yu bi Anders
Hejlsberg, mt kin trc s phn mm ni ting vi cc sn phm Turbo Pascal, Delphi, J++, WFC.
Lot bi hng dn ny s cung cp cho bn kin thc c bn v lp trnh C# qua cc khi nim
t c bn n nng cao lin quan ti ngn ng lp trnh C#.
Lot bi hng dn ca chng ti da trn ngun ti liu ca: Tutorialspoint
i vi c gi
Lot bi hng dn ny c xy dng cho ngi mi hc gip h hiu cc khi nim c bn
v lp trnh C#.
iu kin tin
Ngn ng lp trnh C# l da trn cc ngn ng lp trnh C v C++, v th, nu bn hiu c bn
v C v C++, th iu ny s gip bn hc tp C# d dng hn.
Tng quan v C#
C# l mt ngn ng lp trnh n gin, hin i, mc ch tng qut, hng i tng c pht
trin bi Microsoft v c ph chun bi European Computer Manufacturers Association (ECMA)
v International Standards Organization (ISO).
C# c pht trin bi Anders Hejlsberg v team ca ng trong khi pht trin .Net Framework.
C# c thit k cho Common Language Infrastructure (CLI), m gm Executable Code v
Runtime Environment, cho php chng ta s dng cc ngn ng high-level a dng trn cc nn
tng v cu trc my tnh khc nhau.
Di y l cc l do lm C# l ngn ng lp trnh chuyn nghip c s dng rng ri:
N l hng i tng.
Trang 8
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
N d dng hc.
N l mt ngn ng c cu trc.
Cc c im lp trnh mnh m ca C#
Cu trc C# kh gn vi cc ngn ng high-level truyn thng, C v C++, v l mt ngn ng lp
trnh hng i tng. N c s ging nhau mnh m vi Java, n c nhiu c im lp trnh
mnh m m lm cho n tr nn a thch vi cc lp trnh vin trn ton th gii.
Di y l cc c im quan trng ca C#:
iu kin Boolean
T ng dn rc bi Garbage-Collector (GC)
Assembly
Indexer
Tch hp vi Windows
Ci t mi trng C#
Trong chng ny, chng ti s gii thiu cc cng c cn thit ci t mi trng C#. Chng
ti cp rng C# l mt phn ca .Net Framework v c s dng vit cc ng dng
.Net. V th, trc khi tho lun v cc cng c c sn chy mt chng trnh C#, bn nn hiu
cch C# lin quan ti .Net Framework.
Trang 9
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Windows application
Web application
Dch v Web
Metadata v Assembly
Windows Form
ADO.Net
LINQ
Trang 10
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Hai cng c sau l c sn v min ph ti Website chnh thc ca Microsoft. S dng cc tool ny,
bn c th vit tt c cc loi chng trnh C# t cc ng dng dng lnh n gin ti cc ng
dng phc tp hn. Bn cng c th vit cc tp source code ca C# bi s dng mt Text Editor
c bn, nh Notepad, v bin dch code vo trong Assembly bi s dng Command-line
Compiler, m l mt phn ca .Net Framework.
Trong lot bi ny, chng ti s dng Visual C# 2010 Express v bn c th ti n t:Microsoft
Visual Studio. N c ci t t ng trn my tnh ca bn.
Khai bo Namespace
Mt class
Phng thc ca lp
Thuc tnh ca lp
Comment
Trang 11
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
Dng tip theo c mt khai bo class, class HelloWorld cha cc nh ngha d liu v
phng thc m chng trnh ca bn s dng. Ni chung, class cha nhiu phng
thc. Cc phng thc nh ngha hnh vi ca class. Tuy nhin, lpHelloWorld ch c mt
phng thc Main.
Dng tip theo nh ngha phng thc Main, m l entry point cho tt c chng trnh
C#. Phng thc Main biu din trng thi lp khi c thc thi.
Dng tip theo /**/ b b qua bi compiler v n l comment cho chng trnh.
Trang 12
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Dng cui cng Console.ReadKey(); l cho VS.NET Users. N lm chng trnh i cho
mt phm c nhn v n ngn cn mn hnh chy v ng mt cch nhanh chng khi
chng trnh c pht ng t Visual Studio.Net.
Bn nn ghi nh cc im sau:
Bt u Visual Studio.
Nhn nt Run hoc nhn phm F5 thc thi project. Mt ca s Command Prompt xut
hin m cha dng Hello World.
Bn c th bin dch mt chng trnh C# bi s dng command-line thay cho Visual Studio IDE:
Trang 13
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Lu tp di dng helloworld.cs
C php C# c bn
C# l mt ngn ng lp trnh hng i tng. Trong phng php lp trnh hng i tng, mt
chng trnh gm cc i tng a dng m tng tc vi nhau cc cch thc ca action. Cc
action m mt i tng c th nhn c gi l cc phng thc. Cc i tng cng loi c
xem nh l c cng kiu hoc, c xem nh l trong cng lp.
V d, xt i tng Rectangle. N c cc thuc tnh nh length v width. Ph thuc vo thit k
trn. N c th cn nhng cch cp nhn cc gi tr ca thuc tnh ny, tnh ton din tch v
hin th chi tit.
Bn theo di v d sau trin khai mt lp Rectangle v c php C# c bn ca chng trnh ny:
using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4.5;
width = 3.5;
Trang 14
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
Trang 15
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
T kha using c s dng bao namespace trong chng trnh. Mt chng trnh C# c th
bao nhiu lnh using.
Comments trong C#
Comment c s dng thuyt minh code. Compiler b qua cc comment. Cc comment a
dng trong cc chng trnh C# bt u vi /* v kt thc vi */ nh sau:
/* This program demonstrates
The basic syntax of C# programming
Language */
bo
bn
trong
lp
Lp
Rectangle
cha
hm
thnh
vin
l: AcceptDetails,GetArea v Display.
Trang 16
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
T kha trong C#
T kha l cc t dnh ring (Reserved Keyword) c nh ngha trc cho C# compiler. Nhng
t kha ny khng th c s dng lm nh danh. Tuy nhin, nu bn mun s dng cc t
kha ny lm nh danh, bn c th t k t @ trc chng.
Trong C#, mt s nh danh c ngha c bit trong ng cnh ca code, v d nh get v set
c gi l cc contextual keyword (t kha thuc ng cnh).
Bng sau lit k cc t kha dnh ring v cc t kha thuc ng cnh trong C#:
Reserved Keyword
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
in (generic
modifier)
int
Trang 17
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
interface
internal
is
lock
long
namespace
new
null
object
operator
out
out (generic
modifier)
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
void
volatile
while
add
alias
ascending
descending
dynamic
from
get
global
group
into
join
let
orderby
partial
(type)
partial
(method)
remove
select
set
Trang 18
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Kiu gi tr trong C#
Cc bin kiu gi tr c th c gn mt gi tr mt cch trc tip. Chng c k tha t
lp System.ValueType.
Kiu gi tr trc tip cha d liu. Mt s v d l int, char, v float, tng ng gi s nguyn, ch
ci, v s thc. Khi bn khai bo mt kiu int, h thng cp pht b nh lu gi tr .
Bng sau lit k cc kiu gi tr c sn trong C# 2010:
Kiu
Biu din
Dy gi tr
Gi tr
mc
nh
bool
Gi tr Boolean
False
byte
0 ti 255
char
Kiu Unicode
character (16 bit)
U +0000 ti U +ffff
'\0'
decimal
0.0M
double
0.0D
float
0.0F
int
-2,147,483,648 ti 2,147,483,647
long
-9,223,372,036,854,775,808 ti
9,223,372,036,854,775,807
0L
Trang 19
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
sbyte
-128 ti 127
short
-32,768 ti 32,767
uint
0 ti 4,294,967,295
ulong
0 ti 18,446,744,073,709,551,615
ushort
0 ti 65,535
Trang 20
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
dynamic d = 20;
Kiu dynamic l tng t vi kiu object, ngoi tr vic kim tra cho cc bin kiu object din ra ti
compile time, trong khi vic kim tra cc bin kiu dynamic din ra ti run time.
Trang 21
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d:
char* cptr;
int* iptr;
Chng ta s tho lun v kiu con tr chng: Unsafe Code trong C#.
Trang 22
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Chuyn i kiu tng minh (explicit) - Vic chuyn i ny c thc hin mt cch r
rng bi ngi dng bng vic s dng cc hm c nh ngha trc. Cc chuyn i
kiu tng minh cn mt ton t cast.
ToBoolean
Trang 23
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
ToByte
Chuyn i mt kiu thnh mt byte
ToChar
Chuyn i mt kiu thnh mt Unicode character, nu c th
ToDateTime
Chuyn i mt kiu (kiu integer hoc string) thnh cc cu trc date-time
ToDecimal
Chuyn i mt kiu s thc hoc s nguyn thnh mt kiu thp phn
ToDouble
Chuyn i mt kiu thnh mt kiu double
ToInt16
Chuyn i mt kiu thnh mt 16-bit integer
ToInt32
Chuyn i mt kiu thnh mt 32-bit integer
ToInt64
Chuyn i mt kiu thnh mt 64-bit integer
10
ToSbyte
Chuyn i mt kiu thnh mt kiu signed byte
Trang 24
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
ToSingle
11
ToString
12
ToType
13
ToUInt16
14
ToUInt32
15
ToUInt64
16
Trang 25
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
Console.ReadKey();
}
}
}
Bin trong C#
Mt bin l khng g khc ngoi mt tn c cung cp cho khu vc lu gi m chng trnh c
th thao tc. Mi bin trong C# c mt kiu c th, m quyt nh kch c v cch b tr b nh ca
bin , cch dy gi tr c th c lu gi trong b nh , v cch tp hp cc hot ng c
th c p dng ti bin .
Cc kiu gi tr c bn trong C# c th c phn chia thnh:
Kiu
V d
Kiu Integral
float v double
Kiu Decimal
decimal
Trang 26
http://vietjack.com/csharp/index.jsp
Kiu Boolean
Kiu Nullable
Copyright vietjack.com
C# cng cho php nh ngha cc kiu gi tr khc ca bin nh kiu enum v cc kiu tham chiu
ca bin nh class, s c bn lun trong cc chng ti.
y, data_type phi l mt kiu d liu hp l trong C#, gm: char, int, double hoc bt k kiu
d liu t nh ngha (user-defined) no v variable_list c th cha mt hoc nhiu tn nh danh
c phn bit bi du phy.
Di y l mt s nh ngha bin hp l trong C#:
int i, j, k;
char c, ch;
float f, salary;
double d;
Trang 27
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
/* initializing d and f. */
byte z = 22;
/* initializes z. */
Vic khi to bin mt cch chnh xc l mt bi thc hnh tt cho bn, nu khng th chng
trnh c th to ra kt qu khng mong i.
V d sau s dng cc kiu bin a dng trong C#:
using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
Trang 28
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
a = 10, b = 20, c = 30
Hm Convert.ToInt32() chuyn i d liu nhp bi ngi dng thnh kiu d liu int, bi
v Console.ReadLine() chp nhn d liu trong nh dng chui.
lvalue: Mt biu thc m l mt lvalue c th xut hin hoc bn tri hoc bn phi ca
php gn trong C#.
Trang 29
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Constant l mt kiu d liu thay th cho Literal, cn Literal th hin chnh n. Trong v d: const PI
= 3.14 th Constant y l PI, cn Literal l 3.14.
Constant c th l bt k kiu d liu c bn no trong C#, v c th c phn chia thnh gi tr
hng s nguyn, hng s thc, hng k t, hng chui v Boolean literal (tm dch: hng logic).
Ngoi ra, C# cng c cc kiu hng lit k.
Ngoi ra, constant c i x ging nh cc bin thng thng, ngoi tr vic gi tr ca chng
l khng th thay i sau khi nh ngha.
/* Legal */
215u
/* Legal */
0xFeeL
/* Legal */
078
032UU
/* decimal */
0213
/* octal */
0x4b
/* hexadecimal */
30
/* int */
30u
/* unsigned int */
30l
/* long */
30ul
/* unsigned long */
Trang 30
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
/* Legal */
314159E-5L
/* Legal */
510E
210f
.e55
Khi th hin dng decimal phi bao gm du chm thp phn, phn m hoc c hai. Khi th hin
dng m phi gm phn nguyn, phn l hoc c hai. Dng m i km vi k t E hoc e.
Hng k t trong C#
Cc hng k t trong C# m u v kt thc bi du nhy n. Nu hng k t bt u vi L (v
d Lx) th n l kiu wchar_t. Nu khng th, n l hng k t kiu char, v d nh x.
Hng k t c th l mt k t (nh X), mt escape sequence (nh \t) hay mt k t m rng (nh
\u02c0).
Mt s k t trong C# khi c ng trc bi du \ th chng s mang mt ngha c bit nh
bt u dng mi \n hay to mt tab \t. Chng c bit nh l escape sequence (dy thot).
Bng di y th hin mt s m escape sequence ph bin:
Dy thot
ngha
\\
K t \
\'
K t '
\"
K t "
Trang 31
http://vietjack.com/csharp/index.jsp
\?
K t ?
\a
Ting chung
\b
Backspace
\f
Form feed
\n
Dng mi
\r
Carriage return
\t
tab ngang
\v
tab dc
\ooo
S trong c s 8 ca 1 n 3 k s
\xhh . . .
Copyright vietjack.com
Sau y l v d ch mt s k t dy thot:
using System;
namespace EscapeChar
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
Trang 32
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
World
Chng trnh sau minh ha cch nh ngha v s dng mt hng trong chng trnh C# ca bn:
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;
Trang 33
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}
Ton t trong C#
Mt ton t l mt biu tng, m ni cho compiler thc hin cc thao tc ton hc v logic c th.
C# cung cp nhiu ton t c sn, l:
Ton t s hc
Ton t quan h
Ton t logic
Ton t gn
Ton t hn hp
Ton t s hc trong C#
Bng di lit k cc ton t s hc c h tr bi ngn ng C#. Gi s bin A gi gi tr 10,
bin B gi 20 th:
Trang 34
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
Ton
t
Miu t
V d
A + B s cho kt qu l 30
A - B s cho kt qu l -10
A * B s cho kt qu l 200
B / A s cho kt qu l 2
Chia ly phn d
B % A s cho kt qu l 0
++
A++ s cho kt qu l 11
--
A-- s cho kt qu l 9
Miu t
V d
==
Kim tra nu 2 ton hng bng nhau hay khng. Nu bng th iu kin l
true.
(A ==
B) l
khng
ng.
Trang 35
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
!=
Kim tra 2 ton hng c gi tr khc nhau hay khng. Nu khng bng th
iu kin l true.
(A !=
B) l
true.
>
(A >
B) l
khng
ng.
<
Kim tra nu ton hng bn tri nh hn ton hng bn phi hay khng. Nu
nh hn th l true.
(A <
B) l
true.
>=
(A >=
B) l
khng
ng.
<=
(A <=
B) l
true.
Miu t
V
d
&&
(A
&&
B) l
false.
Trang 36
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
||
(A ||
B) l
true.
!(A
&&
B) l
true.
p&q
p|q
p^q
Trang 37
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
~A = 1100 0011
Cc ton t so snh bit c h tr bi ngn ng C# c lit k trong bng di y. Gi s ta
c bin A c gi tri 60 v bin B c gi tr 13, ta c:
V d
Ton
t
Miu t
V d
&
(A &
B) s
cho
kt
qu
l 12,
tc l
0000
1100
(A |
B) s
cho
kt
qu
l 61,
tc l
0011
1101
(A ^
B) s
cho
kt
qu
l 49,
tc l
0011
0001
Trang 38
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
(~A )
s
cho
kt
qu
l 61,
tc l
1100
0011.
<<
Ton t dch tri. Gi tr ton hng tri c dch chuyn sang tri bi s cc
bit c xc nh bi ton hng bn phi.
A <<
2 s
cho
kt
qu
240,
tc l
1111
0000
(dch
sang
tri
hai
bit)
>>
Ton t dch phi. Gi tr ton hng tri c dch chuyn sang phi bi s
cc bit c xc nh bi ton hng bn phi.
A >>
2 s
cho
kt
qu
l 15,
tc l
0000
1111
(dch
sang
phi
hai
bit)
Trang 39
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Ton t gn trong C#
y l nhng ton t gn c h tr bi ngn ng C#:
V d
Ton
t
Miu t
V d
C=A
+ B s
gn
gi tr
ca A
+B
vo
trong
C
+=
C +=
A
tng
ng
vi C
=C+
A
-=
C -= A
tng
ng
vi C
=CA
*=
C *= A
tng
ng
vi C
=C*
A
Trang 40
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
/=
Chia ton hng tri cho ton hng phi v gn gi tr ny cho ton hng tri.
C /= A
tng
ng
vi C
=C/
A
%=
Ly phn d ca php chia ton hng tri cho ton hng phi v gn cho
ton hng tri.
C %=
A
tng
ng
vi C
=C%
A
<<=
C <<=
2
tng
ng
vi C
=C
<< 2
>>=
C >>=
2
tng
ng
vi C
=C
>> 2
&=
C &=
2
tng
ng
vi C
=C&
2
Trang 41
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
^=
C ^= 2
tng
ng
vi C
=C^
2
|=
Php OR bit.
C |= 2
tng
ng
vi C
=C|2
Cc ton t hn hp trong C#
Di y l mt s ton t hn hp quan trng gm sizeof, typeof v ? : c h tr bi ngn
ng C#.
V d
Ton
t
Miu t
V d
sizeof()
sizeof(int), tr v 4
typeof()
Tr v kiu ca mt lp
typeof(StreamReader);
&
Tr v a ch ca mt bin
&a; tr v a ch thc
s ca bin
Tr ti mt bin
*a; to con tr vi tn
l a ti mt bin
?:
Nu Condition l true
? Th gi tr X : Nu
khng th Y
Trang 42
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
is
as
Ton t
Th t u tin
Postfix
() [] -> . ++ - -
Unary
Tnh nhn
*/%
Tnh cng
+-
Dch chuyn
<< >>
Trang 43
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Quan h
Cn bng
== !=
&
Php OR bit
&&
Php OR logic
||
iu kin
?:
Gn
Du phy
Trang 44
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
C# cung cp cc loi lnh iu khin lung sau. Bn nhn vo link thy chi tit.
Lnh
Miu t
Lnh if trong C#
Trang 45
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Ton t ? : trong C#
Chng ta bn v ton t iu kin ? : trong chng trc m c th c dng thay th
cho lnh if...else. N c mu chung nh sau:
Exp1 ? Exp2 : Exp3;
Trong Exp1, Exp2 v Exp3 l cc biu thc. Ch vic s dng v t ca du hai chm.
Gi tr ca biu thc Exp1 trc du ? c gi tr true, Exp2 c thc hin, v gi tr ca n l gi
tr ca biu thc. Nu Exp1 l false th Exp3 c thc hin v gi tr ca n l gi tr ca biu
thc.
Vng lp trong C#
C mt tnh hung m bn cn phi thc hin mt on code mt vi ln. Nhn chung, cc cu
lnh c thc hin mt cch tun t. Cu lnh u tin ca hm c thc hin trc, sau
n cu th 2 v tip tc.
Ngn ng lp trnh cung cp cho chng ta nhiu cu trc iu khin v cho php bn thc hin
nhng phn phc tp.
Vng lp cho php thc hin mt lnh v mt nhm lnh nhiu ln , di y l dng tng qut:
Trang 46
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
C# h tr nhng lnh iu khin sau y. Click chut vo link xem chi tit.
Kiu vng lp
Miu t
Miu t
Vng lp v hn trong C#
Mt vng lp l vng lp v hn khi mt iu kin khng bao gi false. Vng lp for thng c
s dng cho mc ch ny. Khi bn ba biu thc iu kin trong vng lp for trng th bn s
to ra mt vng lp v hn.
Trang 47
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Hey! I am Trapped");
}
}
}
}
Khi biu thc iu kin vng mt, n c gi s l lun ng. Bn c th c mt biu thc khi
to v biu thc lng gia, nhng cc lp trnh vin C# thng s dng for(;;) biu th mt vng
lp v hn.
Tnh ng gi trong C#
Encapsulation (Tnh ng gi) c nh ngha l tin trnh ng gi mt hoc nhiu mc bn
trong mt gi logic hoc vt l. Tnh ng gi, trong phng php lp trnh hng i tng, ngn
cn vic truy cp ti chi tit ca trnh trnh trin khai (Implementation Detail).
Tnh tru tng v tnh ng gi l hai c im c lin quan vi nhau trong lp trnh hng i
tng. Tnh tru tng cho php to cc thng tin lin quan c th nhn thy v tnh ng gi cho
lp trnh vin kh nng trin khai tru tng c k tha.
Tnh ng gi c trin khai bi s dng Access Specifier. Mt Access Specifier nh ngha
phm vi v tnh nhn thy ca mt thnh vin lp. C# h tr cc Access Specifier sau:
Public
Private
Protected
Trang 48
http://vietjack.com/csharp/index.jsp
Internal
Protected internal
Copyright vietjack.com
class ExecuteRectangle
{
static void Main(string[] args)
Trang 49
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
Trang 50
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
//member variables
private double length;
private double width;
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
Trang 51
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
Trong v d, cc bin thnh vin length v width c khai bo private, v th chng khng th
c truy cp t hm Main(). Cc hm thnh vin AcceptDetails() v Display() c th truy cp cc
bin ny. Khi cc hm thnh vin AcceptDetails() v Display() c khai bopublic, chng c th
c truy cp t hm Main() bi s dng mt Instance (mt s th hin) ca lp Rectangle, tn
l r.
Trang 52
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
//member variables
internal double length;
internal double width;
double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
Trang 53
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Gi phng thc
Access Specifier: nh ngha tnh nhn thy ca mt bin hoc mt phng thc vi lp
khc.
Trang 54
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Method name: Tn phng thc l mt nh danh duy nht v n l phn bit kiu ch. N
khng th ging bt k nh danh no khc c khai bo trong lp .
Parameter list: Danh sch tham s c bao quanh trong du ngoc n, cc tham s ny
c s dng truyn v nhn d liu t mt phng thc. Danh sch tham s lin
quan ti kiu, th t, v s tham s ca mt phng thc. Cc tham s l ty , tc l mt
phng thc c th khng cha tham s no.
Method body: Phn thn phng thc cha tp hp cc ch th cn thit hon thnh
hot ng yu cu.
V d
Chng trnh sau minh ha mt hm FindMax nhn hai gi tr integer v tr v s no ln hn
trong hai s. N c Access Specifier, v th n c th c truy cp t bn ngoi lp bi s dng
mt Instance (s th hin) ca lp .
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
...
}
Trang 55
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 56
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
Bn cng c th gi phng thc public t cc lp khc bng vic s dng Instance (s th hin)
ca lp . V d, phng thc FindMax thuc lp NumberManipulator, bn c th gi n t
lp Test.
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
}
class Test
{
static void Main(string[] args)
{
/* local variable definition */
Trang 57
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
Trang 58
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
result = factorial(num - 1) * num;
return result;
}
}
Miu t
Trang 59
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Phng thc ny sao chp tham chiu ti v tr
b nh ca mt tham s vo trong tham s
chnh thc. Ngha l cc thay i c to ra
ti tham s chnh thc nh hng ti tham s
Nullable trong C#
C# cung cp mt kiu d liu c bit, kiu nullable, t bn c th gn dy cc gi tr thng
thng cng nh cc gi tr null trong C#.
V d: Bn c th lu gi bt k gi tr t -2,147,483,648 ti 2,147,483,647 hoc null trong mt bin
Nullable<Int32>. Tng t, bn c th gn true, false hoc null trong mt bin Nullable<bool>. C
php khai bo mt kiu nullable trong C# l nh sau:
< data_type> ? <variable_name> = null;
Trang 60
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
Console.WriteLine("A Nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
, 3.14157
Ton t ?? trong C#
Ton t Null Coalescing hay ton t ?? trong C# c s dng vi cc kiu gi tr nullable v cc
kiu tham chiu. N c s dng chuyn i mt ton hng ti ton hng vi kiu nullable, ti
y c th l mt s chuyn i ngm nh.
Vi ton t ny s lm code bn gn, sch v chuyn nghip hn. Ton t ?? c gii thiu
t C# phin bn 2.0. Ton t ?? c 2 ton hng. Nu gi tr ca ton hng u tin l null, th ton
t tr v gi tr ca ton hng th hai; nu khng th, n tr v gi tr ca ton hng u tin. V d
sau minh ha ton t ?? trong C#:
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Trang 61
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Ti y:
Trang 62
http://vietjack.com/csharp/index.jsp
arrayName xc nh tn mng.
Copyright vietjack.com
V d:
double[] balance;
{ 99,
{ 99,
Bn c th sao chp mt bin mng vo trong bin mng mc tiu khc. Trong tnh hung ny, c
bin mc tiu v bin ngun u tr ti cng v tr b nh:
int [] marks = new int[]
{ 99,
Trang 63
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d sau minh ha khi nim v khai bo, gn v truy cp mng trong C# cp trn:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int []
int i,j;
Trang 64
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 65
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}
}
Miu t
Trang 66
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
mng
Lp Array trong C#
Trang 67
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 68
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Thuc tnh
Chars
Ly i tng Char ti mt v tr c th trong i tng String hin ti
Length
Ly s k t ca i tng String hin ti
Phng thc
Trang 69
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
public static string Concat(string str0, string str1, string str2, string str3)
Ni chui bn i tng String
10
11
12
Trang 70
http://vietjack.com/csharp/index.jsp
13
Copyright vietjack.com
14
15
16
17
18
19
20
Trang 71
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
21
22
public static string Join(string separator, string[] value, int startIndex, int count)
Ni chui cc phn t xc nh ca mt mng chui, bi s dng Separator (b
tch) cho gia mi phn t
23
24
25
26
27
Trang 72
http://vietjack.com/csharp/index.jsp
28
Copyright vietjack.com
29
30
31
32
33
34
35
Trang 73
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
36
V d
V d sau minh ha mt s phng thc trn:
So snh chui trong C#:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 +
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
Trang 74
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 75
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
}
}
}
Trang 76
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Title
Author
Subject
Book ID
Chng trnh sau minh ha cch s dng cu trc trn trong C#:
using System;
struct Books
{
Trang 77
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Books Book1;
Books Book2;
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject =
Book2.book_id = 6495700;
Trang 78
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.ReadKey();
}
}
c im ca cu trc trong C#
trn, bn s dng mt cu trc Books n gin. Cc cu trc trong C# l kh khc vi kiu
cu trc truyn thng trong C hoc C++. Cu trc trong C# c cc c im sau:
Trang 79
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 80
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
};
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
Console.ReadKey();
Trang 81
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Enum trong C#
Mt Enumeration (lit k) l mt tp hp cc hng s nguyn c t tn. Mt kiu enum c
khai bo bi s dng t kha enum trong C#.
Cc kiu lit k trong C# l kiu d liu gi tr. Ni cch khc, kiu lit k cha cc gi tr ca n v
khng th k tha hoc khng th truyn tnh k tha.
Ti y,
Mi biu tng trong danh sch lit k ny i din cho mt gi tr integer, biu tng sau c gi tr
ln hn ca biu tng trc. Theo mc nh, gi tr ca biu tng kiu lit k u tin l 0. V
d:
Trang 82
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
V d sau minh ha cch s dng ca bin enum trong C#:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Lp (Class) trong C#
Khi bn nh ngha mt lp (class) trong C#, bn nh ngha mt blueprint cho mt kiu d liu.
iu ny khng thc s nh ngha bt k d liu no, nhng n nh ngha ngha ca tn lp
. Tc l, mt i tng ca lp gm nhng ci g, cc hot ng no c th c thc hin
trn i tng . Cc i tng l instance (s th hin) ca mt lp. Cc phng thc v cc
bin m cu to nn mt lp c gi l cc thnh vin ca lp .
Trang 83
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
Ghi ch:
Trang 84
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// Length of a box
// Breadth of a box
// Height of a box
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box();
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
Trang 85
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
// Length of a box
// Breadth of a box
Trang 86
http://vietjack.com/csharp/index.jsp
private double height;
Copyright vietjack.com
// Height of a box
Trang 87
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
Constructor trong C#
Mt constructor ca mt Class, l mt hm thnh vin c bit ca mt lp, c thc thi bt c
khi no chng ta to cc i tng mi ca lp .
Mt constructor c tn ging nh tn lp v n khng c bt k kiu tr v no. Di y l v d
minh ha khi nim constructor trong C#:
using System;
namespace LineApplication
{
class Line
Trang 88
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
private double length;
// Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}
Trang 89
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// Length of a line
//Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
Trang 90
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.ReadKey();
}
}
}
Destructor trong C#
Mt destructor trong C#, l mt hm thnh vin c bit ca mt lp, c thc thi bt c khi no
mt i tng ca lp thot ra khi phm vi. Mt destructor c tn ging tn lp vi mt du
ng (~) trc v n c th: khng tr v mt gi tr hoc khng nhn bt k tham s no.
Destructor trong C# c th rt hu ch gii phng ti nguyn b nh trc khi thot khi chng
trnh. Destructor khng th b k tha hoc np chng.
V d sau minh ha khi nim v destructor trong C#:
using System;
namespace LineApplication
{
class Line
{
private double length;
public Line()
// Length of a line
// constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}
Trang 91
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 92
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
c khi to bn ngoi hm thnh vin hoc nh ngha lp. Bn cng c th khi to cc bin
static bn trong nh ngha lp.
V d sau minh ha cch s dng ca cc bin static trong C#:
using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Trang 93
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.ReadKey();
}
}
}
Trang 94
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
Trang 95
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
Trang 96
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
Rect.getArea());
Console.ReadKey();
}
}
}
Trang 97
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
length = l;
width = w;
}
Trang 98
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
a k tha trong C#
C# khng h tr a k tha. Tuy nhin, bn c th s dng Interface trin khai a k tha. V
d sau minh ha cch s dng Interface trin khai a k tha trong C#:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
Trang 99
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
Trang 100
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
area = Rect.getArea();
Rect.getArea());
Trang 101
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Np chng hm trong C#
Bn c th c nhiu nh ngha cho cng tn hm trong cng mt phm vi. Cc nh ngha ny ca
hm phi khc nhau: nh kiu v/hoc s tham s trong danh sch tham s. Trong C#, bn khng
th np chng cc khai bo hm m ch khc nhau kiu tr v.
V d sau minh ha cch s dng hm print() in cc kiu d liu khc nhau trong C#:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
Trang 102
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
p.print(500.263);
Trang 103
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Shape
{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
Trang 104
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
Trang 105
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester
{
Trang 106
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
c.CallArea(t);
Console.ReadKey();
}
}
}
Hm trn trin khai ton t cng (+) cho mt lp Box t nh ngha (user-defined). N cng cc
thuc tnh ca hai i tng Box v tr v i tng kt qu Box.
Trang 107
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length;
// Length of a box
// Breadth of a box
// Height of a box
Trang 108
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box();
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Trang 109
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}
Miu t
+, -, !, ~, ++, --
+, -, *, /, %
Trang 110
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
&&, ||
V d
T cc khi nim trn, chng ta k tha v d trn v np chng thm mt s ton t trong C#:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length;
// Length of a box
// Breadth of a box
// Height of a box
Trang 111
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 112
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
status = true;
}
return status;
}
Trang 113
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
return status;
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box();
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Trang 114
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Trang 115
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
if (Box1 != Box2)
Console.WriteLine("Box1 is not equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
Box4 = Box3;
if (Box3 == Box4)
Console.WriteLine("Box3 is equal to Box4");
else
Console.WriteLine("Box3 is not equal to Box4");
Console.ReadKey();
}
}
}
Trang 116
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Interface trong C#
Mt Interface c nh ngha nh l mt giao c c tnh cht c php (syntactical contract) m
tt c lp k tha Interface nn theo. Interface nh ngha phn L g ca giao c v cc lp
k tha nh ngha phn Cch no ca giao c .
Interface nh ngha cc thuc tnh, phng thc v s kin, m l cc thnh vin ca Interface .
Cc Interface ch cha khai bo ca cc thnh vin ny. Vic nh ngha cc thnh vin l trch
nhim ca lp k tha. N thng gip ch trong vic cung cp mt Cu trc chun m cc lp k
tha nn theo.
V d
Sau y l v d minh ha trnh trin khai ca Interface trn:
Trang 117
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication
{
public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}
Trang 118
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 119
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Namespace trong C#
Mt namespace trong C# c thit k cung cp mt cch gi mt tp hp cc tn c
phn bit ring r nhau. Cc tn lp c khai bo trong mt namespace khng xung t vi cng
tn ca lp c khai bo trong namespace khc.
namespace second_space
{
Trang 120
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
Chng ta c th vit tn y l:
System.Console.WriteLine("Hello there");
Trang 121
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace first_space
{
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class efg
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
Trang 122
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace first_space
{
Trang 123
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
namespace second_space
{
class efg
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
Trang 124
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Inside second_space
Ch th tin x l trong C#
Cc ch th tin x l (Preprocessor Directive) cung cp ch lnh ti compiler tin x l thng tin
trc khi s bin dch thc s bt u.
Tt c ch th tin x l trong C# bt u vi #, v ch c cc k t white-space c th xut hin
trc mt ch th tin x l trong mt dng. Cc ch th tin x l trong C# khng l cc lnh, v th
chng khng kt thc vi mt du chm phy (;).
B bin dch ca C# khng c mt b tin x l ring bit, tuy nhin, cc ch th ny c x l nh
khi thc s c mt b tin x l ring vy. Trong C#, cc ch th tin x l c s dng gip
ch vic bin dch c iu kin. Khng ging cc ch th tin x l trong C v C++, chng khng
c s dng to cc macro. Mt ch th tin x l phi ch l mt ch lnh trn mt dng.
Cc ch th tin x l trong C#
Di y l bng lit k cc ch th tin x l c sn trong C#:
Preprocessor
Directive
Miu t
#define
#undef
#if
N cho php kim tra mt biu tng hoc nhiu biu tng thy nu
chng c lng l true
#else
#elif
#endif
Trang 125
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
#line
#error
#warning
#region
#endregion
Trang 126
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
#endif
Console.ReadKey();
}
}
}
Ti y, symbol l tn ca biu tng bn mun kim tra. Bn cng c th s dng true v false
hoc ph thm vo sau biu tng vi ton t ph nh.
operator symbol l ton t c s dng c lng biu tng . Cc ton t c th l mt
trong cc:
== (bng)
!= (khng bng)
&& (v)
|| (hoc)
Trang 127
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
#define DEBUG
#define VC_V10
using System;
public class TestClass
{
public static void Main()
{
#if (DEBUG && !VC_V10)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V10)
Console.WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
Console.WriteLine("DEBUG and VC_V10 are defined");
#else
Console.WriteLine("DEBUG and VC_V10 are not defined");
#endif
Console.ReadKey();
}
}
Character escape
Trang 128
http://vietjack.com/csharp/index.jsp
Lp Character
Anchor
Grouping construct
Quantifier
Backreference construct
Alternation construct
Substitution
Miscellaneous constructs
Copyright vietjack.com
Lp Regex trong C#
Lp Regex trong C# c s dng biu din mt Regular Expression. N c cc phng thc
c s dng ph bin sau:
STT
Phng thc
Trang 129
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d 1
V d sau so khp vi cc t m bt u vi S:
using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
{
Console.WriteLine(m);
}
Trang 130
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d 2
V d sau so khp vi cc t m bt u vi m v kt thc vi e:
using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
Trang 131
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "make maze and manage to measure it";
V d 3
V d sau thay th cc white space:
using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
static void Main(string[] args)
Trang 132
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
string input = "Hello
World
";
try: Mt khi try nhn din mt khi code m cc exception c th c kch hot. N
c theo sau bi mt hoc nhiu khi catch.
Trang 133
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
finally: Mt khi finally c s dng thc thi mt tp hp lnh cho, c hay khng
mt exception c nm hoc khng c nm. V d, nu bn m mt file, n phi c
ng, nu khng s c mt exception c to ra.
C php
Gi s mt khi to mt Exeption, mt phng thc bt mt exception bi s dng kt hp cc t
kha try v catch. Mt khi try/catch c t xung quanh code m c th to mt exception. Code
bn trong mt khi try/catch c xem nh l code c bo v, v c php s dng try/catch
trong C# nh sau:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
Trang 134
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Bn c th lit k nhiu lnh catch bt cc kiu exception khc nhau trong trng hp khi try
ca bn xut hin nhiu hn mt exception trong cc tnh hung khc nhau.
Lp Exception trong C#
Cc Exception trong C# c biu din bi cc lp. Cc lp Exception trong C# ch yu c k
tha mt cch trc tip hoc khng trc tip t lp System.Exception trong C#. Mt s lp
Exception
tha
lp
System.Exception
cc
lpSystem.ApplicationException v System.SystemException.
Lp System.ApplicationException h tr cc exception c to bi cc chng trnh ng
dng. V th, cc exception c nh ngha bi lp trnh vin nn k tha t lp ny.
Lp System.SystemException l lp c s cho tt c system exception tin nh ngha.
Bng
sau
cung
cp
mt
lp
Exception
tin
nh
ngha
tha
Miu t
System.IO.IOException
X l cc I/O error
System.IndexOutOfRangeException
System.ArrayTypeMismatchException
System.NullReferenceException
System.DivideByZeroException
System.InvalidCastException
Trang 135
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
System.OutOfMemoryException
X l li c to t vic thiu b nh ri
System.StackOverflowException
Trang 136
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
Trang 137
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
Trang 138
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Nm cc Object trong C#
Bn c th nm mt i tng nu n: hoc trc tip hoc gin tip c k tha t
lpSystem.Exception trong C#. Bn c th s dng mt lnh throw trong khi catch nm i
tng hin din :
Catch(Exception e)
{
...
Throw e
}
Lp I/O trong C#
System.IO namespace c nhiu lp a dng m c s dng thc hin cc hot ng khc
nhau vi File, nh to v xa file, c v ghi mt File, ng mt File,
Bng sau hin th mt s lp non-abstract c s dng ph bin trong System.IO namespace
trong C#:
I/O Class
Miu t
BinaryReader
BinaryWriter
Trang 139
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
BufferedStream
Directory
DirectoryInfo
DriveInfo
File
FileInfo
FileStream
MemoryStream
Path
StreamReader
c s dng c cc k t t mt stream
StreamWriter
StringReader
StringWriter
Lp FileStream trong C#
Lp FileStream trong System.IO namespace trong C# gip trong vic c t, ghi v ng cc
File. Lp ny k tha t lp abstract l Stream.
Trang 140
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Tham s
Miu t
FileMode
Create: N to mt File mi
FileAccess
FileShare
Trang 141
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
Di y l v d minh ha cch s dng ca lp FileStream trong C#:
using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);
for (int i = 1; i <= 20; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close();
Console.ReadKey();
Trang 142
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
}
Attribute trong C#
Mt attribute trong C#, l mt th tng thut, c s dng truyn thng tin ti runtime v
cc hnh vi ca cc phn t a dng nh cc lp, phng thc, cu trc, enum, assembly,
trong chng trnh ca bn. Bn c th thm thng tin tng thut ti mt chng trnh bi vic
s dng mt Attribute. Mt th tng thut c miu t bi cc du ngoc mc vung ([]) c
t bn trn phn t m n c s dng cho.
Trang 143
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Cc Attribute c s dng thm metadata, v d nh ch lnh bin dch v thng tin khc nh
comment, miu t, phng thc v cc lp ti mt chng trnh. .Net Framework cung cp hai
kiu Attribute: cc Attribute c nh ngha trc v cc Custom Attribute.
Xc nh mt Attribute trong C#
C php xc nh mt Attribute trong C# nh sau:
[attribute(positional_parameters, name_parameter = value, ...)]
element
AttributeUsage
Conditional
Obsolete
AttributeUsage trong C#
Attribute c nh ngha trc AttributeUsage miu t cch mt lp custom Attribute c th
c s dng. N xc nh kiu ca cc item, m t Attribute c th p dng cho.
C php xc nh Attribute ny trong C# nh sau:
[AttributeUsage(
validon,
AllowMultiple=allowmultiple,
Inherited=inherited
)]
Ti y:
Trang 144
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
hp
gi
tr
ca
mt AttributeTargets enumerator.
Gi
tr
mc
nh
lAttributeTargets.All.
Tham s inherited (ty ) cung cp gi tr cho thuc tnh Inherited ca attribute ny, mt gi
tr Boolean. Nu n l true, Attribute c k tha bi cc lp k tha. Gi tr mc nh l
false (khng c k tha).
V d:
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Feild |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
Conditional trong C#
Attribute tin nh ngha ny nh du mt phng thc c iu kin m s thc thi ca n ph
thuc vo mt tin trnh tin x l nh danh cho.
N to s bin dch c iu kin ca cc li gi phng thc, ph thuc vo gi tr cho,
nh Debug hoc Trace. V d: n hin th cc gi tr ca cc bin trong khi debug mt code.
C php xc nh Attribute ny trong C# l nh sau:
[Conditional(
conditionalSymbol
)]
V d:
[Conditional("DEBUG")]
Trang 145
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class Test
{
static void function1()
{
Myclass.Message("In Function 1.");
function2();
}
static void function2()
{
Myclass.Message("In Function 2.");
}
Trang 146
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Obsolete trong C#
Attribute tin nh ngha ny trong C# nh du mt thc th chng trnh m khng nn c s
dng. N cho bn kh nng thng bo cho compiler loi b mt phn t target c th. V d,
khi mt phng thc mi ang c s dng trong mt lp v nu bn vn mun gi li phng
thc c trong lp ny, bn c th nh du n l obsolete bng vic hin th mt thng bo l
phng thc mi nn c s dng, thay cho phng thc c.
C php xc nh Attribute ny trong C# l nh sau:
[Obsolete(
message
)]
[Obsolete(
message,
iserror
)]
Ti y,
Trang 147
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Khi bn c bin dch chng trnh trn, compiler s cho mt thng bo li:
Don't use OldMethod, use NewMethod instead
Bc cui cng lin quan ti vic vit mt chng trnh n gin c qua metadata tm ra
cc notation a dng. Metadata l d liu hoc thng tin c s dng miu t d liu khc.
Trang 148
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Lp DeBugInfo c 3 thuc tnh private lu gi 3 thng tin u tin v mt thuc tnh public
lu gi thng bo . V th, s hiu bug, tn lp trnh vin, v ngy review l cc tham s v tr
tng ng ca lp DeBugInfo v thng bo l mt tham s ty .
Mi Attribute phi c t nht mt constructor. Cc tham s v tr tng ng nn c truyn thng
qua constructor . V d sau minh ha lp DeBugInfo trn:
//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(AttributeTargets.Class |
Trang 149
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
Trang 150
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
Trang 151
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trong chng ti, chng ta thu hi thng tin Attribute bi s dng mt i tng lp Reflection
trong C#.
Reflection trong C#
Cc i tng Reflection c s dng thu c thng tin kiu ti runtime. Cc lp ny cung
cp truy cp ti metadata ca mt chng trnh ang chy l trongSystem.Reflection namespace
trong C#.
System.Reflection namespace trong C# cha cc lp m cho php bn thu c thng tin v
ng dng v thm cc kiu, gi tr, v cc i tng mt cch ng ti Application.
Cc ng dng ca Reflection
Reflection c cc ng dng sau:
Trang 152
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
N cho php thm tra cc kiu a dng trong mt Assembly v thuyt minh cc kiu ny.
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
{
get
{
return topic;
}
set
{
topic = value;
Trang 153
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
{
this.Url = url;
}
private string topic;
}
Console.ReadKey();
}
}
}
Trang 154
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d
Trong v d ny, chng ta s dng attribute l DeBugInfo c to trong chng trc v s dng
Reflection c metadata trong Rectangle class.
using System;
using System.Reflection;
namespace BugFixApplication
{
//a custom attribute BugFix to be
//assigned to a class and its members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
Trang 155
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
this.lastReview = d;
}
Trang 156
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
set
{
message = value;
}
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
public double GetArea()
{
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
Trang 157
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);
Trang 158
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
}
Console.ReadLine();
}
}
}
Trang 159
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Accessor trong C#
Trong C#, accessor l mt thuc tnh cha cc lnh c th thc thi, m gip trong vicly (c
hoc tnh ton) hoc thit lp (ghi) thuc tnh. Cc khai bo accessor c th thu c mt get
accessor, mt set accessor, hoc c hai. V d:
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
Trang 160
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
name = value;
}
}
V d
V d di y minh ha cch s dng ca cc thuc tnh trong C#:
using System;
namespace tutorialspoint
{
class Student
{
private string code = "N.A";
private string name = "not known";
private int age = 0;
Trang 161
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
return code;
}
set
{
code = value;
}
}
Trang 162
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class ExampleDemo
{
public static void Main()
{
Trang 163
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 164
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
return code;
}
set
{
code = value;
}
}
Trang 165
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
class ExampleDemo
{
public static void Main()
{
// Create a new Student object:
Student s = new Student();
Indexer trong C#
http://vietjack.com/ Trang chia s cc bi hc online min ph
Trang 166
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
C php
Mt Indexer mt chiu c c php nh sau trong C#:
element-type this[int index]
{
// The get accessor.
get
{
// return the value specified by index
}
Trang 167
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
Trang 168
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namelist[index] = value;
}
}
}
Console.ReadKey();
}
}
}
Trang 169
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
N. A.
N. A.
Trang 170
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
Trang 171
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 172
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
N. A.
N. A.
2
Delegate trong C#
Delegate trong C# l tng t nh con tr ti cc hm, trong C hoc trong C++. MtDelegate l
mt bin kiu tham chiu m gi tham chiu ti mt phng thc. Tham chiu c th c
thay i ti runtime.
c bit, cc delegate c s dng trin khai cc s kin v cc phng thc call-back. Tt
c delegate c k tha mt cch ngm nh t lp System.Delegate trong C#.
Trang 173
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d sau minh ha cch khai bo, thuyt minh v s dng mt delegate m c th c s dng
tham chiu cc phng thc m nhn mt tham s integer v tr v mt gi tr integer.
using System;
Trang 174
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 175
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
num += p;
return num;
}
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
Trang 176
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Value of Num: 75
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
Trang 177
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
Trang 178
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Tip theo, chnh Event c khai bo, bi s dng t kha event trong C#:
//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
V d 1
using System;
namespace SimpleEvent
{
using System;
Trang 179
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
public EventTest(int n )
{
SetValue(n);
}
Trang 180
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
{
EventTest e = new EventTest(5);
e.SetValue(7);
e.SetValue(11);
Console.ReadKey();
}
}
}
V d 2
V d ny cung cp mt application n gin x l s c cho mt h thng ni hn un nc
nng. Khi k s bo dng kim tra ni hi, nhit v p sut ni hi c t ng ghi li vo
trong mt log file cng vi cc ghi ch ca k s bo dng ny.
using System;
using System.IO;
namespace BoilerEventAppl
{
// boiler class
class Boiler
{
private int temp;
private int pressure;
public Boiler(int t, int p)
{
temp = t;
pressure = p;
}
Trang 181
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// event publisher
class DelegateBoilerEvent
{
public delegate void BoilerLogHandler(string status);
Trang 182
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
// this class keeps a provision for writing into the log file
class BoilerInfoLogger
{
FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
}
Trang 183
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}//end of RecordBoilerInfo
}
Temperature 100
Pressure 12
Message: O. K
Trang 184
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Collection trong C#
Cc lp Collection l cc lp c bit lu gi v thu hi d liu. Nhng lp ny cung cp s h
tr cho Stack, Queue, List, v Hash Table. a s cc lp Collection trong C# trin khai cng cc
Interface.
Trong C#, cc lp Collection phc v cc mc ch a dng, chng hn nh cp pht b nh ng
cho cc phn t v truy cp mt danh sch cc item da trn mt ch mc, Nhng lp ny to
tp hp cc i tng ca lp Object, m l lp c s cho tt c kiu d liu trong C#.
Ghi ch: Stack: ngn xp, push: thm nt mi vo nh stack, pop: thao tc ly 1 phn t t nh
stack.
ArrayList trong C#
Hashtable trong C#
Trang 185
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
SortedList trong C#
Stack trong C#
Queue trong C#
BitArray trong C#
Generic trong C#
http://vietjack.com/ Trang chia s cc bi hc online min ph
Trang 186
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace GenericApplication
{
public class MyGenericArray<T>
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
Trang 187
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
array[index] = value;
}
}
class Tester
{
static void Main(string[] args)
{
//setting values
for (int c = 0; c < 5; c++)
{
intArray.setItem(c, c*5);
}
Console.WriteLine();
//setting values
for (int c = 0; c < 5; c++)
{
charArray.setItem(c, (char)(c+97));
Trang 188
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.ReadKey();
}
}
}
c im ca Generic trong C#
Generic l mt k thut lm cho chng trnh C# ca bn phong ph hn theo cc cch sau:
lp
generic
collection
ny
thay
cho
cc
lp
collection
trongSystem.Collections namespace.
Bn c th to cho ring mnh cc Class, Interface, phng thc, Event v Delegate dng
generic.
Trang 189
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace GenericMethodAppl
{
class Program
{
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
Trang 190
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
//call swap
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);
Console.ReadKey();
}
}
}
Trang 191
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace GenericDelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
Trang 192
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
}
Khi Console.WriteLine("Anonymous Method: {0}", x); l phn thn ca phng thc nc danh.
Delegate c th c gi c vi cc phng thc nc danh cng nh cc phng thc c t
tn theo cng cch, v d: bng vic truyn cc tham s phng thc ti i tng Delegate .
Trang 193
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
V d:
nc(10);
V d
Di y l v d minh ha khi nim trn:
using System;
Trang 194
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
new NumberChanger(AddNum);
new NumberChanger(MultNum);
Trang 195
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
*ip;
/* pointer to an integer */
double *dp;
/* pointer to a double */
float
*fp;
/* pointer to a float */
char
*ch
/* pointer to a character */
V d sau minh ha s s dng ca con tr, s dng unsafe modifier trong C#:
using System;
namespace UnsafeCodeApplication
{
class Program
{
static unsafe void Main(string[] args)
{
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} ",
var);
(int)p);
Console.ReadKey();
}
}
Trang 196
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Thay cho vic khai bo ton b phng thc dng unsafe, bn cng c th khai bo mt phn
code dng unsafe.
Console.ReadKey();
}
}
}
Trang 197
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Data is: 20
Data is: 20
Address is: 77128984
Trang 198
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
}
}
}
Trang 199
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Console.ReadKey();
}
}
}
Nu bn ang s dng Visual Studio IDE, bn cn kch hot s s dng ca unsafe code trong
project properties.
lm iu ny:
M project properties bng vic nhn p chut vo properties node trong Solution
Explorer.
Nh trong nh nh sau:
Trang 200
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Trang 201
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Unstarted State: N l tnh hung khi instance ca Thread c to, nhng phng thc
Start cha c gi.
Ready State: N l tnh hung khi Thread sn sng chy v i CPU cycle.
Not Runnable State: Mt Thread l khng th thc thi (not executable), khi:
Dead State: N l tnh hung khi Thread hon thnh s thc thi hoc b hy b.
namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Trang 202
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Miu t
CurrentContext
CurrentCulture
CurrentPrinciple
CurrentThread
CurrentUICulture
ExecutionContext
IsAlive
IsBackground
Trang 203
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Background Thread
IsThreadPoolThread
ManagedThreadId
Name
Priority
ThreadState
Bng ny lit k cc phng thc c s dng ph bin nht ca lp Thread trong C#:
STT
Phng thc
Trang 204
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
10
11
Trang 205
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
12
13
14
15
16
17
18
Trang 206
http://vietjack.com/csharp/index.jsp
19
Copyright vietjack.com
20
21
22
23
Trang 207
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
To Thread trong C#
Trong C#, cc Thread c to bng vic k tha lp Thread. Sau , Lp Thread c k tha
gi phng thc Start() bt u s thc thi ca Thread con.
Sau y l v d minh ha vic to Thread trong C#:
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
}
Trang 208
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
Trang 209
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Hy Thread trong C#
Phng thc Abort() c s dng hy cc Thread trong C#.
Trong thi gian runtime, chng trnh hy b Thread bng vic nm mtThreadAbortException.
Exception ny khng th c bt, iu khin c gi ti khifinally, nu l khng.
Di y l chng trnh minh ha vic s dng phng thc Abort() hy b cc Thread trong
C#:
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{
Console.WriteLine("Child thread starts");
Trang 210
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
catch (ThreadAbortException e)
{
Console.WriteLine("Thread Abort Exception");
}
finally
{
Console.WriteLine("Couldn't catch the Thread Exception");
}
}
childThread.Abort();
Console.ReadKey();
}
}
}
Trang 211
http://vietjack.com/csharp/index.jsp
Copyright vietjack.com
Link hu ch v C#
Trang 212