You are on page 1of 270

. .

C#

-
2007

32.973.26-018.1
. .
C# - .: -, 2007. - 272 .
ISBN 5-91136-023-3

#.
, ,
. , ,
,
, , , ,
,
Microsoft NET Framework.

.
- . . . ", ", , 2006.
C#
Microsoft NET Framework Windows.
Windows
.
Microsoft Visual
C# NET (2003) Microsoft Visual C# NET (2005),
.


C#
-

. .

-
190068, .-, -, . 55,
, . 44
. (495) 333-82-11. ok@kudits.ru. http://books.kudits.ru

1.08.2007 .
70x90/16. . . .
. . . 19,89. 2000. 1428


117623, , . , . 10
. 659-23-27.

ISBN 5-91136-023-3

, -, 2007
. ., 2007

I.
C # .................................. 7
1.
C#................................. 7
1.1.
C #........................................................................................................... 7
1.2. Micorosft Visual C# NET (2003)
Windows.........................12
1.3.
. ........................... 18
1.4. .
......................................................................................22
1.5.
/..............................................................................32
1.6. ( )
ref out......................................40

2.
C# ................................. 46
2.1.
................................................................................. 46
2.2.
................ ;..........................................................................49
2.3. : ................................................ 55
2.4. : ........................... 60

3.
C# ............................. 65
3.1.
, ......................................................................... 65
3.2. C # .........................................69
3.3. .......................................................................... 74
3.4. C#...................................78
3.5. ...................................................... 81

4.
C# ................................ 87
4.1. char UNICODE-........... 87
4.2. char C #............................................................ 92
4.3. ...................................................... 99
4.4. C #..............................................................................104
4.5. ................................................... 107

II.
- C#
Microsoft NET Fram ew ork...........................I l l
5.
#: , ,
, .......................................................................111
5.1. C#
......................................................... 111
5.2. :
............................................................................... 116
5.3. :
............................................................ 124
5.4. FCL.
MyComplex....................................................130

6.
. .
........................................................... 137
6.1.
6.2.
6.3.
6.4.
6.5.

................................................................... 137
: , , .................................140
IComparable................................145
........................................149
................................................................. 154

7.
....................................162
7.1. . / .
/ .....................................................................................162
7.2. ......................................................... 170
7.3. ........................................................ 177
7.4. - ................ 182

III.
Windows-

Microsoft NET Framework...............................................186
8.
Windows
....................................................186
8.1. Win32 Application
C/C++............................................................................................... 186
8.2.
C/C++......................... 193
8.3.
C # ............................................................................... 197
8.4. Windows-
Microsoft Visual C#..............................210

9.

.......................................................
9.1. ............................................
9.2. ....................................
9.3. .................
9.4. ..............................................
9.5.
.....................................

.
Microsoft Developer Studio NET (2003)
Microsoft Visual C# NET (2003)
Microsoft Visual C++ NET (2003)........................................
Microsoft Visual C# NET (2003)...............................
Microsoft Visual C++NET (2003).............................

.................................................................

I

C#
1.


C#

1.1.
C#
[1], ,
,
,
.
.
( #,
- Microsoft Visual C# Windows),
.
, . () x l , 2
. . , ,
, .
.
, :

re s = ( x l + 2 + ) / 3
{)
res. , .

#:

1
double r e s , x l , x2 , x 3 ;
xl = 4.5; x2 = 5.6; x3 = 7.8;
res = ( xl + x2 + x3 ) / 3 ;



.
#, C/C++,
.
, .
C# - ,
C#
( - IL, Intermediate Lan
guage),
, (
, ,
). , ,
- PE-,
CLR (Common Language Runtime) Mi
crosoft NET Framework.
. .
-,
#, .
(, ,
). - : , . , . + - (
), / , = - .
,
( ) -,

( ). x l
4 . 5 { ),
- 2 5 . 6 . .
.
: #, ,
- C/C++,
, -

C#

x l + 2, ,
.
, , .
C#
.
, =,
,
.
,
.
, ,
.
, - x l , 2 double. d o u b le -
,
. -
( , ,
) ,
.
.
C/C++, C#
.
{
) double. C# (
) .
:
? , ,
#.
-, C#
Main ( ),
:
int Main( )

{
double res, xl, x2, x3;
xl = 4.5; x2 = 5.6; x3 = 7.8;
res = ( xl + x2 + x3 ) / 3;
return 0;
}

10

______________________________________________________________________ 1

- Main,
, .
Main,
, return
(
). Main int (
#),
, (),
,
Main ,
.
: #, C/C++,
void .
, :
C# ,
(
- ) ,
:
1.1.
class main

{
public static int Main( )

{
double res, x l , x2 , x 3 ;
xl = 4.5; x2 = 5.6; x3 = 7.8;
res = ( xl + x2 + x3 ) / 3;
return 0;

}
}
, Main
, , , main.

Main ( ) public static. ,
( Main
), -
,
, .

C#

11

1.1 #.
, , ,
, !
1.1 -,
, ,
. .
. , ,
.
. ,
(- 1.1),
, .
C# ,
. :
class main{public static int Main(){double
res, xl, x2,
x3;xl
=4.5;x2=5.6;x3=7.8;res =

(
xl
+ x2 + x3 ) / 3;return
0;
}}

1.1,
.
( ). : -
, : ,
,
.
: - .
#,
, ,
(
).
/ / , (
)
/* * /:
class main

{
public static int Main( )

12

{
// :
double res, xl, 2, ;
/*- -*/
xl = 4.5; 2 = 5.6; = 7.8;
res = ( xl + 2 + ) / 3;

/ * ------------------------------------------------- */

return 0;

}
}
,

,
x l , 2 . , 1.1 .
, ,
- . ,
,
.
[1],
,
, Microsoft NET Framework
Windows 2000, Windows (
Windows),
,
, Microsoft Visual #.

1.2. Micorosft Visual C# NET


(2003)
Windows
Microsoft Visual C# NET (2003)
.
, File | New |
Project... New Project (. . 1.1).
Visual C# Project,
- Empty Project. Name
( Proj 1), -

C#

13

New Project

xj

Project Types:

Templates:

1 Visual Basic Projects


Visual C# Projects
_ 3 Visual J# Projects
- J Visual C ++ Projects
__3 5etup and Deployment Projects
+ __j Other Projects
1 Visual Studio Solutions

^ ASP.NET Web Application


f | ASP.NET Web Service
ASP.NET Mobile Web Application
*5*3 Web Control Library
Lj|f Console Application
iWindows Service
ZE Empty Project
Empty Web Project
fjN e w Project In Existing Folder

An empty project fo r creating a local applicaton


Name:

] P rojl

Location:

I E:\BOOKSl,KUDITS\C#Book\T ests

zl

Browse..

Project will be created at E:\BOOKS\KUDIT5\C#Book\Tests\Projl.

^More

OK

Cancel

Help

.1.1.

Location (, , Browse...)
, .
- .

Projl, ,
, . 1.2.
1.1.
Project | Add New Item...
Microsoft Visual #,
(. . 1.3).
Code File, Name main.cs (
cs Sharp -
C# Microsoft), Open
(. . 1.4).
, . 1.4 , Projl
(
Projl.sin Projl.csproj)
main.cs. 1.1

14

File

View

Edit

Favorites
I .

Address |

1J p
a-

Help

Search

Folders

E:\BOOKS\KUDITS\C#8ook\Tests\Projl

"3 J

^bin
^obj

Folders
Q

Tools

Tests

Go

^ P r o jl. s ln
Pro] 1. suo

^ lP ro jt.c s p ro j
^ P ro jl.c s p ro j.u s e r

L)\
bin

iL

il_________ I

!6 objects (Disk free space: 4.85 GB) 11.8 KB

[ My Computer

. 1.2.

2Ll

Add New Item - Projl


lem plates:

Categories:
^

Name:

Local Project Items

] Windows Form
Class
Component Class
3 User Control
^ D a t a Form Wi2ard
Data Set
te*) XML File
XML Schema
Code File
jjJ Custom Control
_$]HTML Page
^ In h e r ite d Form
jj W e b Custom Control

j^main.
Open

Cancel

Help

.1.3.

Microsoft Visual #,
(. . 1.5).

C#

Edit

View

Back -

' -

Address

Favorites

lools

z l 0

0. j

S i P ro jl. sin
Projl,suo

J )o b \

f^m a in .cs
j
j r j JlP rojl.csproj

-
FI C ^ tu n

i S

^ P ro jl.c s p ro j.u s e r >

X j CD bin
Tests

Folders j

E:\BOOKS\KUDITS\C#Book\Tests\Projl

I Folders
El

Help

Search

-| |

k \T e s ts \P ro J I

I % E :\B O O K S\IC U O IT S \ C # f k
| File

15

_
.
i
> n
il7 objects (Disk free space: 4.85 GB) 11.8 KB

J j
J My Compute.

. 1.4.
[

P ro jl - M icrosoft Visual C # NET [design] - [m a m x s ]


File

Edit

View

Project
-#

1Solution Explorer - Proj 1

Butld

Debug

Debug
4- _ x j

^ Solution P ro jl (1 project)
Ip l P ro jl
Q3 References
J ] mafri.es

Tools

Window

Help

- 9 X

- '

I I f ma,n
c l a s s w a in
{
p u b lic s t a t i c

z l

! * ^

i n t M a in t)

<
d o u b le

re s ,

x l,

x2,

x3;

/ * -----------------------------------------------------------* /
x l = 4 . 5 ; x2 - 5 . 6 ; x3 = 7 . 8 ;
r e s = ( x l + x2 + x3 ) / 3 ;
/ * -----------------------------------------------------------V
re tu rn

3 s o l... ^ C la ...|
Ready

>

0;

zJ
1
In 1

> r
Col 1

C hi

__ j INS

. 1.5.

Microsoft Visual C# NET


, C#
.
. Build | Build Solution.

16

( ,
, )
,
(. . 1.6).
JS Jx j

P ro jl - Microsoft; Visual C # .NET [design] - [m a ln .c s *]


File

Edit

View

Project

.Jp

1.*

[solution Explorer-P ro jl

3 ,U
a

Debug

Debug

lools

Window

Help

9 "x ]

class m a i n

P ro ji
References
2 main.cs

<1

Build

lli

public static int Haint)

i
double res, xl,

______________ I

x2,

x3;

B u ild s t a r t e d : P r o j e c t : P r o j l , C o n fig u r a tio n : Debug .NET

LlL
0 Task List
[R e a dy

Output |
Ln 17

C o ll

C hi

. 1.6.


( Output)
(0 errors),
( warnings). , C#
Projl.exe.
Debug

Windows .
C#
Microsoft Visual C# F5. ,

( Debug),
(. . 1.6)
Project: Projl, Configuration: Debug .NET

C#

17

Debug,
.


. ,
( ,
Release
).
F5 (Debug)

.
, F9
(
), ,
(. . 1.7).
P ro jl
File

Edit
12?

II

-jn jx |
_ X

M icrdsoft Visual C # NET [b r e a k ] - [m aM :s]

View Project

&

Build

Debug

Debug

' **5 C = ^ 5

Tools

Window

Help

Hex

4 - ,

p " Locals

Build succeteded

Ln 10

Col 5

Ch 2

INS

. 1.7.

,
,
. , . 1.7
r e s . .

18

_____________________________________________________________________ 1

#,
F10, ,
.

F5.

1.3.
.
.
(.
[1]). ,
, ,
, . ,

.
, #,
C/C++, .

Main 1.1
Aver:
1.2.
class main

{
// :
public static int Main()

{
double res, xl, x2, x3;
xl = 4.5; x2 = 5.6; x3 = 7.8;
res = Aver( xl, x2, x3 ) ;
return 0;
}

//
// :
static double Aver( double x, double y, double z )
{

return ( x + + z ) / 3;
}

C#

19

1.2 Main
Aver,
,
.

Main
Aver:

re s = A ver( x l , x2, x3 ) ;
x l, 2 d o u b le . ,
A ver , z
( ).
1.2 ,

(. [1]) #. , [1],
, ,
Main ( ) , A ver () .
, #, -
, ( -
, ):
, 1.2 A v er ()
s t a t i c , ( ),
( . . 2).
, C#

, .

() ,
, ( 1.2). ,

(. . 7 [1]),
- C# ,
.
- C#
, , -
, , .

20

#,

- .
, C#
(, ) (. . 2
[1]). , MySum() 2.9 . 2.6
[1], , #-
:
1.3.

c la s s main
{
/ * ---------------------------------------------------------------*/
static int MySum( int M, int N )i /*1*/
/*2*/
{
/*3*/
int i, Sum;
i = M; Sum = 0;
/*4* /
/* 5* /
/*6*/
while( i <= N )
/*7*/
{
Sum = Sum + i ;
/*8*/
/*9*/
i ++ ;
/*10*/
}
/*11*/
/*12*/
return Sum;
/*13*/
}
/*---------------------/*14*/
public static int Main( )
/*15*/
{
/*16*/
int i, N, Sum;
/*17*/
i = 137; N = 895;
/*18*/
/*19*/
Sum = MySum( i , N );
/*20*/
Sum = MySum( 5, 555 );
/*21*/
Sum = MySum( Sum, Sum + 1 ) ;
/*22*/
Sum = MySum ( N, N+3 ) + 4;
/*23*/
MySum( 11, 123 );
/*24*/
/*27*/
retuirn 0;
/*28*/
}

, ----------------------------------------

C#

21

, while,
1.3 / * 6 * /- / * 1 0 * /.

( ), MySum ()
, :

s t a t i c i n t MySum( i n t M, i n t N )
{
i n t i , Sum;
fo r( i .= M, Sum = 0; i <= N; i ++
{

Sum = Sum + i ;

/* !* /
/* 2 * /
/*3*/
/*4*/
/*5*/
/* 6 * /
/*7*/

/*8* /

re tu r n Sum;

/*9*/
/* 1 0 * /
/* 1 1 * /

/ * 3 * / - / * 6 * /
for, - fo r.
, , C#
.
, i f e l s e (. . 2 [1]).
, . ,
#, C/C++, ,
(- , , i+ +, Sum++),
for
( )
. C# C/C++
, f o r C#

, - ,
( , ).
,
C/C++.
f o r
w h ile . , ,
()
/ .
C/C++

22

_____________________________________________________________________ 1

. C# ,
,
( ,
bool - true
false).
C# , C/C++ (
==, !=, <, <=, >, >=). /
C++, I, && | | (. . 2.3 [1])
#,
&, | ,
.
#,
, C/C++ C#
, -
( ) , , ,
i = i + 1 : i += 1, : i + + (.
/* 9 * / 1.3).

1.4. .


, 1.3
MySum ( ) , ,
,
, , , MyCalc.
1.3 (
):
1.4.
/*---File main.es
class main

----

public static int Main( )


{

int i, N, Sum;
i = 137; N = 895;
Sum = MyCalc.MySum( i, N );
Sum = MyCalc.MySum( 5, 555 );

C#

23

Sum = MyCalc.MySum( Sum, Sum + 1 );


Sum = MyCalc.MySum( N, N+3 ) + 4;
MyCalc.MySum( 11, 123 );
return 0;
}
}

class MyCalc
{

public static int MySum( int M, int N )


{

int i, Sum;
i = M; Sum = 0;
while( i <= N )
{

Sum = Sum + i;
i++;
}

return Sum;
}
}

1.3 MyCalc
MySum() p u b lic ,
MyCalc, Main ()
main.
, ,
- .
C# ( C++) ,
( static)
, MyCalc .MySum()
1.4, .
,
- main.cs.
,
.
( , , ),

.
.

24

( - - 1.4):
1.5.
/*---File main.cs
class main

---- */

public static int Main( )


{

int i, N, Sum;
i = 137; N = 895;
Sum = MyCalc.MySum(i,
N );
Sum = MyCalc.MySum( 5, 555 );
Sum = MyCalc.MySum( Sum, Sum + 1 );
Sum = MyCalc.MySum(N,
N+3 ) + 4;
MyCalc.MySum( 11, 123 );
return 0;
}
}

File MyCalc.cs
/*---class MyCalc

---- */

public static int MySum( int M, int N )


{

int i, Sum;
i = M; Sum = 0;
while( i <= N )
{

Sum = Sum + i;
i++;
}

return Sum;
}
}

Project | Add New Item...


Microsoft Visual C# MyCalc.cs,
M yCalc (
MyCalc.cs). 1.5

C#

25

/ * ---- F i l e m a i n . c s -------* / / * -----F i l e M y C a l c .c s -------* /.


Mi
crosoft Visual C# (. . 1.8).
Pro j4 - M icrosoft Visual C # / [d e s ig n ] - [M yCoh cs]

/> File

Edit

_Jp ^ &

View

&

Solution Explorer -

Pro]ect

4 Solution 'Pro)4' (1 project)


- i p l P ro j4
References

My Calc, cs

Debug

Debug

j.a

Build

Tools

Window

_ X

Help

F MySum(int M/nt M)

c l a s s MyCalc

{
publ i c s t atic

int MySum(

int M,

int N J

{
mt

i, Sum;

i = K;

Sura = 0;

w h i l e ( i <=* N )

{
S u m =* S u m + i;
i++;

}
r e t u r n Sum;

9 Re--- 5 5c'--
Ready

2 6

x :

. 1.8.

. 1.8 , Proj4
- main.cs MyCalc.cs. MyCalc.cs
. 1.8, (
) .
, -
Build | Build Solution,
Proj4.exe.
,
.
,

.

26

namespace.
,
,

.
1.6.
File main.es
/*---using MyCalcClasses;

---- */

class main
{

public static int Main( )


{

int i, N, Sum;
i = 137; N = 895;
Sum = MyCalc.MySum(
Sum = MyCalc.MySum(
Sum = MyCalc.MySum(
Sum = MyCalc.MySum(
MyCalc.MySum( 11, 123 );

i,
N );
5,
555 );
Sum, Sum+
1 );
N,
N+3 )+ 4;

return 0;
}
}

/*---File MyCalc.cs
namespace MyCalcClasses

---- */

class MyCalc
{

public static int MySum( int M, int N )


{

int i, Sum;
i = M ; Sum = 0;
while( i <= N )
{

Sum = Sum + i;
i++;
}

return Sum;
}
}
}

C#

27

1.6 , MyCalc
M yC alcC lasses. M yC alcC lass
e s M y C alcC lasses .MyCalc,
MySum ( ) M y C alcC lasses .MyCalc . MySum (}.
, ,

, (
) ()
.
,
using MyCalcClasses;


, .
main.cs 1.6.
MyCalc
, ,

/*---File MyCalc.cs ---- */
namespace MyCalcClassesOut
{

namespace MyCalcClassesInner
{

class MyCalc
{

public static int MySum( int M, int N )


{

int i, Sum;
i = M; Sum = 0;
while( i <= N )
{

Sum = Sum + i ;
i++;
}

return Sum;
}
}
}
}

28

main.cs ( ) MySum ()
MyCalcClassesOut .MyCalcClassesInner.MyCalc.MySum(),

using MyCalcClassesOut.MyCalcClassesInner;

MyCalc . MySum ().


,
, ,
Microsoft NET Frame
work.
, ,
cs-,
(
- ),
,
.

( dll).

MyCalc.cs 1.6
.
Proj4 (. . 1.8) main.cs
Proj4.exe ( CLR ).
MyCalcClasses, Class Library (. . 1.9).
Microsoft Visual C#
( )
(. . 1.10).
, ,
()
, . 1.10, Delete. ,
, ,
: .
: ,
p u b l i c .
MyCalc.cs
1.6,
public class MyCalc

C#

29

New Project
Templates:

Project Types:

.7*] Windows Application


j? lc ia s s Library
gjif] Windows Control Library
c^S m a rt Device Application
A5P.NET Web Application
f k A5P.NET Web Service
g f ASP.NET Mobile Web Application
]W e b Control Lforary
3 Console Application

1 Visual Basic Projects


Visual C # Projects
Visual J# Projects
f+J
Visual C ++ Projects
I Setup and Deployment Projects
S Q Other Projects
__3 Visual Studio Solutions

zi

A project fo r creating classes to use in other applications

jMyCalcClasses

Name:

E: \BOOKS\KUDITS\C#Book\T ests

Location:

Browse..

Project will be created at E:\BOOK5\KUDIT5\C#8ook\Tests\MyCalcClasses


Cancel

OK

TM ore

Help

. 1.9.

iDlxl

MyCalcClasses - Wrmsoft Visual C# JNET [ck^km] - [C lassic*]

*jO File

dit

- Q&

View

Project

Build

Debug

Solution Explorer * MyCalc... x

|^ i

3 3 j

Ready

. 1.10.

lo o ls

Window

Help

&

- 3 ^ 3 * 5 1 - ?

IdcClasr .Cla

| 1

u s in g S y stem ;

^ Solution 'MyCalcClasses' (1 proje


4 ^ MyCalcClasses
(3 ^ References
* Q System
O System.Data
<3 System.XML
3 AssembtyInfo.es

iL

Debug

Sol... JWCla... iL

nam esp ace M y C a lcC la sses

///

- sumr ar*.
Summary d e s c r i p t i o n f o r C l a s s l .

// i Vsximmary
p u b lic c l a s s C la s s l

{
p u b lic C la s s l( )

>16

30

MyCalc public,
Build | Build Solution
MyCalcClasses. dll.
MyCalc
MyCalc.cs. Proj5
Empty Project main.cs :
/*---File main.es
using MyCalcClasses;

---- */

class main
{

public static int Main( )


{

int i = 137, N = 895, Sum;


Sum = MyCalc.MySum( i, N );
return 0;
}
}


:
:\BOOKS\KUDITS\C#Book\Tests\Proj5\main.cs(1): The type or
namespace name 'MyCalcClasses' could not be found (are you
missing a using directive or an assembly reference?)

, M y C alcC lasses Proj5


.
:
References
Microsoft Visual C#
Add Reference..., (. . 1.11).
Browse...
MyCalcClasses.dll,
,
. 1.11. Proj5
M y C alcC lasses (. . 1.12).
Proj5 . ,
(reference)
MyCalcClasses.dll
( ),

C#

31

Microsoft Visual C#
.
Add R e feren ce

x||

.NET | COM

Projects |
Browse..

Project Name

I Project Directory

Selected Components:

. . I Type

Com; onent Name

Source

I '

OK

Remove

Help

Cancel

. 1 .11 .
Ci ProjS - M icrosoft Visual C # -NET [d* ] - [m<*r>.cs]
r&

File

Edit

L=j] -

View
@

Project

Debug

Debug

Solution Explorer - ProjS


3

Build

^ X 1

Help

-|Ol x|

&

(3

zJ

I us m g

J p Pr!5

^ < 3 MyCalcClasses
FI main.cs

Window

U f .

Solution 'ProjS' (1 project)


a

lo o ls

H y C a lcClasses;

class m a i n

{
publ i c stat i c

{
int i

int H a m (

137, N -

895,

S u m - HyC a l c . H y Sumt

i,

Sum;

N );

r e t u r n 0;

0 lR e s . . .
Task List Ready

. 1.12.

1
1Build Error task shown (filtered)
d

Solu... 1

Clas... 1

........ ........J
______if_______....

^ r1
xl

32

|_____________________________________________________________________ 1

1.5.
/

Microsoft Visual C#
,
.
C# tfem .
Console,
Microsoft NET Framework. Framework
Class Library, FCL.
. FCL
dll-,
\Windows\Microsoft.NET\Framework.
, FCL
Microsoft NET Framework.


Windows.
FCL Console,
( s t a t i c ) R e a d L in e O W r ite L in e O

.
Console
, s c a n f ()
p r i n t f () (. . 2 [1]).
1.1 x l , 2
,
r e s ,
. , C o n s o le S ystem .
1.7.
using System;
class main
{

public static int Main()


{

double res, xl, x2, x3;

C#

33

//
// :
Console.WriteLine( "Enter 3 numbers:" );
xl = Convert.ToDouble( Console.ReadLine() );
x2 = Convert.ToDouble( Console.ReadLine() );
x3 = Convert.ToDouble( Console.ReadLine() );
//
// :
res = ( xl + 2 + ) / 3;
Console.WriteLine( "Average value = {0}", res );
// :
Console.WriteLine( "Press Enter to exit" );
Console.ReadLine() ;
return 0;
}
}

1.7 , ,
,
, . 1.13 ,
Enter 3 numbers:
1,2 3 (
Enter).
.
Enter
, Press Enter to exit.


.
i

. 1.13.

34

1.7.
S ystem ,
using System;

/
Console . WriteLine ()
. ,
Console.WriteLine( "Enter 3 numbers:" );

( ,
, )
. Wri teLine ()
Console.WriteLine( "Average value = {0}", res );

, ,
res,
{placeholder), {0 }.
, (
W r i t e L i n eO) ,
,
WriteLineO. ,

double = 0, yl = 1, 2 = 2;
Console.WriteLine("First {2} Second {1} Third {0}", yO, yl, y2);

:
First 2 Second 1 Third 0

{2} 2,
( )
W ri t e L i n e () .
, WriteLineO
C o n s o le p r i n t f ()
(. . 1 [1]), ,
, %Lf, %d . ,
,
\ ,
.

C#

35

,
R eadL ine ( ) , ,
- s c a n f ( ) ,
.
() ,
d o u b le . , S y s
tem C o n v ert,
C# .

xl = Convert.ToDouble( Console.ReadLine() );

ToDouble () C o n v e rt (
)
( R eadL ine () C o n so le )
d o u b le.
x l.
Enter,
1.7
// :
Console.WriteLine( "Press Enter to exit" );

,
,
r e t u r n 0; Main ().
,
Console /. -,

( References )
, System (.
), . , , dll-
(header files),
,
# i n c l u d e
- C#
() .
,
Math
System. #,

36

_____________________________________________________________________ 1

,
2.4 . 2 [1] :
1.8.
using System;
class main
{

public static int Main( )


{

double , , , D, xl, x2 ;
Console.WriteLine( "Enter A, and C: " );
A = Convert.ToDouble( Console.ReadLine() )
- Convert.ToDouble( Console.ReadLine() )
= Convert.ToDouble( Console.ReadLine() )
D = B * B - 4 * A * C ;
if ( D >= 0

ScSc

A != 0 )

xl = ( -B + Math.Sqrt(D) )/(2*A);
x2 = ( -B - Math.Sqrt(D) )/(2*A);
Console.WriteLine( "xl = {0} x2 = {1}", xl, x2 );
}

else
{

Console.WriteLine( "Cant solve equation" );


}

Console.ReadLine();
return 0;
}

1.8 , s q r t ()
, S q r t ()
Math.

C#

37


(. . 1.14), . 2.3 . 2 [1].

. 1.14.

C#
, [1]
2.17 . 2.
1.9.
using System;
class main
{

public static int Main( )


{

double a, b, eps, S;
Console.WriteLine( "Enter a, b and eps: " );
a
= Convert.ToDouble( Console.ReadLine() )
b
= Convert.ToDouble( Console.ReadLine() )
eps = Convert.ToDouble( Console.ReadLine() )
/*-- Testing a, b, eps: */

i f ( (b-a) <= 0 | | eps < 0 )


{

Console.WriteLine( "Bad input values" );


Console.ReadLine();
return -1;
}

S = TrapezSquare( a, b, eps );
Console.WriteLine( "\nFor a = {0}, b = {1}, eps = {2},"+
"S = {3}", a, b, eps, S );

38

______________________________________________________________________ 1
Console.ReadLine();
return 0;

}
/ * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * /

static double TrapezSquare( double a, double b, double eps )


{

double resl, res2;


int N;
N = 2;
resl = MyTrapezSquare( a, b, N ) ;
N= N * 2;
res2 = MyTrapezSquare( a, b, N );
while( Math.Abs( res2 - resl ) >= eps )
{

resl = res2;
N = N * 2;
res2 = MyTrapezSquare( a, b, N ) ;
}

return res2;
}
/ * -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------* /

static double MyTrapezSquare( double a, double b, int N )


{

double x, h, SI, S2;


h = ( b - a ) / N;
51 = ( Math.Sin(a) + Math.Sin(b)
52 = 0;

) / 2;

for( x=a+h; x < b; x=x+h )


{

S2 = S2 + Math.Sin(x);
}

return h * ( SI + S2 );
}
}

,
, ,
C#
, (. . 2
[1]):

C#

39

printf( "\nFor = %Lf, b = %Lf,

" N = %d, S = %Lf",


a, b, N, S ) ;

:
Console.WriteLine( "\nFor = {0}, b = {1}, eps = {2},"+
"S = {3}", a, b, eps, S );

: #, ,
( , )
( "Some""Text" ,
"SomeText")
C#
string,
. 4. (
) .
, #,
1.9, - ,
, #.

. 1.15.

. 1.15

( 2.17 [1]) C#
1.9. ,
#.

40

[_____________________________________________________________________ 1

1.6. (
)
ref out
C#
,
, , ,
.
( /
),
.
1.10.
class main
{
/ * ------------------------------------------------------------------------------------------------------------------* /

public static int Main()


{

int
double
iRes
dRes

xl = 1, x2 = 2, iRes;
yl = 1, y2 = 2, dRes;
= MyMin( xl, x2 );
= MyMin( yl, y2 );

return 0;
}
/ * ------------------------------------------------------------------------------------------------------------------ * /

static int MyMin( int x, int )


{ return ( x < )? x : y; }
/ * ------------------------------------------------------------------------------------------------------------------ * /

static double MyMin( double x, double )


{ return ( x < )? x : y; }
/ * ------------------------------------------------------------------------------------------------------------------ * /
}

, {function overloading)
, ,
,
F in d (} , S o r t ( ) , Min () , , ,
.
1.10 ( )
- MyMin. -

41

C#

, - d o u b le .
, 1.10
C/C++ (. . 4.6 [2]),
#.
FCL
. ,
W r ite L in e () C o n s o le -
, ,
Microsoft Visual C#
.
F1,
(. . 1.16).
Q2 main.cs - [WriteLine Method]
X) File

| 4- *4
Solu... ?

View

Edit

a
tion Proj9' ( I p
P ro j9
oj References
rrvain.cs

Project

3@

Debug

f iS

l.P.I Xl

Build

Debug
-

Tools

Window

- & x

Help

ms-he!p://MS.VSCC.2003/MS.M5DNQTR.2C -

G f1 ^

JJ.

"

M .

0 13 -NET Framework Class Library


Console.WriteLine Method [c *l
O v e r lo a d L is t
Writes the current line terminator to the standard output stream
Supported by the .NET Compact Framework.
p u b lic s ta tic vo id W rite L in e O ;
Writes the text representation of the specified Boolean value followed by the
current line terminator to the standard output stream.

___I 2J

o u b lic s ta tic vo id W rite L in e fb o o l):

J tf
Done

. 1.16.
. 1.16 ,
W ri t e L in e () {Overload List - ).
,
C#
, C#
(. . 2.6 [1]),
.

42

, , , MySwap (),
.
, , ,
, (
) , . 2.6
[1].
1.11.
using System;
class main
{

static int M = 1, N = 5;
/*

* /

public static int Main()


{

MySwap();
Console.WriteLine( "M = {0} N = {1}, M, N );
Console.ReadLine();
return 0;
}
/ * ----------------------------------------------------------------------------------------------------------------------------------* /

static void MySwap( )


{

int temp;
temp = M;
M = N;
N = temp;
}
/*

* /

1.11 N static
M ain () MySwap ( ) ,
. MySwap ( )
,
(. . 1.17).
,
, #, ,
.

C#

< E :\B O O K S \K U D IT S \O B . o k \T e s ts \P ro j6

43

J B J xJ

. 1.17.


(. . 6.5 [1]). C#
,
, . , ,
, .
1.12.
using System;
class main
{

public static unsafe int Main()


{

int M = 1, N = 5;
// M N:

MySwap( &, &N );


Console.WriteLine( "M = {0} N = {1}", M, N );
Console.ReadLine();
return 0;
}
/ * ---------------------------------------------------------------------------------------------------------------------------------* /

static unsafe void MySwap( int* pM, int* pN )


{

int temp;
temp = *pM;
*pM = *pN;
*pN = temp;
}

1.12 unsafe (,
), C#
,
(, &- ).

44

, -
, Project | Properties...
Property Pages, (
) Build Allow Unsafe
Code Blocks True (. . 1.18).
f*roj6 Proper Pa^es
onflgiSHon: |Acbve(Debug)

D Common Properties
3 Configuration Properties
t Build
Debugging
Advanced

*J

Configuration Manager ..

Batfonn: |Active(.NET)

Code G e n e ra tio n
Conditional Compilation Constant DEBUG; TRACE
Opt mize Code
False
Check for Arthmetic Overflow/Ur False
B IM IB E ffftd s P rf False
**' and V/ v ,ngs
Warning Level
Treat Warnings As Errors
Suppress Specific Warnings
Output
Output Path
bln\Debug\
XML Documentation File
Generate Debugging Informat on True
Registet for COM Irfcnop
False
Allow Unsafe Code Blocks
Enable use of the unsafe keyword (/unsafe)

OK

Cancel

Help

. 1.18.

, C# .
C#
C++ (. [2]).
C++ C# , .
,
, ,
, ,
, , ref.

C#

45

.
using System;
class main

{
public static int M a i n O

{
int M = 1, N = 5;
// M N :
MySwap( ref , ref N );
Console.WriteLine( "M = {0} N = {1}", M, N );
Console.ReadLine();
return 0;

}
/* ----------------------------------------------------------------------- */
static void MySwap( ref int M, ref int N >

{
int temp;
temp = M;
M = N;
N = temp;

}
>
r e f
MySwarp ( ),
, ,
C# .

2.

C#

2.1.

. 1 C# (wrappers)
.
,
,
[1],
#.
, C#
( )
, C o n so le,
W rite L in e () R eadL ine ()
, p r i n t f ( ) s c a n f ()
.
#,
, ,
,
,
. , C#
(
) ,
.

#,
() .
C# ,
,
, , , . . II
,
- .
.
MyComplex, d o u b le R, I L ength,
,
(

C#

47

, - .,
, [4]).
2.1.
class MyComplex
{

// Methods:
public void SetR(
{ R = x; Length =
public void Setl(
{ I = ; Length =

double x )
Math.Sqrt( R*R + 1*1 ); }
double )
Math.Sqrt( R*R + 1*1 ); }

public void Print( )


{ Console.WriteLine( "Complex number = {0}+{l}i"/ R, I ); }
static public void Sum(MyComplex zl,MyComplex z2,MyComplex z3)
{

z3.R = zl.R + z2.R; z3.I = zl.I + z2.I;


z3.Length = Math.Sqrt( z3.R * z3.R + z3.I * z3.I );
}

// Data
private
private
public

fields:
double R;
double I;
double Length;

MyComplex double
R, I Length, . Complex //Data fields.

,
( , ).
R
(, x + iy
, - ),
I - . Length
[4],

( SetR (),
Setl () Sum () 2.1).
R I private,
MyComplex.

48

Length , public.
C# private public , private.
: C++ (. [2]) C#
public/private (
), .
, C# ( friend
).
2.1
, C++,
C++ , , .
,
, ,
, ,
. - ,
.
( static)
-
MyComplex ( . .)
,
double.
Sum () 2.1.
. 1
(. 1.11), ,
,
,
, , .

.
, , 2.1
, Sum ()
.
, static
, SetR ( ) ,Setl ()
Print () 2.1.
, R, I Length.

( ).

C#

49

2.2.

,
, ,

, ,
.
, , ,

( ).
p l e x M a in ( ), , ,
MyComplex. ,
:
static public int Main( )
{

double
x
MyComplex rZ

=
=

0;
null;

/*1*/
/*2*/

,
( d o u b le )
( MyComplex).
double, /* 1 * /,
(
)
, d o u b le .
,
.
,
( ,
).

( ).

C#
.
C#
(

50

, ; - - ). ,
/ * 2 * / MyComplex ,
rZ,
MyComplex. , / * 2 * /
,
(
Intel IA-32, Pentium,
4 ) null (
#), CLR
. ,
CLR 0,
. n u l l -
n u l l ( ).
rZ (<object reference) MyComplex.
/* 2 * /
/* 1 * /.

MyComplex ( ,
)
new ( #)
. new

:
static public int Main( )
{

double
x
= 0;
MyComplex rZ = null;
rZ = new MyComplexO;

/*1*/
/*2*/
/*3*/

, MyComplex
rZ /* 3 * /
.
(
)
#:
MyComplex rZ

new MyClass();

-
,
2.1 Sum().

C#

51

: C++ (. [2,3]),
,
, , C#
: C# (
, C++),
, , .

C# ,
,
Empty Project - MyComplex.cs
main.cs.
MyComplex.cs MyComplex
2.1, using System.
main.cs m a in M ain (),
MyComplex :
2.2.
/*---File MyComplex.cs
using System;

---- */

class MyComplex
{

// Methods:
public void SetR(
{ R = x; Length =
public void Setl(
{ I = ; Length =

double x )
Math.Sqrt( R*R + 1*1 ); }
double )
Math.Sqrt( R*R + 1*1 ); }

public void Print( )


{ Console.WriteLine( "Complex number = {0}+{l}i", R, I ); }
static public void Sum(MyComplex zl,MyComplex z2,MyComplex z3)
{

z3.R = zl.R + z2.R; z3.I = zl.I + z2.I;


z3.Length = Math.Sqrt( z3.R * z3.R + z3.I * z3.I );
}

// Data
private
private
public

fields:
double R;
double I;
double Length;

52

/*---File main.cs
using System;

---- */

class main

{
static public int Main( )

/*1*/

/* 2 * /
// Create
MyComplex
MyComplex
MyComplex

3 Complex objects:
zl = new MyComplex()
z2 = new MyComplex()
z3 = new MyComplex()

// Process "complex" numbers:


zl.SetR( 1 ); zl.Setl( 2 );
z2.SetR( 3 ); z2.Setl( 4 );
MyComplex.Sum( zl, z2, z3 )
z3.Print();
Console.WriteLine( "Length = {0}", z3.Length )
// Screen delay:
Console .ReadLine ().,
return 0;

/*3*/
/*4*/

/*5*/

/* f ' /
/*7*/
/*8*/
/*9*/

/* 1 0 * /
/* 1 1 * /
/* 1 2 * /
/*13*/
/*14*/
/*15*/
/*16*/
/*17*/
/*18*/
/*19*/

/* 2 0 * /

}
, / * 4 * / - / * 6 * /
MyComplex, z l, z2 z3.

( / * 9 * / - / * 1 0 * / /* 1 4 * / - / * 1 5 * / ) ,
L e n g th ( /* 1 5 * /).
Sum () ,
.
, , Main ()
( ) MyCom
p l e x .
( z l) SetR () S e t l ()
1 2, .
- 2 4, .
Sum () , z3
. P r i n t ( ) ,
L en g th .

C#

53

(. [4]),
4 + 6 i. 2.2 NET ,
(. . 2.1).
i E:\BOOKS\KUDITS\C#Book Te%U
Complex number e 4+6 i
Length * 7.21110255092798

hi

.....................................................

i
j

. 2.1.

,
. , Sum(),
,
( r e f ),
z3 .
Sum () , z3.
,
C# . ,
C++ , M ain ()
2.2, , ,
( ).
. , CLR
(managed heap),
CLR.
, (gar
bage collection).
: C++, new
delete, C#
, ( ) delete
.
, C++ C#
,
MyComplex zl = new MyComplex(); MyComplex z2 = new MyComplexO;
zl = z2; /*1*/

54

/ * 1 * / ,
( z l z2
,
CLR).
C++
new. - ,
(<default constructor). C++
,
( ) ,
.
, , #.
, C++,

. , ,
C++,
.
.
. MyComplex

( R I p r i v a t e )
(
)
( L en g th p u b lic ). (
Main () )
MyComplex.cs -
[4]
.
,
, . -,

.
. ,
- -
Sum ( ) .
, . MyCom
p l e x #,
. 2.4.

C#

55

, .
, ,
,
,
.
, M ain () -
#.
,
(, :
- ). ,
.

2.3. :
, ,
. ,
(<constructors), ,

new, 2.2.

(
void), ,
.

( ),
. ,
( ),
.
MyComplex 2.2 ,
:
2.3.
/*----- File MyComplex. cs
using System;
class MyComplex

{
// Constructors:

-----*/

56

public MyComplex( ){ R = I = Length =0; }


public MyComplex( double r, double i )
{ R = r; I = i; Length = Math.Sqrt( R*R + 1*1 ); }
// Methods:
public void SetR(
{ R = x; Length =
public void Setl(
{ I = ; Length =

double x )
Math.Sqrt( R*R + 1*1 ); }
double )
Math.Sqrt( R*R + 1*1 ); }

public void Print( )


{ Console.WriteLine( "Complex number = {0}+{l}i", R, I ); }
static public void Sum(MyComplex zl,MyComplex z2,MyComplex z3)

{
z3.R = zl.R + z2.R; z3.I = zl.I + z2.I;
z3.Length = Math.Sqrtf z3.R * z3.R + z3.I * z3.I );

}
// Data
private
private
public

fields:
double R;
double I;
double Length;

}
File main.cs
/*---using System;

---- */

class main

{
static public int Main( )

{
// Create
MyComplex
MyComplex
MyComplex

3 Complex objects:
zl = new MyComplex(1, 2 );
z2 = new MyComplex(3, 4 );
z3 = new MyComplex();

// Process "complex" numbers:


//zl.SetR ( 1 ),; zl.SetI( 2 );
//z2.SetR( 3 ); z2.SetI( 4 );
MyComplex.Sum( zl, z2, z3 );
z3.Print();
Console.WriteLine( "Length = {0}", z3.Length );

C#

57

// Screen delay:
Console.ReadLine();
return 0;

}
}
, ,
z l z2
d o u b le ,

SetR () S e t l () ( 2.3
).
, ,
,
() MyComplex, ,
,
.
MyComplex ,
+ ( ).
SetR() Setl() ,

.

{copy constructor)- ,
, (,

):
public MyComplex( MyComplex z )
{ R = z.R; I = z .I ; Length = z.Length;

MyComplex ,

,
( MyComplex).
:
/*----- File main.cs
Using System;
class main

-----*/

{
static public int Main( )

58

{
MyComplex zl = new MyComplex( 1, 2 );
MyComplex z2 = new MyComplex( zl );
z 2 .Print();
Console.ReadLine();
return 0;

/* 1 * /
/* 2 * /
/*3*/
/*4*/
/*5*/

/ *2 * /
z2 z l ( ,
MyComplex)
() (. . 2.2).

. 2.2.

.
, ,
( - ).
.
. -,
C# ( C++)
, -
,
:
class Test
{ public T e s t ()
{ x = 7; }
private int x = 6 ;

/*1 */

}
class main
{ static public int Main( )
{ Test obj = new Test();

C#

59

return 0;

}
=
/ * 1 * /.
(breakpoints) , . 2.3.
Projl - Microsoft Visu C# [break]
File

Edit

View

Project

Build

Debug

JnjxJ
Tools

Window

Help

ISolutionExplorer -Pro]10 x 1[^main


#Main()
s fs j! j !
class Test
4/1 SolutionPro]10(1project)
J { public Test()

Projl0

{ >
(o) References

jU S S S B S E B S B

}
class main
{ static public int Main( )
<5
{ Test obj new Test();
5JsoiutC)n... jjpRunnin.., j <1______ ___ 1
Ready
If, , .
\

- & X

______ 2 L
1

. 2.3.

, ,
T e s t
/* 1 * / ,
. ,

(
, ).
.
C# ( C++)
:
class Test
{ static T e s t ()
{ = 5; }
public Test(){ x = 7; }
private int x;
static private int y;

60

class main
{ static public int M a i n ( )
{ Test obj = new Test();
return 0;

}
}

( p r i v a t e p u b li c ) .
,
, .
.
CLR, ,
, NET- .

2.4. :

MyComplex,
Sum ()
, - +.
,

. -,
. -
-
operator .
( ) - .
- + MyComplex,
,
- :
static public MyComplex operator+ ( MyComplex , MyComplex rOp )

{
return new MyComplex( lOp.R + rOp.R, lOp.I + rOp.I );

}
MyComplex,
,

C#

61

,
, .

:
Z3 = zl + z2 ;

- o p e ra to r+ () z l z2,
- ,
z3. , z3 ,
z l z2.
, MyComplex
-
, . ,
() :
2.4.
/*---File MyComplex.es
using System;
class MyComplex

---- */

{
// Constructors:
public MyComplex( ){ R = I = Length = 0 ; }
public MyComplex( double r, double i )
{ R = r; I = i; Length = Math.Sqrt( R*R + 1*1 ); }
public MyComplex( MyComplex z )
{ R = z.R; I = z.I; Length = z.Length; }
// Methods:
public void SetR( double x )
{ R = x; Length = Math.Sqrt( R*R + 1*1 ); }
public void Setl( double )
{ I = ; Length = Math.Sqrt( R*R + 1*1 ); }
public void Print( )
{ Console.WriteLine( "Complex number = {0}+{l}i", R, I ); }
// Overloaded operator "+":
static public MyComplex operator+ (MyComplex , MyComplex rOp)
{ return new MyComplex( lOp.R + rOp.R, lOp.I + rOp.I ); }

62
// Data fields:
private double
R;
private double
I;
public double Length;

}
/*---File main.es
using System;
class main

---- */

{
static public int Main( )

{
MyComplex zl
= new MyComplex(1,
MyComplex z2
= new MyComplex(3,
MyComplex z3 = null;

2 );
4 );

z3 = zl + z2;
/*1*/
z3.Print();
Console.WriteLine( "Length = {0}", z3.Length );
Console.ReadLine();
return 0;

}
}
, M ain (),
z l z2, z3 MyCom
p le x , z l + z2
o p e r a t o r + () /* 1 * / 2.4.
2.4 ( Empty Project)
,
, . 2.1.
MyComplex
, +
- * (
) [4], Abs ( ) ,
() .
L en g th
,
- :

C#

63

2.5.
/*---File MyComplex.es
using System;
class MyComplex

---- */

{
// Constructors:
public MyComplex( ){ R = I = Length = 0 ; }
public MyComplex( double r, double i )
{ R = r; I = i; Length = Math.Sqrt( R*R + 1*1 ); }
public MyComplex( MyComplex z )
{ R = z.R; I = z.I; Length = z.Length; }
1 1 Methods:
public void SetR( double x )
{ R = x; Length = Math.Sqrt( R*R + 1*1 ); }
public void Setl( double )
{ I = ; Length = Math.Sqrt( R*R + 1*1 ); }
public void Print( )
{ Console.WriteLine( "Complex number = {OJ+flJi", R, I ); }
static public double Abs ( MyComplex z )
{ return z.Length; }

// Overloaded operators:
static public MyComplex operator+ (MyComplex I0p,MyComplex rOp)
{ return new MyComplex( lOp.R + rOp.R, lOp.I + rOp.I ); }
static public MyComplex operator-(MyComplex , MyComplex rOp)
{ return new MyComplex( lOp.R - rOp.R, lOp.I - rOp.I ); }
static public MyComplex operator*(MyComplex lOp,MyComplex rOp)

{
double Re = lOp.R * rOp.R - lOp.I * rOp.I;
double Im = lOp.R * rOp.I + lOp.I * rOp.R;
return new MyComplex( Re, Im );

}
1 1 Data fields:
private double R;
private double I;
public double Length;

}
File main.es
/*---using System;
class main

---- */

{
static public int Main( )

64

2
MyComplex zl
MyComplex z2
MyComplex z3

= new MyComplex( 1, 2 );
= new MyComplex( 3, 4 );
= null;

z3 = zl * z2 ;
z 3 .Print();
Console.WriteLine( "Abs value = {0}", MyComplex.Abs(z3) )
Console.ReadLine();
return 0;

}
2.5, -
(. . 2.4)
MyComplex.
C V E:\BOOKS\KUDITS * Book Tests Pni|S\Un\D*bu
C o n p le x nu m b er = - 5 + 1 0 i
fibs v a l u e = 1 1 -1 8 0 3 3 9 8 8 7 4 9 8 9

- 1 * 1
1

zJ
h i

. 2.4.

, ( l + 2 i ) (3 + 4 i)
( - 5 + 1 0 i) .
, MyComplex .
, , . , -

P r i n t ():
z 3 .Print();

, WriteLineO
Console.
MyComplex,
.
, , ,
. , #,
C++ (. [3]), ,
( ) , [ ] new ( ,
) .

3.

C#

3.1.
,

,
. ,
,
. ,
,
. ,
, -,
, -,
.
.
.
, [1]
. ,
, ,
#. ,
- ( ) .
,
, , [1].
.
C#
: ;
. , , .
( ),
3.9 [1],
,
.
100%- , #:

66

_____________________________________________________________________ 3

3.1.
class main

{
public static int Main()

{
int size=73, i, Max;
int[] Arr = {1,6,3,2,5,1,77,-18,99,16,45,12,-45,54,
567,-123,5,9,-4,67,-17,44,2,3,9,5,34,
11,-11,234,67,82,91,3,7,15,-32,-56,-77,
678, -987,456,-123,555,3,78,1,90,-4,37,
2,33,6,543,-88,37,66,-66,777,12,-45,567,
999,888,3,-765,34,89,-37,41,333,56,-987};
//size = sizeof( Arr )/ sizeof( int );
Max = Arr[0];
for( i = 1; i < size; i++ )

{
if( Arr[i] > Max )
Max = Arr[i];

}
return 0;

}
}
,
, 999,
. - ,
. - ,
s i z e o f C# ,
(, , unsafe . . 1.6), size,
, .
- ,
int, .
,
C# ( ) 3.1 .
[1] 3.10,
A r r A v e r ()
. 3.10 C#
:

C#

67

3.2.
class main

{
static public int Main( )

{
int size = 73; double Aver;
int[] Arr = {1,6,3,2,5,1,77,-18,99,16,45,12,-45,54,
567,-123,5,9,-4,67,-17,44,2,3,9,5,34,
11,-11,234,67,82,91,3,7,15,-32,-56,-77,
678, -987,456,-123,555,3,^8,1,90,-4,37,
2,33,6,543,-88,37,66,-66,777,12,-45,567,
999,888,3,-765,34,89,-37,41,333,56,-987};
//size = sizeof( Arr )/ sizeof( int );

/ * ---------------------------------------*/
Aver = ArrAver( Arr, Size );

/ * ---------------------------------------*/

return 0;

}
static public double ArrAver( int[] ar, int size )

{
int i;

double Sum = 0;

for( i = 0; i< size; i++ )

{
Sum = Sum + a r [i];

}
return Sum / size;
}
}

ArrAver ()
i n t ,
, .
, #. ,

( []) .
( )
.
. ,
.

68

,
. ,
(. . 6.2 [1]), C# - Array
System.
(
,
), ,
A rray.
, new, ,
.
, 3.1 3.2, (
) new ( ,
).
#.
,
.
,

( ).
L ength,
C# Array.
,
-
. 3.2:
3.3.
class main

{
static public int Main( )

{
double Aver;
int[] Arr = {1,6,3,2,5,1,77,-18,99,16,45,12,-45,54,
567,-123,5,9,-4,67,-17,44,2,3,9,5,34,
11,-11,234,67,82,91,3,7,15,-32,-56,-77,
678, -987,456,-123,555,3,78,1,9 0,-4,37,
2,33,6,543,-88,37,66,-66,777,12,-45,567,
999,888,3,-7 65,34,89,-37,41,333,56,-987};

C#

69

/ * -----------------------------------------*/
Aver = ArrAver( Arr );

/* ----------------------------------------- */

return 0;

}
static public double ArrAver( int[] ar )

{
int i, size = ar.Length; double Sum = 0;
for( i = 0; i < size; i++ )

{
Sum = Sum + a r [i];

}
return Sum / size;

}
}
A rrA v e r (), ar ,
a r . L en g th .

3.2. C#
, C#
new,
(
A rray , ):
int[] ar = null;
ar = new int[6 ];

,
n u l l ( ).
, 6 i n t .
6 () .
:
int[] ar = new int[6 ];

:
int[] ar = new int[6] {1,2,3,4,5,6};

70

int[] ar = new int[] {l/2/3/4/5/6};

C# ,
:
double[,] twodAr = new double[2,3];

. C/C++,

(. [2]), C# -
(
):
for( int i = 0; i < twodAr.GetLength( 0 ); ++i )
for( int j = 0; j < twodAr.GetLength( 1 ); ++j )
twodAr[i,j] = i + j ;

G etL en g th (), C# A rray ,


( ). ,
twodAr .G e tL e n g th (0)
, tw odA r. G etL en g th (1) - .
,
twodAr.Rank

, 2
. tw odA r. L e n g th
, 6 .

#,
, (
Random).
[1], 3.11:
3.4.
using System;
class main

/ * ------------------------------------------------------------------------------ */
static public int Main( )

{
// :
Random rand = new Random();

C#

71

// :
double[,] twodAr = new double[2,3];
//
// :
for( int i = 0; i < twodAr.GetLength( 0 ); ++i )
for( int j = 0; j < twodAr.GetLength( 1 ); ++j )
twodAr[i ,j] = rand.NextDouble();
// :

double Disp = ArrDisp( twodAr );


Console.WriteLine( "Disp = {0}", Disp );
Console.ReadLine();
return 0;

/* ------------------------------------------------------------------------------ */
static double ArrAver( doublet,] ar )

{
double Sum = 0;
for( int i = 0; i < ar .GetLength( 0 ); ++i )
for( int j
= 0; j < ar.GetLength( 1 ); ++j
Sum = Sum
+ a r [i ,j];

return Sum / ( ar.Length );

}
/* --------------------------------------------------------------------------------* /
static double ArrDisp( doublet,] ar )

{
double Aver, dSum = 0;
Aver = ArrAver( ar );
for( int i = 0; i < ar.GetLength( 0 ); ++i )
for( int j
= 0; j < ar.GetLength( 1 ); ++j
)
dSum = dSum + ( a r [i ,j] - Aver ) * ( a r [i ,j] - Aver );
return Math.Sqrt( dSum / ( ar.Length ) );

}
/ * --------------------------------------------------------------------------------*/
}
N e x t D o u b l e () R a n d o m
0 1. 3.4
. . 3.1

,
.

. 3.1.
,
. ,
:
int[] ar = new i n t [ ];
for( int i = 0; i <= ar.Length; ++i) ar[i]++;

< <=.

.
, ,
,
. [1]
.
, C#
,
, . Microsoft NET Framework
CLR,
- ,
C# ( ,
C# Array, ).
CLR (exception)
(. . 3.2).
, Continue,
. Break,
(debug),
System.IndexOutOfRangeException,
.

C#

73

An unhandled exception of type System. IndexOutOfRangeException


occurred in Pro) 11. exe
Additional information: Index was outside the bounds of the array.

-J
Break

Continue

Help

. 3.2.

,
- . , ,
.
C#
-
,
(try-).
, #,
FCL NET- [5].
, , C#
( while for), foreach ,

( ):
int[] ar = new i n t [] {1,2,3,4,5,6};
foreach( int el in ar)
Console.WriteLine( "Element in ar = {0}", el );


(. . 3.3).

. 3.3.

74

, f o r e a c h .
: (foreach)
e l , int,
W r ite L in e (). .
,
(
).

3.3.
. 2 , C#
.
, :
MyComplex[] mcAr = new MyComplex[4];

M yC o m ple x - 2.5,
,
n u l l M yCom plex.
, Debug-
Microsoft Visual C#
F9 , (
F10), mcAr
Shift-F9 QuickWatch (. . 3.4).
j QuickWatch
Expression:

Recalculate |
|

Add Watch
Close
Help

Current value:
Name
E3 mcAr

[0]

[1]

[2]

. 3.4.

Value
{Length=4}
<undefined value >
<undefined value >
cundef ned value >
<undefined value >

Type
MyComplex[]
MyComplex
MyComplex
MyComplex
MyComplex

I 3

C#

75

. 3.4 , null undefined


value ( ,
).
, new
CLR (
) MyComplex:
mcAr[0] = new MyComplex( 1, 2 );
mcAr[l] = new MyComplex( 3, 4 );

0 1

MyComplex.
QuickWatch,
(. . 3.5).

Recalculate

Expression:

zl

Add Watch
Close
Help

Current value:
Name

1Value

R mcAr

[]
- [i]

[2]
[33

{Length=4}
{MyComplex}
{MyComplex}
<undefined va!ue>
<undefmed value >

I Type
MyComplex[]
MyComplex
MyComplex
MyComplex
MyComplex

. 3.5.

. 3.5 {MyComplex}
M yCom plex.
, ,
I , L e n g t h R
M yC o m ple x (. . 3.6).
. 3.6 R I [ 0 ]
, (.
2.5) M yC o m ple x new.

76

QuickWatch
Recalculate

Expression:
jm cA r[0]

Add Watch
Close

Help

Current value:

Type

Value

Name

System {MyComplex}
I
2.0
Length 2.23606797749979

1.0

'J

System Object
double
double
double

zi

. 3.6.

, ,
( MyComplex),
AverLen(),
:
3.5.
class main

{
static public int Main( )

{
MyComplex[ ] mcAr = new MyComplex[ 4 ] ;
m c A r[0 ]
m c A r [l]
m c A r[2 ]
m c A r[3 ]

=
=
=
=

new
new
new
new

MyComplex(
MyComplex(
MyComplex(
MyComplex(

1,
3,
5,
7,

2
4
6
8

);
);
);
);

/ * ------------------------------------------------ */
double averLen = AverLen( mcAr );

/ * -------------------------------------------------*/
return 0;

/ * ------------------------------------------------------------------------- */
static public double AverLen( MyComplex[] mcAr )

C#

77

int i, size = mcAr.Length;


double Sum = 0;
for( i = 0; i < size; i++ )

{
Sum = Sum + meAr[i].Length;

}
return Sum / size;

}
}
3.5, .

i n t MyComplex,
(. . 3.7).
int[] LA = new int[2];

MyComplex[] mcAr =
new My omplex[2];

null

null

. 3.7.


(. . 3.8).
int[] LAr = newint[2]{l,2);

W&I

MyComplex[] mcAr =
new MyComplex[2]
{new MyComplex(l,2),new MyComplex(3,4)};

iAr


MyComplex

a?

l+2i 3+4i

mcAr

(" ")

. 3.8.

. 3.8 ,
( MyComplex),

78

,
.

3.4. C#
,
( ).
#.
:
3.6.
using System;
class Test

{
// Constructor:
public Test( int Num ){ data = new intfNum]; }
// Other methods:
public int GetElem( int i ){ return data[i]; }
public void SetElem( int i, int val ){ data[i] = val; }
public int[] GetInnerAr( ){ return data; }
// Data field:
private int[] data;

}
class main

{
static public int Main( )

{
Test obj = new Test(3);
// :

for( int i = 0; i < obj.GetInnerAr().Length; ++i )


obj.SetElem( 1,1*1);
/*1*/
// " ":

foreach( int el in obj.GetlnnerAr() )


Console.WriteLine( "Elem = {0}", el );
Console.ReadLine();

/*2*/
/*3*/

C#

79

return 0;

}
}
Test ,
.
. SetElem()
.
Get Inner Ar ()
data ( ).
,
, .
. 3.9 , ,

( / * ! * / 3.6).
VE:\BOOKS\KUDITS\r#book -*v ' 5 \ \
E le n = 0
E le n * 1
E le n 4

Bl
=1

JlU

. 3.9.

3.6
foreach ( / * 2 * / - / * 3 * / ) ,
,
GetlnnerAr () Test.
( ) ,
C# Array,
. C#
,
, ,
( .
. 2.3).
, , ,

, :

80

T e s t 3.6
:
public Test( Test ob ){ data = ob.data; }

, , :
Test obj = new Test(3); Test obj2 = new Test(obj);


,
T e s t, . .
Test obj = new Test(3);

Test obj2 = new Test(obj);

I
0

. 3.10.

o b j o b j 2 ,
data, ,

. 3.6,
o b j,
o b j 2,
, . 3.9.
, ,
Test ,
(shallow ). ,

:
public Test( Test ob )

{
int len = ob.GetInnerAr().Length;
data = new int[len];
for( int i = 0; i < len; ++i )
data[i] = ob.GetElem( i );
}

C#

81

( C++)
,
:
class Test2

{
// Constructor:
public Test( int Num ){ data = new int[Num]; }
// Other methods:
public int GetElem( int i ){ return data[i]; }
public void SetElem( int i, int val ){ data[i] = val; }
public int[] GetInnerAr( ){ return data; }
// Data field:
private int[] data;
// Static array:
static public int ARR [] = new int [] {1,2,3,4,5};

}

= (. . 2.3)
. , ,
. , ,
.

3.5.
#, , C#
, ,
. ? (. . 3.2),
, CLR
.
, C/C++,
,
C/C++.
#
? , :
C# A rra y ,
,
. ,
.

82

_____________________________________________________________________ 3

[1] ,
, ,
, (. 3.18 [1]). ,
C# ( ).
, Array
Sort (), :
3.7.
using System;
class main

{
static public int Main( )

{
Random rand = new Random();
double[] Ar = new double[50000];
for( int i - 0; i < Ar.Length; ++i )
A r [i] = rand.NextDouble();

/ * -----------------------*/
Array.Sort( Ar );

/ * -----------------------*/

foreach( double el in Ar )
Console.WriteLine( "El = {0}", el );

C o n so le. R eadL ine( ) ;


r e t u r n 0;
}
}
(
) , . ,
3.6, 50000
double. ,
( [1])
. -
, .
3.6 Empty Project, .

. , ,
, . 3.11.

C#

83

. 3.11.

. 3.11 , Sort ()
.
, ,
#, .
#,
(, Sort () int, dou
ble, ,
).
, ,
.
Array,
Binary Search ():
3.8.
using System;
class main

{
static public int Main( )

{
Random rand = new Random();
int[] Ar = new int[50000];
for( int i = 0; i < Ar.Length; ++i )
Ar[i] = rand.Next( 0, 10000 );
Array.Sort( Ar );
int ind = Array.BinarySearch( Ar, 5 );

3
if( ind >= 0 ) 1 1 success
Console.WriteLine( "El = {0} for index = {1}",
Ar[ind], ind );
else
// failure
Console.WriteLine( "No any 5s in the array" );
Console.ReadLine();
return 0;

}
3.8, C#
BinarySearch () Array (
System) ,
bsearch () (. . 9.2
[1]). BinarySearch ()
, ,
. , ,
Sort ().
, ,
(
N ex t () 0 10000),
3.8 .
, (
5), . 3.12.

. 3.12.

-
( ) , 5
( ),
3.8 , . 3.13.
Array ,
Sort () BinarySearch ( ) , ,
, ,

C#

85

. 3.13.

, ,
.
[1] (. 3.5).
:
3.9.
using System;
class main

{
static public int Main( )

{
Random rand = new Random();
double[] Ar = new double[5 ] ;
for( int i = 0; i < Ar.Length; ++i )
A r [i] = rand.NextDouble();
foreach( double el in Ar )
Console.WriteLine( "Before reverse: El = \t{0}", el );

/*

*/

Array.Reverse( Ar );

/*

*/

Console.WriteLine();
foreach( double el in Ar )
Console.WriteLine( "After reverse: El = \t{0}", el );
Console.ReadLine();
return 0;
}

86

R e v e r s e () -
. . 3.14
.

. 3.14.

. 3.14 , R e v e r s e ()
, ()
.
, , C#

, ( )
.

4.

C#

4.1. char UNICODE


,
char (. . 4.1 [1]). C#
char . char C#
UNICODE (2
, 1 ASCII/ANSI).
,
( ).
. , UNICODE
,
( )
.
#, ,
( ).
UNICODE-
,
,
:
4.1.
using System;
class main

{
static public int Main( )

{
char[] chAr = {'A', '\\ , ' ', ' '};
int[] iCode = new int[chAr.Length];
for( int i = 0; i < chAr.Length; ++i )

{
iCode[i] = (int)chAr[i];
Console.WriteLine( " {0} {1}",
chAr[i ] , iCode[i] );
}

88
Console.ReadLine();
return 0;

}
}
chAr char [ ] - ''
'', '', .
C# , (. . 4.1
[1]) - (\ , \ t - . .),
.
chAr [ ]
int :
iCode[i] = (int)chAr[i];
WriteLine () chAr
, iCode [i ] -
.

4.1
UNICODE- (. . 4.1).

. 4.1.

. 4.1 , UNICODE-
65, - 92,
- 1060, - 1046.
, UNOCODE- , ,
, ASCII-.
\ \t:

C#

89

4.2.
using System;
class main

{
static public int Main( )

{
char x = '\n', = '\t';
int ix = (int)x, iy = (int)y;
Console.WriteLine( "Symbol \\n has code {0}", ix );
Console.WriteLine( "Symbol \\t has code {0}", iy );
Console.ReadLine();
return 0;

}
,
(. . 4.2).
E:\BIj OKS\KUDITV Cffbook \C J f \F ro| 1
yrobol h a s c o d e 1 0
C t/n b o l 4 t h a s c o d e 9

zl

. 4.2 , \
UNICODE- 10 ( ), \ t
9 ( , ASCII- - .
4.4 . 4.3 [1]).
, . . 4.1
, UNICODE- ( 1000),
:
4.3.
using System;
class main

90

static public int Main( )

{
char x = (char)1040;
Console.WriteLine( "UNICODE\t\tSymbol" );
Console.WriteLine( "------------------------------" );
for( int i =0; i < 66; ++i, ++x )

{
Console.WriteLine( "{0}\t\t{1}", x, 1040+i );

}
Console.ReadLine();
return 0;

}
, ,
UNICODE-
(. . 4.3).
E:\BOOKS\KUDITS\C#8o. TesU .. Oebug
Symbol

UNICODE

1040
1041
1042
1043
1044
1045
1046

.
. 4.3.

, #, C/C++, char
,
. 4.3
:
char = (char)1040;

,
1040:
char = '\u0410';

, , c h a r C#
C/C++ ,

91

C#

C har (
System).
#, ( - ,
Char, c l a s s ,
- s t r u c t ,
, ).
Char
, - ,
() , .
:
4.4.

using System;
class main
{
static public int Main( )
{
char xl = '\n', x2 = ' ', x3 = '7';
if( Char.IsWhiteSpace( xl ) )
Console.WriteLine( "\\n is whitespace" );
if( Char.IsLetter( x2 ) )
Console.WriteLine( " is letter" );
if( Char.IsNumber( x3 ) )
Console.WriteLine( "7 is number" );
Console.ReadLine();
return 0;
}
}
, IsW h ite S p a c e (), I s L e t t e r ( ) IsN um ber () (. . 4.4).

. 4.4.

92

, \
(whitespace), '' 7 , , ,
. I s L e t t e r O r D ig it (),
, .

4.2. char C#
char
( , UNICODE- ), char
,
( )
:
4.5.
using System;
class main

{
static public int Main( )

{
char[] myT = { '', 'p', ' ', ', 'e', ',
' ', 'M ', ', , '! } ;
Console.WriteLine( "Words in char-array" );
Console.WriteLine( "------------------- );
foreach( char el in myT )
Console.Write( "{0}", el );
Console.ReadLine();
return 0;

}
}
, myT char,
'', '', '', '', '', V , ' ' , '', '','!',
W rite () C o n so le
", !", . 4.5.
4.5 W rite ()
C o n so le, W r ite
L in e (), ,
", !"
( ).

C#

V: BOOKS\KUDITS\CfojukOU\Pil

93

2<J

D o rd s in c h a r-a p p a y
, !

J
. 4.5.

c h a r [ ]
, ,
,
:
4.6.

using System;
class main
{
static public int Main( )
{
char[] myT = { ' ', 'p , ' ', ' ', 'e ', ' ', ',',
' ' , 'M ', ' ' , * ' , '! ' };
Console.WriteLine( "Words in reverse symbol order" );
Console.WriteLine( "-------------------------- " );
/ * ----------------------------- */
Array.Reverse( myT );
/ * ----------------------------- */
foreach( char el in myT )
Console.Write( "{0}"# el );
Console.ReadLine();
return 0;
}
, , C#
Reverse ()
Array (. 3.9),
ReversePhrase () (.
4.6 [1]).

94

. 4.6 4.6.

| E:\BOOK5 KUDIT5 # ^ \ests


|'o i * d s in r e v e r s e sy m b o l o r d e r
1?
M

-|||
j

HI

. 4.6.

. 4.6 R e v e rse () ", !"


"! ".
,
(
c h a r ) . , ,
. ,
,
c h a r ,
. ,
,
, :
"Hello, world" "Something else"

.
C#

String, System. , C# -
String. #,
, .
, String ( )
string (, String).
, C#
c h a r [ ]:
char[] myT = { ' , ' ', '', '', ' ', ' ' };
string str = new string( myT );

C# s t r
String,

C#

95

new.
String ,
c h a r [ ].
, String
, C#
:
string str = new string( ); // error

.
C# ,
,
( C/C++
),
#.
(),
,
string str = "";

, new.
s t r - String
.
s t r ,
. , ,
string str;

, s t r i n g .

str = "";

( new) s t r
String (
"").
= C#
:
string str = "";
str = str + ", " + "" + "!";

, s t r ", !,
, String = +,

96

C# .
,
() +=:
string str = "";
str += ", " + "" + "!";

, ,
,
, , , ,

.
C# ,
,
,
. C#
-
, String
,
.
s t r (
UNICODE-)
s t r . L e n g t h . , , ,
:
4.7.
using System;
class main

{
static public int Main( )

{
string strl = "";
string str2 = new string( 3 , 2 );
strl += , " + str2;

int len = strl.Length;


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

{
char ch = strl[i];
Console.WriteLine( " {0} {1
i / ch );
}

C#

97

Console.ReadLine();
return 0;

}
strl
. 4.7.

. 4.7.

4.7 . ,
( []) ,
.
-, strl, . 4.7,
,
string str2 = new string( '3', 2 );

, (
) ( ).
, ,
String ,
. , , . 1.5
ReadLine () Console, ,
, ,
( Enter,
). :
4.8.
using System;
class main

98
static public int Main( )

{
string strl
string str2
string str3

= Console.ReadLine();
= Console.ReadLine();
= strl + '\n' + str2;

/*1*/
/*2*/
/*3*/

Console.WriteLine( str3 );
Console.ReadLine();
return 0;

}
}
. -,
C# ( / * 1 * / - / * 2 * /
4.8). -, ,
, ( / * 3 * /
).
-, 4.8 Write
Line () ,
s t r 3 .
. 4.8.
Jnfxl

. 4.8.

. 4.8,
"" Enter (
, s t r l ) ,
"Los Angeles". W r ite L in e ()
,
, \ ,
, s t r 3
. . 4.8.

C#

99

4.3.
,
C# ( ),
. , [1]
,
(. . 4.4 [1]). C#
,
. ,

string stl = "abc"; stl = " "; stl = "";

- ( -
):
string st2 = "abc"; st2 += "";


( ).

-
, .

W r ite L in e ():
Console.WriteLine( " "+
" " );

, C# ,
, . ,
:
, ,
.
,
, ,
,
, (,
, ).

.
,
.

100

I_____________________________________________________________________ 4


String .
: N ,
N , N ,
m- .
S u b s t r i n g ():
str.Substring( Startlndex, length );

S t a r t l n d e x -
, a l e n g t h - . :
4.9.
using System;
class main

{
static public int Main( )

{
string strl = "Moscow";
string str2 = null;

/ / 1.
str2 = strl.Substring( 0, 3 );
Console.WriteLine( str2 + '\n' );
// 2 .

str2 = strl.Substring( 1, 2 );
Console.WriteLine( str2 + '\n' );
// 3.
str2 = strl.Substring( strl.Length - 3, 3 );
Console.WriteLine( str2 );
Console.ReadLine();
return 0;

}
4.9 - s t r 2
(. . 4.9).
, . 4.9 , s t r 2
s t r l ,
, 1 (
"os"). , s t r l

C#

\ E:\BQQKS\KUt ITS
Mos

101

-vU'- I

os

ow
I U - -_____ ________________ J

zi

. 4.9.
strl.Substring( strl.Length - 3, 3 )

( "cow").

,
,
.
In d e x O f ():
ind = str.IndexOf( fragment, Startlndex );

f r a g m e n t s t r ,
S t a r t l n d e x ,
. ,
-1 .
In d e x O f () ,
, ?
:
4.10.
using System;
class main

{
static public int Main( )

{
string Text = "When you say \"yes\H, I say \"yes\" too";
string Frag = "yes"; string NewFrag = "no";
int lenOld = Frag.Length, lenNew = NewFrag.Length, ind;
Console.WriteLine( " : " + Text );
ind = Text.IndexOf( Frag, 0 );
while( ind >= 0 )

{
ind = Text.IndexOf( Frag, ind );

102

4
if( ind >= 0 )

{
Text = Text.Remove( ind, lenOld );
Text = Text.Insert( ind, NewFrag );
ind += lenNew;

}
}
Console.WriteLine( " : " + Text );
Console.ReadLine();
return 0;

}
}
4.10 "yes"
"When you say \"yes\", I say Y'yesV' too" (
V
, ) "".
. 4.10.

. 4.10.

. 4.10 , 4.10
. .
, :
Text = Text.Remove( ind, lenOld );
Text = Text.Insert( ind, NewFrag );
ind += lenNew;

: IndexOf ()
ind , Remove (),
Insert () NewFrag
ind .
, , RemoveQ InsertQ
,

C#

103

Text ( string),
( ).
, ,
In d ex O f (),
:
string Text = "Moscow"; char ch = 's'; int ind;
ind = Text.IndexOf( ch, 0 );

in d
2, 's' "Moscow" 2.
IndexOf () .
,

ToLower () () String
Text = Text.ToUpper(); Frag = Frag.ToUpper() ;

IndexOf ().
String
Microsoft Visual C# (. . 4.11).
91 P r o jl9 - Microsoft; Visual C # .NET [d e s ig n ] - [T rim M e th y l ()J
Fie

1:? xl
3
TSTsoii
a p

Edit

View

0 0 E

Project

Build

Debug

lools

Window

Help

-iH lxf
- if x

>NET F ram ew ork C/ass Library

String.Trim Method ( ) [c#]


R e m o v e s a ll o c c u rre n c e s o f w h ite space c h a ra c te rs fro m th e b e g in n in g and en d o f
this
th is in
in sstan
ta n cce.
e,
p u b lic

sr r in c r T rim < )

R e tu r n V a lu e

A new S trin g e q u iv a le n t to th is in s ta n c e a fte r w h ite space ch a ra cte rs a re re m o v e d


fro m th e b e g in n in g and e n d .

<J____________________________________ I
Ready

. 4.11.

, . 4.11
Trim () String, .

,
.

104

4.4. C#
,
#. ,
, ,
.
.
.
:
string[] strArr = null;
strArr = new string[3];
strArr[0] = "first";
strArr[1] = "second";
strArr[2] = "third";

:
string[] strArr = new string[3]{"first","second","third"};

s t r A r r [] ( C#
. 3) ,
- , Quick
Watch ( QuickWatch . . 3.3)
(. . 4.12).
jnjxj
| Recalculate |

Expression:

Add Watch
Close
Current value:
Name

strArr

[0 ]

[1 ]

[2 ]

[ Value
-{L e n g th s}
"first*
"second"
"third"

IType
string[]
string
string
string

U
J

. 4.12.

s t r A r r
:

C#

105

4.11.
using System;
class main

{
static public int Main( )
string[] strArr = new string[3]{"second", "first", "third"};
for( int i = 0; i < strArr.Length; ++i )
Console.WriteLine( strArr[i] );
Console.ReadLine();
return 0;

}
}

. 4.13.

. 4.13.


Sort () Array (. . 3.5)
Array.Sort( strArr );

(. . 4.14).

. 4.14.

106

4.11
s t r A r r .
f o r e a c h ,
, (-
) - ,
s t r A r r (
, . 4.13 4.14):
for( int i = 0; i < strArr.Length; ++i )

{
for( int j = 0; j < strArr[i].Length; ++j )
Console.Write( strArr[i][j] );
Console.WriteLine();

}
W r ite () (
s t r A r r [ i ] [ j ]) i-
, W r ite L in e O
( ).
,
4.11
foreach:
foreach( string el in strArr )
Console.WriteLine( el );

, , , , ,
.
f o r e a c h
,
(separators).
, , S p l i t (), ,
:
4.12.
using System;
class main

{
static public int Main(

{
string str = "second, first, third";
char[] sep = new char[3] {'. ', ', ', ' '};

C#

107

foreach( string s in str.Split( sep ) )


Console.WriteLine( s );
Console.ReadLine();
return 0;

4.12 S p l i t ()
S t r i n g "second, first, third"
("second", "first" "third"), f o r e a c h
.

4.5.
C#
double int.
, "7.3921"
double, "-12345" - int.
, ,
,
.
, . 1.5
double, ReadLine ()
Console, ,
. . 1.5
ReadLine () double ToDouble ()
Convert:
xl = Convert.ToDouble( Console.ReadLine() );


int, ( char):
int I
char ch

= Convert.ToInt32( Console.ReadLine() );
= Convert.ToChar( Console.ReadLine() );

, (
ReadLine ()) . , ,
Convert

. ,
, "4.567.67", ,
Convert

108

CLR ( CLR
. 3.2, . 3.2). ,

int

= Convert.ToInt32( "4.567.67" );


M icrosoft CLR D ebugger

| \

An unhandled exception of type 'System.FormatException' occurred in


Proj20.exe

Additional information: Input string was not in a correct format

J
Continue

Help

. 4.15.



,
(. [5]).

(
) ,
Convert.
Convert :
, ( )
. :
int I = 333; string st = Convert.ToString( I );

.
Convert ,
WriteLine () Con
sole,
(
). W r i t e L i n e O
, .

C#

109

,
Console StringBuilder
( System.Text), AppendFormat ()
, WriteLine () Console,
,
( ), ToString( )
.
, :
4.13.
using System;
using System.Text;
class main

{
static public int Main( )

{
double d = 3.456; int m = 33; string st;
StringBuilder sb = new StringBuilder();
// WriteLine():
Console.WriteLine( "numl = {0}\nnum2 = {l}\n"/ m, d );
// st:
sb.AppendFormat( "numl = {0}\nnum2 = {l}\n", m, d );
st = sb.ToString();
Console.WriteLine( st );
Console.ReadLine();
return 0 ;

}
}
4.13
: , WriteLine ()
m d,
s t ,
AppendFormat () StringBuilder.
, WriteLine () ,
s t.
WriteLine () .
. 4.16 4.13.

110

E:\BOOKS\KUDlTS\C#^tk\TrMVPni^O
nural ift
nup>2 =* 3 .4 5 6

1>< 1. .

n u n l 3 33
n u n 2 3 .4 5 6

_____________ ___________ J____________ 21


. 4.16.

. 4.16 ,
.
StringBuilder ,
.
, Replace ()
4.10 ( ):
string Text = "When you say \"yes\", I say \"yes\" too";
StringBuilder sb = new StringBuilder( Text );
Console.WriteLine( sb.Replace( "yes", "no" ).ToString() );

() Replace ()
.
, , C#
Microsoft NET Framework
( ).
.

II
-
C#

Microsoft NET Framework
5. #: , ,
,
5.1. C#

#,
. , C# ( -
C++) -
{properties).
C#
,
MyComplex,
(. 2.5 . 2.4).
, (
):
5.1.
class Trivial

{
// Methods:
public void Set( double x ){ X = x; }
public double Square( ){ return X * X; }

112

// Private data field:


private double X;

}
Trivial ,
Set () Square ()
, .
Trivial
:
double res;
Trivial ob = new Trivial();
ob .Set( 3 . 5 ) ;
res = ob.Square();

, , ,
( ) , , ,
,
- :
5.2.
ob.X = 3.5;
res = ob.X * ob.X;

Trivial 5.1
( ) -
X,
. 5.2 X
(),
ob Trivial.
,
.
(
)
- .
()
C++ ( - )
, (pub
lic) -

#: , , ,

113


(,
).
X Trivial
(. 5.1) ( private).
,
( 5.2)
( 5.1) . C++
,
. C#
, .
Trivial,
#:
5.3.
class Trivial

{
// Method:
public double Square( ){ return m_X * m_X; }
// Public property X:
public double
X

/*1*/

/* 2 * /
get
set

{return m_X;
{ m_X =value;

} //
} //

get-block: to get m_X value


set-block: to set m_x value

/*3*/
/*4 */
/*5*/

// Private data field:


private double m_X;

}
X (public) Trivial,
/ * 1 * / - / * 5 * / ,
(private) _ (
).
5.3
( double),
( public). (
) g e t - s e t - ,
g e t s e t . (
)

114

_____________________________________________________________________ 5

, .
Trivial get-
get_X (), set- - set_X ().
(
),
,
value #.
,
X - ,
5.2 . ,
,
ob.X = 3.5;

set_X (),
res = ob.X * ob.X;

get_X ().
, C#
, .
,
MyComplex,
(. 2.5 . 2.4):
5.4.
class MyComplex

{
// Constructors:
public MyComplex( ){ R = I = 0; }
public MyComplex( double r, double i ) { R = r ; I = i ;
public MyComplex( MyComplex z ){ R = z.R; I = z.I; }

// Methods:
public void Print( )
{ Console.WriteLine( "Complex number = {0}+{l}i", R, I ); }
static public double Abs( MyComplex z )
{ return z.Length; }
// Properties:
public double Length
{ get { return Math.Sqrt( R*R + 1*1 ); } }

#: , , ,

115

public double Re { get{ return R; } set{ R = value; } }


public double Im { get{ return I; } set{ I = value; } }
// Overloaded operators:
static public MyComplex operators-(MyComplex 1Op,MyComplex rOp)
{ return new MyComplex( lOp.R + rOp.R, lOp.I + rOp.I ); }
static public MyComplex operator-(MyComplex 1Op,MyComplex rOp)
{ return new MyComplex( lOp.R - rOp.R, lOp.I - rOp.I ); }
static public MyComplex operator*(MyComplex lOp,MyComplex rOp)

{
double Re = lOp.R * rOp.R - lOp.I
double Im = lOp.R * rOp.I + lOp.I
return new MyComplex( Re, Im );

* rOp.I;
* rOp.R;

}
// Private data fields:
private double R;
private double I ;

}
MyComplex Length (. 2.5)
5.4 get (set- , , ), SetR()
Setl () Re Im, .


, :
MyComplex zl = new MyComplexO;
zl.Re = 1 ; zl.Im = 2 ;

#.
.
, Length.
,
( ). ,
FCL (
Microsoft NET Framework) ,
, ,
.

116

5.2. :

C# ,
,
:
5.5.
class MyTestl
public void Set( int x ){ Xl = x; }
private int XI;
class MyTest2
public void Set( int x ){ X2 = x; }
private int X2;
class main
public static int Main( )

{
MyTestl obi = new MyTestl();
MyTest2 ob2 = new MyTest2();
obi.Set( 1 ); ob2 .Set( 2 );
return 0 ;

}
}
5.5
() - MyTestl MyTest2. ,
.


UML (Unified Modelling Language). . 5.1 UML
5.5:
M y T e stl

M y T e s t2

- X I : int

- X 2 :in t

+ S e t ( x : i n t ) : void

+ S e t( x : i n t ) : void

. 5.1.

#: , , ,

117

. 5.1 , UML ()
,
, .
UML , -
.
UML
.
5.5 ,
:
5.6.
class MyTestl

{
public void Set( int x ){ Xl = x; }
private int XI;

}
class MyTest2

{
public
{ 2 =
public
{ 2 =

MyTest2( )
0; mtl = new MyTestl(); }
void Set( int x, int )
x; mtl.Set( ); }

// Private data:
private int
X 2;
private MyTestl mtl;

}
class main

{
public static int Main( )

{
MyTestl obi = new MyTestl();
MyTest2 ob2 = new MyTest2();
obi.Set(1 ); ob2 .Set(2,3);
return 0 ;

}
MyTestl,
MyTest2 mtl . , MyTest2
MyTestl ( ). -

118

_____________________________________________________________________ 5

UML
:
M yTestl
-XI: int

MyTest2
- X2: int
- mtl: MyTestl
+Set( x : int, : int): void
+MyTest2()

+ Set( x : int): void

. 5.2.

:
. , UML- . 5.2 ,
MyTest2 MyTestl.
, UML
.
5.6, MyTest2
TnnaMyTestl, mtl. ,
MyTest2
, ( , )
MyTestl (
). (classes
aggregation).
UML
- ,
(. . 5.3).
M yTestl
-XI: int
+ S e t(x :in t): void

MyTest2
- X2: int
- mtl: MyTestl
+Set( x : int, : int): void
+MyTest2()___________

. 5.3.

. 5.3 , MyTest2 ,
MyTestl - .
,
.

(nested class):

#: , , ,

119

class MyTest2

{
public
{ X2 =
public
{ X2 =

MyTest2( )
0; mtl = new MyTestl(); }
void Set( int x, int )
x; mtl.Set( ); }

// Data field of primitive type:


private int X2;
// Nested type:
private class MyTestl

{
public void Set( int x ){ Xl = x; }
private int XI;

}
// Data field of nested type:
private MyTestl mtl;

}
class main

{
public static int Main( )

{
//MyTest2.MyTestl obi = new MyTest2.MyTestl();
MyTest2 ob2 = new MyTest2();
ob2 .Set(2,3);
return 0 ;

/*1*/

}
}
MyTestl private
MyTest2, ,

( /* 1 * / ).

(),
. ,
,
"has " (
).
.

120

(
) "is " (
). C# (
C++) ,
.
, (
) MyBase:
class MyBase

{
public MyBase( int x ){ XI = x; }
public void Set( int x ){ XI = x; }
public void Print( ){ Console.WriteLine("Xl={0}",XI); }
private int XI;

}
, MyBase
,
.

:
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int )
{ Set( x ); 2 = y; }
public void Print( )
{ base.Print(); Console.WriteLine( "X2={0}",2); }
private int 2;

}
M yDerived
( MyBase).
M yDerived
MyBase. , M yDerived
,
XI, ,
2, .
,
( , ).

#: , , ,

121

, S e t () M yDerived
S e t () MyBase ( -
, ),
P r i n t ()

base. b a se
.
p r i v a t e XI

private protected:
class MyBase

{
public MyBase( int x ){ XI = x; }
public void Set( int x ){ XI = x; }
public void Print( ){ Console.WriteLine("Xl={0}",XI); }
protected int XI;

}
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){ XI = x; X2 = y; }
public void Print( ){Console.WriteLine( "X1={0} X2={1}"/X1/X2);}
private int X 2 ;

}
M yDerived XI
(
S e t () P r i n t () ), -
.
, MyBase MyDe
r i v e d ( ) :
5.7.
using System;
class MyBase

{
public MyBase( int x ){ Xl = x; }
public void Set( int x ){ Xl = x; }
public void Print( ){ Console.WriteLine(X 1 = {0}", Xl) ; }
protected int Xl;

122

}
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int )( XI = x; X2 = y; }
public void Print( ){Console.WriteLine( "Xl={0}
X2={0}",X1,X2);}
private int X2;

}
class main

{
public static int Main( )

{
MyBase
obi = new MyBase(1);
MyDerived ob2 = new MyDerived(2,3);
obi.Set( 6 ); ob2.Set( 7, 8 );
obi.Print(); ob 2 .Print();
Console.ReadLine();
return

5.7
,
(. . 5.4).
cv fc\BOOKS\KUDITS\C#b<^l. s , , ,

si

XI =6
1= 7 2-8

<

. 5.4.

UML
(
, ) (. . 5.5).
M yB ase

. 5.5.

M yD erived

#: , , ,

23

. 5.5
(). ,
-
UML

. , ,

(. . 5.6).
MyBase
MyDerived
. 5.6.

,
UML
,
, .
,
,
. ,

(
), .
C#
:
MyBase ob2 = new MyDerived(2,3);
ob2.Set 7 );

new M yD erived(2 ,3 )
M yDerived, 2 MyBase,
.
ob2 . S e t (7) S e t ()
, . ,
7 ,
MyBase ( XI, . 5.7).

124

[_____________________________________________________________________ 5

5.3. :


#.
C# .
, 1,
,
2. ,
1 2, :
class 2

{
1 _1;

}
1 2
_1 1.
,
(),
( ).

.
,

,
.
, ,
,
,
, .
,
(
) :
class Basel { ... }
class Derivedl : Basel { ... }


,
( )

#: , , ,

125


( ) - MyBase MyDerived 5.7:
5.8.
using System;
class MyBase

{
public MyBaSe( int x ){ XI = x; }
public void Set( int x ){ Xl = x; }
public void Print( ){ Console.WriteLine("X1={0}",X1); }
protected int XI;

}
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){ Xl = x; X2 = y; }
public void Print( ){Console.WriteLine( "X1={0} X2={0}"/X1/X2);}
private int X2;

}
class main

{
public static int Main( )

{
MyBase obi = new MyBase(1);
MyBase ob2 = new MyDerived(2,3);
GenericFunc( obi, 8 );
GenericFunc( ob2, 9 );
Console.ReadLine();
return 0 ;

}
static void GenericFunc( MyBase ob, int val )

{
ob.Set( val );
ob.Print();

}
}
( )
GenericFunc (),
MyBase.

126

,
(. 5.7),
GenericFunc () ,
5.8.
,
MyBase [ ],
GenericFunc () :
MyBase[] obAr = new MyBase[2]{new MyBase(1),new MyDerived(2,3)};
GenericFunc( obAr[0], 8 ) ;
GenericFunc( obAr[l], 9 );


. , 5.8

(. . 5.7).

<1

. 5.7.

. 5.7 , -

, .
, , ,
. ,
GenericFunc ()
MyDerived, , Print ()
,
(
. 5.7).
( ).
C# ( C++)
:

#: , , ,

127

class MyBase
{
public MyBase( int x ){ XI = x; }
public void Set( int x ){ XI = x; }
public virtual void Print( ){Console.WriteLine("Xl={0}",XI) ;}
protected int XI;

}
class MyDerived : MyBase

(
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){ XI = x; X2 = y; }
public override void Print( )
{ Console.WriteLine( "X1={0} X2={0}"fXlfX2); }
private int X2;

Print () (
)
, MyBase,
virtual.
, .
, ,
,
override.
5.8
MyBase MyDerived
, GenericFunc ()
(. . 5.8).

. 5.8.

. 5.8 , GenericFunc ()

Print ().

128

: C++ (. [3]),

virtual, , C#
override.

,
.

, - ,

.

.
5.8
M yBase M y D e r iv e d ,
P r i n t ( ) , G e
n e r i c F u n c () ,
. ,
5.8 S e t () ,
,
. G e n e r ic F u n c ()
S e t () .
G e n e r ic F u n c () ,
S e t ( ) ,

. C# is:
static void GenericFunc( MyBase ob, int val )

{
if( ob is MyDerived )
((MyDerived)ob).Set( val, val+1 );
else
ob.Set( val );
ob.Print();

}
G e n e r ic F u n c ()
ob is MyDerived

#: , , ,

129

t r u e , ob
. (M y D e r iv e d )
ob M y D e r iv e d

(MyDerived)ob
, M y D e r iv e d , S e t ( )

((MyDerived)ob).Set( val, val+1

, , ,

.
,

,
:

5.9.
using System;
class MyBase

{
public MyBase( int x ){ XI = x ; }
public void Set( int x ){ XI = x ; }
public virtual void Print( ){Console.WriteLine("X1={0}",X1);}
protected int XI;

}
class MyDerived : MyBase

(
public MyDerived ( int x , int ) : base( x )
{ X2 = y; }
public void Set( int x , int ){ XI = x ; X2 = y; }
public override void Print( )
{ Console.WriteLine( "X1={0} X2={0}",X1,X2); }
private int X 2 ;

}
class main

(
public static int Main( )

{
MyBase[] obAr = new MyBase[2] { new MyBase(1),
new MyDerived(2,3) };
GenericFunc( obAr[0], 8 );

130

GenericFunc( obAr[1], 9 );
Console.ReadLine();
return 0;
}
static void GenericFunc( MyBase ob, int val )
{
if( ob is MyDerived )
((MyDerived)ob).Set( val, val+1 );
else
ob.Set( val );
ob.Print();
}
}
5.9 . 5.9.

. 5.9.

. 5.9 , MyDerived
GenericFunc () Set ()
, (
9 10, ).

5.4. FCL.
MyComplex
Microsoft NET Framework
, , FCL
(Framework Class Library). FCL
#, ,

.
,
Windows-
.

#: , , ,

131


- ,
,
.
FCL,
.
FCL,
,
Object, System (- ,
Object). ,
, ,
( Object)
. ,
C# .
, Array String,
C# (. . 3 . 4),
MyBase M y
Derived - Object,
UML- . 5.10.

. 5.10.


Microsoft Visual #,
Class View (. . 5.11).
. 5.11 ,
Set () Print (),
MyBase, ,
, ,
. -
Object.

132

1 P ro j2 2
% > File

Edit

View

Project

Build

Debug

lo o ls

Class View - Proj22

Window

~3

class MyBase

{
Bases and Interfaces
^ Object
Equais(object object)
Equals(object)
^ FinalizeO
GetHashCodeQ
GetTypeO
MemberwiseClone()
" Object()
ReferenceEquals(object, object)
- . ToStringO
MyBase(lnt)
Print*)
Set(int)

p ubl i c M y B a s e ( i n z

p ubl i c v i r t u a l v o i d P r i n t (
p r o t e c t e d int XI;
c lass M y D e r i v e d

Solution Ex...

: MyBase

{
pu b l i c M y D e r i v e d
{ X2 - y;

( int x,

>

publ i c v o i d S e t ( int x,
{ XI - x; X2 - y;

int

publ i c o v erride v o i d P r i n t (
{ C o n s o l e . W r i t e L i n e ( "Xl= {

li
5 Resource Vi... '

x ]{ XI

p ubl i c v o i d S e t ( int x ){ X

p r ivate

Ready

- fl x

Help

[^M yBase

_j
El

-|]

M icrosoft Visual C # .NET [d e s iy n ] - [ wcs]

" Class View

int X2;

_____ 1_____________________ I b T
Ln 57

Col5

C h2

. 5.11.


, ,

.
Microsoft Visual C# , ,
, C#
,

, ,
, ,
(. . 5.12).
. 5.12 ,
ob MyBase,
.
,
MyBase, , MyBase Obj ect.

#: , , ,

133

[ & P ro j22 - M icrosoft Visual C # NET [d esig n ] - [m a iru ts *]

r)5 File

Edit

View

Project

Build

Debug

Tools

W'ndow

Solution E x p l , 9 _ x ] I f jm a in
3

jq jx j
- & X

Help

j |d ^GenericFunc(MyBase ob,int val)


s t atic v o i d G e n e r i c F u n c ( MyBase ob,

[jtion 'Proj22l (1 project>|


ro j2 2
1 References
| ) main.cs

int val

- j

<
i f ( ob is M y D e r i v e d )

( ( M y D e r i v e d ) o b ) . S e t ( val, v a l + 1 ) ;
else
ob.

Equals
+ GetHashCode
GetType

ob
>
<1

S IR

>

iS s l^ c

Set "
ToString

j Ready

iL
Col 12

Ch 12

INS

. 5.12.


FCL O b je c t
Microsoft Visual C# (
Help | Contents... Help | Index... Help | Search...). ,
. 5.13 T o S tr i n g ().
I

P ro j22 - M icrosoft Visual C # NET [d e s ig n ] - [T o S trm g M ettiodJ

*/> File

Edit

Solu... * X |
S I J
fjtion Proj22' (1
P roj2Z
>->i Reference:
[f_] main.cs

View

Project

Bold

Debug

lo o ls

Window

.J n J x J
_ X

Help

v Y .NETFramework Ciass Library

O b j e c t .T o S t r i n g M e t h o d

zl

f c ]
u s i n g S y ste m ;
p u b l i c c l a s s Sam ple

{
v o i d Method. ( )

_J

/ / P r in ts o u t:

'S y s te m .O b je c t"
O b je c t = new O b je c t ;
C o n s o le -W r ite L in e t o . T o S t r i n g ( ) ) ;

I
1

. 5.13.

zl

<1

Ready

- ....*1

21

134

. 5.13 ,
#, .
, O b je c t
T o S trin g () .
T o S trin g ()
O b je c t,
, W rite L in e ()
C onsole.
T o S trin g ()
MyComplex,
5.4.
(override) MyComplex T o S trin g () ,
,
(
, Obj e c t).
T o S trin g ()
S tr in g B u ild e r ,
S y ste m .T e x t, . 4.5 . 4:
public override string ToString( )

{
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "Re = {0} Im = {l}\n, R, I );
return sb.ToString();

}
MyComplex
T o S trin g ( ) ,
P r i n t (). , ,
:
5.10.
using System;
using System.Text;
class MyComplex

{
// Constructors:
public MyComplex( ){ R = I = 0; }
public MyComplex( double r, double i ){ R = r; I = i; }
public MyComplex( MyComplex z ){ R = z.R; I = z .I; }

#: , , ,

135

// Methods:
public override string ToString( )

{
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "Re = {0} Im = {l}\n", R, I );
return sb.ToString();

}
static public double Abs( MyComplex z )
{ return z.Length; }
// Properties:
public double Length
{ get { return Math.Sqrt( R*R + 1*1 ); } }
public double Re { get{ return R; } set{ R = value;
public double Im { get{ return I; } set{ I = value;

} }
} }

// Overloaded operators:
static public MyComplex operator+ (MyComplex lOp,MyComplex rOp)
{ return new MyComplex( lOp.R + rOp.R, lOp.I + rOp.I ); }
static public MyComplex operator-(MyComplex lOp,MyComplex rOp)
{ return new MyComplex( lOp.R - rOp.R, lOp.I - rOp.I ); }
static public MyComplex operator*(MyComplex lOp,MyComplex rOp)

{
double Re = lOp.R * rOp.R - lOp.I
double Im = lOp.R * rOp.I + lOp.I
return new MyComplex( Re, Im );

}
// Private data fields:
private double R;
private double I;

}
class main

{
public static int Main( )

{
MyComplex z = new MyComplexO;
z .Re = 1 ; z .Im = 2 ;
Console.WriteLine("{0}", z );
Console.ReadLine();
return 0 ;
}
}

* rOp.I;
* rOp.R;

136

, ,
MyComplex Re Im,
ToString (),

, WriteLine () Console.
5.10 ,
(. . 5.14).

. 5.14.

Object, FCL,
, C#
object, .
Object

object,

. .

6.

. .

6.1.
,
C# .

.
(enumeration) ,
( class),
,
( ,
).
,
enum MyBooks

{
FirstBook,
SecondBook,
ThirdBook

M y
Books .FirstBook, MyBooks .SecondBook MyBooks .ThirdBook,
0, 1 2. ,
:
int = (int)SecondBook;

C#
, Object.
C#
:
6.1.
using System;
enum MyBooks

{
FirstBook,
SecondBook,
ThirdBook

138

}
class main

{
public static int Main( )

{
MyBooks mb = MyBooks.FirstBook;
Console.WriteLine( "{0}\n{l}"/ mb,

(int)mb );

mb = MyBooks.ThirdBook;
string str = mb.ToString( );
Console.WriteLine( "\n{0}", str );
Console.ReadLine();
return 0 ;

}
}
. 6.1.

. 6.1.

:
enum MyBooks

{
FirstBook = 50
SecondBook,
ThirdBook = FirstBook + 50

50
51
// 100
11
11

,
,
,
-,
switch ( switch C/C++,
cm

. [2 ]):

. .

139

using System;
enum MyBooks

{
FirstBook = 50,
SecondBook, //51
ThirdBook = FirstBook + 50 //100

}
class main

{
public static int Main( )

{
MyBooks mb = MyBooks.FirstBook;
TellAboutBooks( mb );
Console.ReadLine();
return 0;

}
private static void TellAboutBooks( MyBooks mb )

{
switch( mb )

{
case MyBooks.FirstBook:
Console.WriteLine( "The book is a FirstBook\n" );
break;
case MyBooks.SecondBook:
Console.WriteLine( "The book is a SecondBookXn" );
break;
case MyBooks.ThirdBook:
Console.WriteLine( "The book is a ThirdBookXn" );
break;

}
}
}
s w i tc h C# ,
b r e a k case- (
C/C++),
goto ( ).
g o to
s w i tc h c a s e :
switch( mb )

{
case MyBooks.FirstBook:
Console.WriteLine( "The book is a FirstBookXn" );

140

goto case MyBooks.SecondBook;


case MyBooks.SecondBook:
Console.WriteLine( "The book is a SecondBook\n" );
break;

}
s w i tc h g o to
d e f a u l t :
goto default;

d e f a u l t - s w i tc h ( ,
, ).
, C# s w i tc h
g o to C/C++
(., , [2]),
:
string str = "ABC";
if( str == "DEF" ) goto LABEL;
LABEL: str = "asdf";


LABEL. ,
( ) .

6.2. : , ,
. 3.5 , C# (
Array)
Sort (). , Sort ()
()
-.
( ),
? ,
, , Sort ()
Array - .
, (
),
, ,

. .

141


, ,
( ).

.
(Component Object Model)
,
, C++ (. [3]),

. ,
, ,
.
Microsoft NET Framework
C# (
)
#.
C# ,
:
class interface.
.
( ) (
, ) .
/, :
interface IMylnterface

{
int Funl( int k);
int Fun2( );

}
,
.
, - ,
, , ,
( #)
public/protected/private.

: C#
, public virtual .

142

C# ,
( ,
) (
, ),
:
class MyClass : IMylnterface

{
// Funl() Fun2()
// MyClass:
public int Funl( int k ){ return k; }
public int Fun2( ){ return Get(); }
// MyClass:
public MyClass( ) { data = 777; }
private int Get( ) { return ( 2 + data ); }
// MyClass:
private int data;

}
Funl () Fun2 (),
IMylnterface, ( public)
MyClass.

6.3,
, :
6.2.
using System;
interface IMylnterface

{
int Funl( int k);
int Fun2( );

}
class MyClass : IMylnterface

{
// Funl() Fun2()
// MyClass:
public int Funl( int k ){ return k; }
public int Fun2( ){ return Get(); }
// MyClass:
public MyClass( ) { data = 777; }
private int Get( ) { return ( 2 + data ); }

. .

143

// MyClass:
private int data;

}
class main

{
public static int Main( )

{
MyClass ob = new MyClassO;
// Funl() Fun2()
// MyClass:
Console.WriteLine( "{0}", ob.Tunl( 5 ) );
Console.WriteLine( "{0}", ob.Fun2() );
Console.ReadLine();
return 0 ;

}
}
6.2 ,
F u n l () Fun2 () ob My
C la s s , .

: , :
6.3.
using System;
interface IMylnterface

{
int Funl( int k);
int Fun2( );

}
class MyClass : IMylnterface

{
//
/ / Fun2()
int IMylnterface.Funl(
int IMylnterface.Fun2(

MyClass Funl()
IMylnterfacel:
int k ){ return k; }
/*1*/
){ return Get(); }
/*2*/

// MyClass:
public MyClass( ) { data = 777; }
private int Get( ) { return ( 2 + data ); }

144

// MyClass:
private int data;

}
class main

{
public static int Main( )

{
MyClass ob = new MyClass();
// Funl()
//
Console.WriteLine( "{0}",
Console.WriteLine( "{0}",

Fun2()
IMylnterface:
((IMylnterface)ob).Funl( 5 ) )
((IMylnterface)ob) .Fun2() );

Console.ReadLine();
return 0;

}
}
/ * 1 * / /* 2 * / :
(
),
( ).
, MyClass Funl () Fun2 ()
, MyCla
ss .
6.3 ,
,
( IMylnterface,
, Funl () Fun2 () ).
, , :
IMylnterface rlnt = ob;
Console.WriteLine( "{0}", rInt.Funl( 5 ) );

/*3*/
/*4*/

( /* 3 * / ) ,
( /* 4 * /) ,
F u n l ().
,
( ) ,
/ * 3 * /
.
(
) a s:

. .

145

IMylnterface rlnt = ob as IMylnterface;


if( rlnt != null)
Console.WriteLine( "{0}", rlnt.FunK 5 ) )

, as, ,
,
null. , .

6.3. IComparable
,
, ,
Sort () Array ( #)
,
, -. - Sort ()
CompareTo (),
IComparable.
Array, IComparable
FCL System. ,
( FCL)
, Sort ()
Array,
FCL IComparable.
, ICompa
rable, FCL
()
CompareTo () (. . 6.2).
ProJ2 3 - M icrosoft Visual C# [<k*grt]

E ile
j] -

E d it y e w
H

P r o je c t g u ild
D ebug

D e b u g lo o ls
- J}

W ndow

(H elp

_ X

02 .N ET Framework Class Ubrary

IC o m p a r a b le M e th o d s
The m ethods of the I C o m p a r a b le interface are listed h ere. For a com plete list
of I C o m p a r a b le interface m em bers, see the IC om parable Members topic.
P u b lic M e th o d s
^ C om p a reT o

.i L L j J

_ _ rr
Ready

. 6.2.

C o m p a re s the current instance with


another object of the sam e typ e.

Supported by the .NET C om p a ct


Fram ew ork.

zl

146

. 6.2 , Mi
crosoft Visual C#
IComparable. CompareTo
,
,
CompareTo (). (. . 6.3).
; Proj23 - M icrosoft V b u d C # .NET [ d e s n ] - [C om ^oreTo M e th o d )
File

Edit

View

Project

Build

Debug

Tools

Window

deip

j n |x j
-fix

?x
l -W f T Framework C/ass Library
I C o m p a r a b le . C o m p a r e T o M e t h o d
S
xi 'ProjZ! R e tu rn V a lu e
0 ]23 J
A 3 2 -b it signed in te g e r th a t in d ica te s th e re la tiv e o rd e r o f th e co m p a ra n d s . The re tu rn
1) Refer j va lu e has th e se m e a n in g s :
) 'nain.c
V a lu e
M e a n in g
Less th a n zero

A il
\ G re a te r th a n
LiL
~ T

T h is in sta nce is less th a n obj.


This in sta nce is e q u al to obj.

Z e ro
zero

This in sta nce is g re a te r th a n obj.

Ready

. 6.3.


, .
( . 6.3):
, ,
- , ,
( ) .
IComparable, ,
MyBase . 5.3 (. 5.9).
6.4.
using System;
class MyBase : IComparable

{
// Interface IComparable method:
public int CompareTo( object ob )

{
if( Xl > ((MyBase)ob).Xl ) return 1;

. .

147

else i f ( XI == ((MyBase)ob).XI ) return 0;


else return -1 ;

}
public MyBase( int x ){ XI = x; }
public void Set( int x ){ XI = x; }
public virtual void Print( ){Console.WriteLine("X1={0}",XI);}
protected int XI;

}
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){ XI = ; X2 = y; }
public override void Print( )
{ Console.WriteLine( "X1={0} X2={0}",XI,X2); }
private int X2;

}
class main

{
public static int Main( )

{
MyBase[] obAr = new MyBase[3] { new MyBase(6 ),
new MyDerived(2,3),
new MyDerived(9,1)
};
// obAr:
Array.Sort( obAr );
// :
for( int i = 0; i < obAr.Length; ++i )
obAr[i].Print();
Console.ReadLine();
return 0 ;

}
}
6.4. , object
C# j ect, CompareTo ()
, . , ,
, ,
,

148

CompareTo ()
ob ,
MyBase MyDerived, ?
,
obAr. 6.4
MyBase, IComparable,
MyDerived, IComparable
, ,
.
6.4,
(. . 6.4).

. 6.4.

, .6.4,
. - Sort ()
Array
MyBase MyDerived. -
XI.
,
CompareTo():
// " ":
public int CompareTo( object ob )

{
if( XI > ((MyBase)ob).XI ) return -1;
else if( Xl == ((MyBase)ob).Xl ) return 0;
else return 1;

>
obAr (. . 6.5).
, ,
,

: ,

. .

c'x E BOOKS KUDXTS\Ci ^ t o k \ T r - > ? 1 Urn ttefMI


X I=9 X2 9
XI =6
XI =2 X22

149

JLOJx ]

HI
s i

__________ dJU J

<

. 6.5.

- ( ).
, .

6.4.

"MyBase - MyDerived
MyBase
IComparable. Sort ()
Array M y
Base [].

Com
pareTo () MyBase MyDerived
,
>, <, =- ! = (
C# . 2.4):
6.5.
using System;
class MyBase : IComparable

{
// Interface IComparable method:
public int CompareTo( object ob )

{
if( Xl > ((MyBase)ob).Xl ) return 1;
else if( XI == ((MyBase)ob).Xl ) return 0;
else return -1;

// napaiw:
static public bool operator>( MyBase obi, MyBase ob2 )

{
int res = o b i .CompareTo( ob2 );

150

return ( res > 0 ) ? true : false;

}
static public bool operator<( MyBase obi, MyBase ob2 )

{
int res = obi.CompareTo( ob2 );
return ( res < 0 ) ? true : false;

}
static public bool operator==( MyBase obi, MyBase ob2 )

{
int res = obi.CompareTo( ob2 );
return ( res == 0 ) ? true : false;

}
static public bool operator!=( MyBase obi, MyBase ob2 )

{
int res = obi.CompareTo( ob2 );
return ( res != 0 ) ? true : false;

}
// :
public MyBase( int x ){ Xl = x; }
public void Set( int x ){ XI = x;
}
public virtual void Print( ){Console.WriteLine("X1 = {0}",XI);}
// :
protected int XI;

}
class MyDerived : MyBase

{
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){XI = x; X2 = y; }
public override void Print( )
{ Console.WriteLine( MX1={0} X2={0}",X1,X2); }
private int X2;

}
class main

{
public static int Main( )

{
MyDerived obi = new MyDerived(2,3);
MyDerived ob2 = new MyDerived(2,1);

. .

151

// 1. ():
int res = obi.CompareTo( ob2 );
if( res > 0 )
Console.WriteLine( "obi ob2" );
else if( res == 0 )
Console.WriteLine( "obi ob2 " );
else
Console.WriteLine( "obi ob2" );
// 2. :
if( obi > ob2 )
Console.WriteLine( "obi ob2" );
else if( obi == ob2 )
Console.WriteLine( "obi ob2 " );
else
Console.WriteLine( "obi ob2" );
Console.ReadLine();
return 0 ;

}
}
6.5 ,
,
CompareTo().

6.5 ( Main () main)


2 MyDerived
( CompareTo ()
), , ,
(. . 6.6).

. 6.6.

,
:
if( obi == ob2 )

152

, ,
o b i 2, ,
.

,
() ,
.
(
).

(. . 2.3).
C++,
.
. ,
C# , - ,
C# (
, , ).
FCL, , .


C lo n e () ( ).
C#
.
,
#,
, ,
FCL ICloneable.
I C lo n e a b le (
S ystem ) C lo n e ().
:
6.6.
using System;
class MyBase : ICloneable

{
// Interface ICloneable method:
public virtual object Clone( )
{ return new MyBase( XI ); }

. .

153

// :
public MyBase( int ){ Xl = ; }
public void Set( int x ){ XI = x; }
public virtual void Print( ){Console.WriteLine("X1={0}",XI) ;}
// :
protected int Xl;

}
class MyDerived : MyBase

{
// Interface ICloneable method:
public override object Clone( )
{ return new MyDerived( Xl, X2 ); }
// :
public MyDerived ( int x, int ) : base( x )
{ X2 = y; }
public void Set( int x, int ){ Xl = x; X2 = y; }
public override void Print( )
{ Console.WriteLine( "Xl={0} X2={0}",Xl,X2); }
// :
private int X2;

}
class main

{
public static int Main( )

{
MyBase
MyDerived

obMBl = new MyBase(1),


obMB2;
obMDl = new MyDerived(2,3), obMD2;

// Cloning:
obMB2 = (MyBase)( obMBl.Clone() );
obMD2 = (MyDerived)( obMDl.Clone() );
Console.ReadLine();
return 0 ;

}
}


MyBase M yDerived 1(),
IC lo n e a b le ,
virtual ( ,
- ),

154


o v e r r i d e .
,
, .
C lone () MyBase MyDerived" ,
(. . 5.3), 6.6
:
obMB2 = (MyBase)( obMBl.Clone() );
obMD2 = (MyDerived)( obMDl.Clone() );

C lone () o b j e c t (
O b je ct),
MyBase MyDerived, (,
,
. . 5.3).
, ,
(, , . . 2.3 . 3.4),
(
shallow ), (deep
) - .

6.5.
FCL
.
( C++
). ,
#,
.

C# ,
( ),

. ,
, ( ) ,
.

FCL A rra y L is t.

155

. .

, ,
S y s te m .C o lle c tio n s ,
using System . C o lle c ti o n s .
,
A rra y L is t:
6.7.
using System;
using System.Collections;
class main

{
public static int Main( )

{
// arL :
ArrayList arL = new ArrayList();
// arL :

a r L .Add ( 3 );
arL .A d d ( -5 ); .
a r L .Add( 8 );
// :
MyPrint( arL );
// :
// 1. -5 0.
// 2. .
arL.RemoveAt( 0 );
arL.Remove( -5 );
arL[0] = 77;
/*1*/
MyPrint( arL );
Console.ReadLine();
return 0 ;

}
static void MyPrint( ArrayList ar )

{
Console.WriteLine( "\nB " +
" {0 } .", ar.Count );
for( int i = 0 ; i < ar.Count; ++i )
Console.WriteLine( "{0}", a r [i] );
}

/*2*/

1 5 6 _____________________________________________________________________ 6

6.7 , - arL
ArrayList :
A rra y L ist

arL

= new

A r r a y L i s t ();

,
Add (). a r L . C o u n t
.

- ArrayList, ( /
* 2 * / 6.7), ( / * 1 * / 6.7).
Remove () RemoveAt () ,

, -
, .
. 6.7 6.7.

3 .

\ < 1 .

:
. 6.7.

, . 6.7,
6.7:
( ) ,
77.
( ,
) C#
, , CLR
,
. , ,

(, ) (
) IEnumerator (

. .

157

System.Collections), GetEnumerator ():


static void MyPrint( ArrayList ar )

{
System.Collections.IEnumerator enumer = ar.GetEnumerator();
Console.WriteLine( "\nB " +
" {0 } .", ar.Count );
whi le ( enumer.MoveNexjt () )
Console.WriteLine( "{0}", enumer.Current );

}
MyPrint () ,
enumer
IEnumerator. . ,
MoveNext () ( enumer)
, "
enumer.Current.

#, . 3 ,
.
,
, - '
.
,
ArrayList, :
6.8.
using System;
using System.Collections;
class main

{
public static int Main( )

{
// arL :
ArrayList arL = new ArrayList();
// arL :
arL.Add( "" );
arL.Add( "-" );
arL.Add( "" );

158

// :

arL.Sort();
// :

for( int i = 0; i < arL.Count; ++i )


Console.WriteLine( " {0}", arL[i] );
Console.ReadLine();
return 0 ;

}
}
6.8.
. 6.8.

E:\BOOKS\KUDITS\,c * b , , k K * i >

-_________________________ I

-In l

zi

. 6.8.

. 6.8 , Sort () ArrayList


.
AraryList
, ,
IComparable (. . 6.3).
,
, Add ()
object, , object
( ),

obj ect, :
6.9.
using System;
using System.Collections;
class main

{
public static int Main( )

. .

159

{
// arL :
ArrayList arL = new ArrayList();
// arL :
arL.Add( "" );
arL.Ad d ( 66 );
arL.Add( 'A' );
// :
//arL.Sort();
/*!*/
// :
for( int i = 0; i < arL.Count; ++i )
Console.WriteLine( "{0}", arL[i] );
Console.ReadLine();
return 0 ;

}
}
6.9 , arL ArrayList
Add () ", 66
''.

(. . 6.9).

. 6.9.

, , Sort ()
arL -
(
/ * 1 * / 6.9).
ArrayL
ist - ,
- (wrapper class),
.

160

- MyStrArList, :
6.10.
using System;
using System.Collections;
class MyStringArList : IEnumerable

{
// IEnumerator:
public IEnumerator GetEnumerator( )
{ return arList.GetEnumerator(); }
// MyStringArList:
public MyStringArList( ) { arList = new ArrayList(); }
public void Add( string str ) { arList.Add( str ); }
public void Remove( int i ) { arList.Remove( i); }
public void Sort( ){ arList.Sort(); }
// Count ( ):
public int Count
{ get { return arList.Count; } }
// - ArrayList:
private ArrayList arList;

}
class main

{
public static int Main( )

{
// strArL " ":
MyStringArList strArL = new MyStringArList();
// strArL :
strArL.Add( "" );
strArL.Add( "Los Angeles" );
//StrArL.Add( 'A' );
/*1*/
MylteratePrint( strArL );
// strArL:
StrArL.Sort();
MylteratePrint( strArL );
Console.ReadLine();
return 0 ;
}

. .

161

static void MylteratePrint( MyStringArList ar )

{
System.Collections.IEnumerator enumer = ar.GetEnumerator();
Console.WriteLine( "\nB " +
" {0} .", ar.Count );
w hile( enumer.MoveNext() )
Console.WriteLine( "{0}", enumer.Current );

}
}
MyStringArList Add ()
string, object, -
- (
/* 1 * / 6.10).
6.10 . 6.10.

. 6.10.

- MyStringArList Array
List , . 6.10
List, .
, - .

FCL ArrayList.
[6], ,
Microsoft Visual #.

7.

7.1. . / .
/
,
. .
,
.
Windows,
, ,

. , , ,
.
#, [1],
,
, ,
.
,
, .
[1],
( )
/.
f o p en ():
#include <stdio.h>
FILE* pf = fopen( "FileName", "rb" );

C#
FCL,
,
. , ,
, FileStream (
System.IO):

163

using System.10;
FileStream fs = new FileStream(

"FileName", FileMode.Open,
FileAccess.Read );

( ,
#) ( )
,
,
.
, fopen()
FileStream, , ,
, FILE (
), FileStream (
#).
"FileName" (
- ).
. , fopen()
Mrb" , ,
( - read, ), , (b - binary,
)
. FileStream
FileMode.Open FileAccess .Read (
FileMode FileAccess, Sys
tem. 1 0 )
,

FileStream .
/
.
f c l o s e () :
fclose( pf );

Close () FileStream:
fs.Close();

, , C# ,
. #.
,
. ,

164

CLR
. -
F i l e S t r e a m
ExistsQ File:
if( File.Exists( "FileName" ) )

{
...// FileStream

}
,
.
.
, ,
. , ,
( f a l s e
Exists () File).
, ( FileMode.Create FileAccess .Write) ',
,
:
7.1.
using System.10;
class main

{
public static int Main( )

{
FileStream fs = new FileStream( "MyFileName", FileMode.Create,
FileAccess.Write );
fs.Close();
return 0 ;

}
}
7.1 MyFileName,
.
7.1 ,
, Microsoft Visual C# F5
(. . 1.2). ,
,
. 7.1.

165

____________
File

Edit

View

Favorites

Toois

Search
Address

_ bin
w J Debug

Edit

View

Favortes

Name
i""1PrQiFileOpen.exe '
ProjFileOpen.pdb

. My Computer

jo ,* ]
Tools

Search

Folders

< z i - > r i \ _____ I


2 objects (Disk I 27.5 KB

File

Help

E:\BOOK5\KITS\C#Book\Tests,j

Folders

i ..

*: '. .

Go

Help
Folders

Address | . ^ ok\Tests\Pro)FileOpen\bin\Debiig ^
X

Folders
| J

jJ k

j Name ^

J1

j ^ 1 Go

~~

bin
I QPrqjFiIeOpen.exe :
__ t
ProjFileOpen.pdb
Debug
MyFileName

-4

3 objects (Disk! 27.5 KB

if J
My Computer

. 7.1.

. 7.1 () Debug
, . 7.1 () - . ,
MyFileName,
,
ProjFileOpen.exe.
: ,

,
.

( int double), . 7.3 -
.
,
FileStream - byte.
( )
, 0 255,
( 8 ).
.
. ,
.
(, 512 ).
(
) FileStream WriteByteQ:

166

_____________________________________________________________________ 7

7.2.
using System.10;
class main

{
public static int Main( )

{
FileStream fs = new FileStream( "MyFileName", FileMode.Create,
FileAccess.Write );
for( int i = 0; i < 256; ++i )
fs.WriteByte( (byte)i );
fs.Close();
return 0 ;

}
}
7.2 ,

i i n t b y t e ( ).
7.2,
Debug MyFileName (. . 7.1, ),
Microsoft
Visual #.
-
Open Open File
Open with..., Open With (. . 7.2).
Open With - MyFileName
Select a program to open:
Source Code (Text) Editor (Default)
Source Code (Text) Editor With Encoding
HTML/XML Editor
HTML/XML Editor with Encoding
XML Schema Edi r

zi

Open

A dd...

Set as default

Help

Resource Editor

zl
Close

. 12.

167

. 7.2, Open With ()


Binary Editor Open.
Microsoft Visual C# My
FileName (. . 7.3).
Jn Jx j

P ro jF le O p e n - M icrosoft Visual C # .NET [d e s ig n ] [M y F fle fta m e ]


&

File

Edit

View

00000000
5oluti3

pp
Q
a

Id

00000010
00000020
00000030
00000040
00000050
00000060
00000070
00000080
00000090
OOOOOOaO
OOOOOObO
OOOOOOcO
OOOOOOdO
OOOOOOeO
OOOOOOfO

00
10
20
30
40
50
60
70
80
90
AO
BO
CO
DO
EO
FO

Project

01
11
21
31
41
51
61
71
81
91
A1
B1
Cl
D1
HI
FI

02
12
22
32
42
52
62
72
82
92
A2
B2
C2
D2
E2
F2

Build

03
13
23
33
43
53
63
73
83
93
A3
B3
C3
D3
3
F3

04
14
24
34
44
54
64
74
84
94
A4
B4
C4
D4
E4
F4

Debug

05
15
25
35
45
55
65
75
85
95
A5
B5
CS
D5
E5
F5

06
16
26
36
46
56
66
76
86
96
A6
B6
C6
D6
E6
F6

Tools

07
17
27
37
47
57
67
77
87
97
A7
B7
C7
D7
E7
F7

08
18
28
38
48
58
68
78
88
98
A8
B8
C8
D8
E8
F8

Window

09
19
29
39
49
59
69
79
89
99
A9
B9
C9
D9
E9
F9

OA
1A
2A

4A
SA
6A
7A
8A
9A
AA
BA
CA
DA
EA
FA

Help

OB
IB
2B

4B
5B
6B
7B
8B
9B
AB
BB

DB
EB
FB

1C
2C
3C
4C
5C
6C
7C
8C
9C
AC
BC
CC
CC
EC
FC

OD
ID
2D
3D
4D
5D
6D
7D
8D
9D
AD
BD
CD
DD
ED
FD

OE
IE
2E
3E
4E
5E
6E
7E
8E
9E
AE
BE
CE
DE
EE
FE

OF
IF
2F
3F
4F
5F
6F
7F
8F
9F
AF
BF
CF
DF
EF
FF

ff X

0 1 2 3 4 5 6 7 8 9 :;<>:
QABCDEFGHIJKLHNC

PQRSTUVtJXYZ [ \ ] _
1abcdefghijklumt
p q r stu w x y z {I)~

l l_____

[R e a d y

I O ff 0x00000000

Len 0x00000000

'owj .

. 7.3.

. 7.3 , ,
, 0 (00
) FF (
255).
MyFileName,
7.2, -,
:
7.3.

using System;
using System.10;
class main
{
public static int Main( )
{
if( File.Exists( "MyFileName" ) )

168

{
F ile S tre a m

fs

= new F il e S t r e a m (

"M y F ile N a m e ", F i l e M o d e .Open,


F i l e A c c e s s .R e a d );

f o r ( i n t i = 0; i < 25 6; + + i )
C o n s o le .W r ite L in e ( "{0} b yte in the
i,
f s . R e a d B y t e ()

f ile
);

is

{I}",

f s . C l o s e ();

}
e lse
C o n so le .W rite L in e (

"N o

f ile

in

the

d isk "

);

C o n s o l e .R e a d L in e ();
r e t u r n 0;

}
}
,
MyFileName
, Exists ()
File .
MyFileName
7.3 ReadByte ()
FileStream.

7.3 ,
(. . 7.4).
i - 1

. 7.4.

. 7.3 . 7.4 MyFileName


.

169


,
7.2 7.3,
. ,
, FileMode.OpenOrCreate FileAc
cess .ReadWrite:
7.4.
using System;
using System.10;
class main

{
public static int Main( )

{
// , :
FileStream fs = new FileStream( "MyFileName",
FileMode.OpenOrCreate,
FileAccess.ReadWrite );
// () :
for( int i = 0; i < 256; ++i )
fs.WriteByte( (byte)i );

/ * ----------------------------------------------------------------------- */
//
// :
fs.Position = 0 ;

/ * ----------------------------------------------------------------------- */

// 256 :
for( int i = 0; i < 256; ++i )
Console.WriteLine( "{0} byte in the file is {1}",
i, fs.ReadByte() );
// :
fs.Close();
Console.ReadLine();
return 0 ;

FileMode.OpenOrCreate FileAc
cess .ReadWrite (
) ,

( )
.
,
(
):
fs.Position = 0 ;

Position
FileStream. .

. , ,
, (
):
int = 0 ;
while( fs.Position != fs.Length )

{
Console.WriteLine( "{0} byte in the file is {1}",
k, fs.ReadByte() );
+ +k;

}
Length () .

, f s . Length.
.

7.2.
WriteByte () ReadByte () FileStream,
, /
int double.
BinaryWriter BinaryReader,
Write () ( ), Readlnt32 () ReadDou () .
Write(), Readlnt32() (
int) ReadDouble () ( dou
ble) :

171

7.5.
using System;
using System.10;
class main

{
public static int Main( )

{
int
int

m = 5; double d = 8 .8 8 ;
iRes =0;
double dRes = 0;

/*------------file writing ------------------- */


FileStream fsW = new FileStream( "MyFileName",
FileMode.Create,
FileAccess.Write );
BinaryWriter bw = new BinaryWriter( fsW );
bw.Write( m );
bw.Write( d );
bw.Close();
fsW.Close();
file reading --------------------*/
/*------------i f ( File.Exists( "MyFileName" ) )

{
FileStream fsR = new FileStream( "MyFileName",
FileMode.Open,
FileAccess.Read );
BinaryReader br = new BinaryReader( fsR );
iRes = br.Readlnt32();
dRes = br.ReadDouble();
br.Close();
fsR.Close();

}
Console.WriteLine( "iRes is {0}; dRes is {1}, iRes, dRes );
Console.ReadLine();
return 0 ;

}
}
7.5 MyFileName ,
f sW FileStream
. bw BinaryWriter:
BinaryWriter bw = new BinaryWriter( fsW );

172

Write () BinaryWriter
d.
Close ().
, .
MyFileName ( ,
, )
BinaryReader Readlnt32 () ReadDouble () iRes
dRes, :
iRes = br.Readlnt32();
dRes = br.ReadDouble();
, , iRes dRes
Write
Line () Console (. . 7.5).

. 7.5.

. 7.5 , MyFileName
,
.
7.5 ,
, :
7.6.
using System;
using System.10;
class main

{
public static int Main( )

{
i n t [] iArr - {5,6,7}; double[] dArr = {8.88,9.9,1};
in t [] iArrRes = new int[3];
double[] dArrRes = new double[3];
int i ;


/*-----------file writing ------------------ */
FileStream fsW = new FileStream( "MyFileName",
FileMode.Create,
FileAccess.Write );
BinaryWriter bw = new BinaryWriter( fsW );
for( i = 0 ;
bw.Write(
for( i = 0;
bw.Write(

i < iArr.Length; ++i )


iArr[i] );
i < dArr.Length; ++i )
dArr[i] );

bw.Close();
fsW.Close();
/*-----------file reading ------------------ */
if( File.Exists( "MyFileName" ) )

{
FileStream fsR = new FileStream( "MyFileName",
FileMode.Open,
FileAccess.Read );
BinaryReader br = new BinaryReader( fsR );
for( i = 0; i < iArrRes.Length; ++i )
iArrRes[i] = br.Readlnt32();
for( i = 0; i < dArrRes.Length; ++i )
dArrRes[i] = b r .ReadDouble();
br.Close();
fsR.Close();

}
for( i = 0; i < iArrRes.Length; ++i )
Console.WriteLine( "iArrRes[{0}] = {1}; " +
"dArrRes[{0}] = {2}",
i, iArrRes[i], dArrRes[i] );
Console.ReadLine();
return 0 ;

}
}
7.6 iArr dArr, :
int [] iArr = {5,6,7},* doublet] dArr = {8.88,9.9,1};

MyFileName:

173

174
for( i = 0;
bw.Write(
for( i = 0;
bw.Write(

i < iArr.Length; ++i )


iArr[i] );
i < dArr.Length; ++i )
dArr[i] );


MyFileName - iArrRes
dArrRes:
for( i = 0; i < iArrRes.Length; ++i )
iArrRes[i] = b r .Readlnt32();
for( i = 0; i < dArrRes.Length; ++i )
dArrRes[i] = br.ReadDouble();

,
iArrRes dArrRes: 7.6 iArr dArr,
MyFileName,
iArrRes dArrRes, MyFileName ,
. - ,
-, 7.6
( - ),
,
.
MyFileName 7.6
. 7.6.

. 7.6.

. 7.6 , ,
.
7.5 7.6
. , ,
, .
, ?

175


,
i n t d o u b le :
7.7.
using System;
using System.10;
class main

{
public static int Main( )

{
int[] iArr = {5,6,7};
doublet] iArrRes = new double[8 ];
int i;
file writing ------------------- */
/*-----------FileStream fsW = new FileStream( "MyFileName",
FileMode.Create,
FileAccess.Write );
BinaryWriter bw = new BinaryWriter( fsW );
for( i = 0; i < iArr.Length; ++i )
bw.Write( iArr[i] );
bw.Close();
fsW.Close();
file reading ------------------- */
/*-----------if( File.Exists( "MyFileName" ) )

{
FileStream fsR = new FileStream( "MyFileName",
FileMode.Open,
FileAccess.Read );
BinaryReader br = new BinaryReader( fsR );
i = 0;
while( br.PeekChar() != -1 && i < 8 )

{
iArrRes[i] = b r .Readlnt32();
i++;

}
br.Close();
fsR.Close();
}

176

for( i = 0; i < iArrRes.Length; ++i )


Console.WriteLine( "iArrRes[{0}] = {1}",
i , iArrRes[i ] ) ;
Console.ReadLine();
return 0;

}
}
MyFileName
iA r r i n t .
.
- , ,
( ). ,
R e a d ln t3 2 () ,
PeekC har ():
w h ile( b r .PeekChar() != -1 && i < 8 )

{
iArrRes[i] = br.Readlnt32();

i+ + ;
PeekC har () -1 , My
FileName ,
R ea d ln t3 2 ().
PeekChar () -1,
( - i < 8,
iA rrR es).
7.7 . 7.7.

. 7.7.

177

. 7.7 , iA rrR e s ,
, MyFileName
.
,
, P eekC har (), .

7.3.

, ( ,
) (
), , , ,

( ).

StreamWriter StreamReader (
BinaryWriter BinaryReader).
.
Write () ReadLine ()
StreamWriter StreamReader:
7.8.
using System;
using System.10;
class main

{
public static int Main( )

{
string strl = "Hello\n", str2 = ", world! \n";
string Strl, Str2;
file writing ------------------ */
/*-----------FileStream fsW = new FileStream( "MyFileName",
FileMode.Create,
FileAccess.Write );
StreamWriter sw = new StreamWriter( fsW );
sw.Write( strl );
sw.Write( str2 );
sw.Close() ;
fsW.Close();

178

file reading
FileStream fsR = new FileStream( "MyFileName",
FileMode.Open,
FileAccess.Read );
StreamReader sr = new StreamReader( fsR );
Strl = sr.ReadLine();
Str2 = sr.ReadLine();
sr.Close() ;
fsR. Close();
Console.WriteLine( "Strl = {0}\nStr2 = {l}\n";
Strl, Str2 );
Console.ReadLine();
return 0 ;

}
}
7.8 ,
,
.
( #) s t r l s t r 2
\ (. . 4.1):
string strl = "Hello\n", str2 = ", world!\n";


7.8 C# - Strl Str2
(. . 7.8).

. 7.8.

\
s t r l s t r 2
string strl = "Hello", str2 = ", world!";

MyFileName

179

Strl = sr.ReadLine();
Str2 = sr.ReadLine();

S t r l S tr 2
(. . 7.9).
' fc\B O O K S \K iro iT S \C # d u o k \T ests^l*rojT<

S t r l H e l l o , w o rld !
S tr2 *

. 7.9.

, ReadLine ()
\ .
\ ,
.

. ,
,
.
, "Note
pad" ("" Windows)
MyTextFile (. . 7.10).

M yT extF ile - N otepad

-in i x|

File Edit Format View Help


MOSCOW
Los A n g e le s
M a d r id

. 7.10.


MyFileName :

180
7.9.
using System;
using System.10;
class main

{
public static int Main( )

{
string Str;
/*-----------file reading ------------------ */
if( File.Exists( "MyTextFile" ) )

{
FileStream fsR = new FileStream( "MyTextFile",
FileMode.Open,
FileAccess.Read );
StreamReader sr = new StreamReader( fsR ) ;
while( ( Str = sr.ReadLine() ) != null )
Console.WriteLine( "Str = {0}", Str );
sr.Close();
fsR.Close();

}
Console.ReadLine();
return 0 ;

}
}
7.9, ,
, . 7.11.

. 7.11.

. 7.11 . 7.10, , 7.9


ReadLine () Notepad (
) MyTextFile .

181

-
ReadLineQ null,
while( ( Str = sr.ReadLine() ) != null )
Console.WriteLine( "Str = {0}", Str );

,
MyTextFile.
\ .

( [2]), , ,
Notepad - \ \
( ).
,
W r ite (),
( -
), WriteLineO.
.

, 7.8,

Microsoft NET Framework,
:
7.10.
using System;
using System.10;
class main

{
public static int Main( )

{
string strl = "Hello", str2 = ", !";
string Strl, Str2;
/*-----------file writing ------------------ */
FileStream fsW = new FileStream( "MyFileName",
FileMode.Create,
FileAccess.Write );
StreamWriter sw = new StreamWriter( fsW );
sw.WriteLine( strl );
sw.WriteLine( str2 );
sw.Close();
fsW.Close();

182

/*-----------file reading -------------------*/


FileStream fsR = new FileStream( "MyFileName",
Fi1eMode.Open,
FileAccess.Read );
StreamReader sr = new StreamReader( fsR );
Strl = sr.ReadLine();
Str2 = sr.ReadLine();
sr.Close();
fsR.Close();
Console.WriteLine( "Strl = (0}\nStr2 =
Console.ReadLine();
return 0 ;

{ l } \ n ,

Strl, Str2 );

}
}
7.10 . 7.12.
E:\BOOKS\KUDITS CWu)k Test> > .|>-14: U > I
S t r l H e llo
S t *2 ?

jjQjJSl

_______

______

2)

. 7.12.

. 7.12 , 7.10
,
\ ( W r ite L in e ()
).

7.4. -

- ,
. ,

Notepad ().

:
(
) , . 7.13. ,
Telephons.txt.

T e M w m tx t - W e p i J
File dit Format View Help
1234567

1234568

123684 5

3214 567

5555555

3333333

1111111

2222222

183

JSjxJ

--

J
. 7.13.

txt
,
.
,
Telephons.txt UTF-8 (. . 7.14).
2Jx]

Save As
Save ) | Debug

184



,
. ,
,
? ,
Telephons.txt
, .
,
,
, :
7.11.
using System;
using System.10;
class main

{
public static int Main( )

{
string Name, PhoneNum, Str;
int ind;
Console.Write( " : " );
Name = Console.ReadLine();
file reading ------------ */
/*-----------if( File.Exists( "Telephons.txt" ) )

{
FileStream fsR = new FileStream( "Telephons.txt",
FileMode.Open,
FileAccess.Read );
StreamReader sr = new StreamReader( fsR );
while( ( Str = sr.ReadLine() ) != null )

{
ind = Str.IndexOf( Name, 0 );
iff ind != - 1 )

{
Console.WriteLine( "-------------------------" );
Console.WriteLine( "{0}", Str );

}
}
sr.Close();

f s R . C l o s e ();
}

Console.WriteLine( "---------Console.WriteLine( "The end." );


Console.ReadLine();
return 0;

185

\n" );

}
. 7.15 .

i
. 7.15.


Enter, Telephons.txt,
.

Telephons.txt ( UTF-8)
7.11:
while( ( Str = sr.ReadLine() ) != null )
{
ind = Str.IndexOf ( Name, 0 );
if( ind != - 1

{
Console.WriteLine( "---------------------- " );
Console.WriteLine( "{0}", Str );
}
}
,
Telephons.txt ReadLine (),
. 4.3 IndexOf ()
String. ,
.

7.11 ,
.

III

Windows-


Microsoft NET Framework
8.

W indows

8.1. Win32 Application


C/C++

(
)
Windows ,
(GUI Windows applications).
C# Microsoft NET Framework

, Windows
(controls)
FCL,
Form.
GUI- Microsoft NET Framework
C# Win32-nporpaMMHpoBaHHeM

Windows

187

C/C++ ([1,2,3]))

.
[1] Windows-
Microsoft Visul C++ 6.0. -
,
C++ ( ,

, ).
, Microsoft Visual C++ NET
(2003), Microsoft Developer
Studio NET (2003) (. ),

#.

, C# Microsoft Visual
C# NET (2003), .

.
\32-
C++.
[1] , Microsoft Visual C++
6.0
Win32 Application. Mi
crosoft Visual C++NET Win32 Project
Visual C++ Projects (. . 8.1).
, . 8.1, File |
New | Project. ( Lo
cation Browse...) ( Name),
, Win32 Application Wizard
Application Settings Empty
project (
, . ).
( )
SimpleDialog,
:

188

id

New P ro ject
Project Types:

Templates:

{__| Visual Basic Projects


Cr\ Visual C# Projects
CD
Q
33

Cl

Visual J# Projects
Vi5Ual C ++ Project
Setup and Deployment Projects
Other Projects
Visual Studio Solutions

Application
f^ M F C DLL

s MFC ISAPI Extension Dll


Win32 Console Project


Windows Control Library (.NET)
[ Windows Forms Application (.NET)
Windows Service (.NET)

A Win32 console application or other Win32 project.


Name:

I SimpIeDialog

Location:

| E:\BOOKS\KUDITS\C#Book

71

Browse...

Project will be created at E.\BOOKS\KUDIT5\C#Book\5impleDialog


TM o re

OK

Cancel

Help

. 8.1.

main.cpp C++ (
)
Script.rc

resource.h #define


[1].
.
. 8.2 SimpleDialog.rc ,
Notepad ():
IDB_OK IDB_Cancel,
Cancel,
resource.h:
#define IDB_OK
10
#define IDB_Cancel 11

Windows

189

*1S]*]
File dit Format View (Help
#include <abcres h>
#include resource h"
MYDIALOG DIALOG 0,0,186,95
STYLE DS_MODALFRAM E | W S_CAPTION | W S_SYSMEHU
CAPTION "SimpleDialog"
FONT 8, "MS Sans SenP
BEGIN
PUSHBUTTON "OK",
IDB_OK,
129,7,50,14
PUSHBUTTON "Cancel1, IDB_Cancet 129,24,50,14
END

. 8.2.

Script.rc SimpleDialog, Microsoft Visual C++ NET


Project | Add Existing Item... Script.rc .
main.cpp resource.h
,
Microsoft Visual C++ NET.
Project | Add New Item...,
C++.
resource.h ,
, main.cpp :
8.1.
j& 'k'k 'k 'k 'k 'k'k'k 'k 'k 'k 'k'k 'k 'k 'k 'k'k'k Jr'k & 'k-k j

/*
File main.cpp
*/
/************************* j
#include <windows.h>
#include "resource.h"

// Prototypes:
// Dialog window function:
int CALLBACK DlgProc( HWND, UINT, WPARAM, LPARAM );
// Message Handlers:
void OnClose( HWND hwnd );
void OnOK( HWND hwnd );
void OnCancel( HWND hwnd );

190

/////////////////////////////////////////////////////////
int WINAPI WinMain( HINSTANCE hi, HINSTANCE hl2,
LPSTR p, int n)

{
int ret;
ret = DialogBox( hi, "MYDIALOG", 0, (DLGPROC)DlgProc);
if( ret == 0 )
MessageBox( 0, "Close box", "Message", MB_OK );
if ( ret == 1 )
MessageBox( 0, "OK button",

"Message", MB_OK );

if ( ret == 2 )
MessageBox( 0, "Cancel button",

"Message", MB_OK );

return 0 ;

}
/////////////////////////////////////////////////////////
int CALLBACK DlgProc( HWND hwnd , UINT iMsg,
WPARAM wParam, LPARAM 1Param ) .

{
if( iMsg == WM_CLOSE )

{
OnClose( hwnd );
return 1 ;

}
if( iMsg == WM_COMMAND )

{
i f ( LOWORD( wParam ) == IDB_OK )
OnOK( hwnd );
if( LOWORD( wParam ) == IDB_Cancel )
OnCancel( hwnd );
return 1 ;

}
return 0 ;

}
/////////////////////////////////////////////////////////
void OnClose( HWND hwnd )

{
EndDialog( hwnd, 0 );

}
void OnOK( HWND hwnd )

Windows

191

{
EndDialog( hwnd, 1 );

}
void OnCancel( HWND hwnd )

{
EndDialog( hwnd, 2 );

}
/////////////////////////////////////////////////////////
SimpleDialog
Microsoft Visual C++ NET . 8.3.
JQ I |
Fi'e

Edit

. j p " { H

View
p

Project
'

Build

Debug

Debug

Tools

Window

Help

QjJ

zJ
# include < w i n d o w s . h >

IJJJ Solution SimpleDialog1(1

^incl u d e

"resource.h1

3 - !jP S im p le D ia lo g

References
i S Source Files

// Prototypes:
// D i a l o g w i n d o w function:
int C A L L B A C K D l g P r o c ( HTOND, UINT,

UPARAB,

LPA R A M

// Hess a g e Handlers:
v o i d OnClose( HUND hwn d );
v o i d OnOK(

HtJND hwnd ) ;

v o i d O n C a n c e l ( HWND h w n d );

J 1
R.. S s.. l^ c -
Ready

JL

. 8.3.

SimpleDialog.exe,

( Script.rc,
. . 8.2) SimpleDialog,
. 8.4.
(
) ,
Windows-
. -

Cancel

. 8.4.

( ):
.
,
(, , ),
. , . 8.5 ,
.
XJ
OK button

. 8.5.

, ,

. ,
, , .
.
, . 8.4,
,
- ,
. ,

.

Tab ( ).

Windows

193

,
Alt+, ,
. 8.6.

C lose

Alt+F4

OK
Cancel

. 8.6.

Enter , . 8.6,

( ,
). . 8.6 , ,
Alt+F4.

8.2.

C/C++
, Windows-
C/C++,
.
, (hardware
events), (,
), ()
(,
,
, , ),
(messages queue).
.
Windows-
.
,

194

8.1,
DialogBox(),
DlgProc ().

,
(
), (
) DlgProc () iMsg,

- wParam lParam (. 8.1).
WinMain ()
DialogBox (). , ,

, ( 8.1
DialogBox ()
).

, WinMain ()

,
( , C++
#). , (.,
, . 11 [2], [7]).


Windows.
,
WinMain () (. . 8.7).
,
( ),
.
, (
8.8 [1]), , 8.1,
-.
. 8.7
(
) .

Windows, . ,

Windows


Win32 Project
-


Windows
DialogBox

W inMain
Funl Fun2

#1

#2

195

-
,

. 8.7.


:
( C++)

, Win32
API ( 8.1
DialogBox ( ) ,EndDialog () MessageBox ()),
,
C/C++.
,
( )
int __stdcall WinMain( void* h i , void*
char* p, int n)

hI2,

{
return 0 ;

}
-
C/C++. .
WinMain () h i , ,

. ,
( Win32 API) h i
. __ stdcall

196

( )
C/C++,
WinMain ().
Windows - -
:
#include <windows.h>
int WINAPI WinMain( HINSTANCE hi, HINSTANCE hI2,
LPSTR p, int n)

{
return 0 ;

}
,
,
Windows,
.
,
windows.h
.
windows.h (
, )

# d e f in e ,

: , v o id *
HINSTANCE, c h a r * LPSTR,
__ s t d c a l l WINAPI.
, (.
8.1), ,
, WinMain ():
C/C++
#def ine. UINT, WPARAM LPARAM int,
CALLBACK
, a HWND void*
HINSTANCE. ,
HINSTANCE
,

Windows

197

, , Win32 API
. HWND
.
, , . 8.7
, Windows- , ,
, .

8.3.
C#
. 8.7, ,
C/C++ Windows

,
.
Microsoft NET Framework C#
, FCL
(. . 8.8).
C#

........

FCL

....

#1

#2

DialogBox

Form

MyDialog


Windows

||

-
,

. 8.8.

. 8.8 , FCL
. -

198

FCL ,
, . 8.8 .
, FCL
Win32 API Windows (
FCL).

FCL, ,
Form (
) Button.
-
main Main (), MyDialog, . MyDialog
,
Form.
, MyDialog
Button ( . . 5.2).
. 8.8
.

-
, ,
HWND, WPARAM, LPARAM .
#, .
, - (
FCL).
#, .
(
, [8]),
. ,
, FCL,
, .
C#
,
( ),
MyDialog. ,
,

Windows. C# .

Windows

199

(
delegate, ),
MulticastDelegate,
() ,
(
#). C#
Win
dows ( FCL, ).
FCL ( Button,
) ( #,
event), ,
,
, (
). ,
+= -=
,
.
,
#,
FCL,
.
#, main.cs,

,
, . 8.1 C++ (. 8.1).
8.2.

************************* j
/*
File main.cs
*/
/*************************/
using System;
using System.Drawing;
using System.Windows.Forms;
class main
{
public static int Main( )
{
MyDialog myDlg = new MyDialogO;

200

DialogResult res = myDlg.ShowDialog( null );

i f ( res == DialogResult.Cancel )
MessageBox.Show( "Close Box", "Message" );
return 0 ;

}
}
class MyDialog : Form

{
// :
public MyDialogO

{
// ,
// :
MaximizeBox = false;

MinimizeBox = false;
Text = "SimpleDialog";

ClientSize = new Size( 186, 95 );


FormBorderStyle = FormBorderStyle.FixedDialog;
ShowInTaskbar = false;
// ,
// , C/C++:
Font = new Font( "MS Sans Serif", 8 );
AutoScaleBaseSize = new Size( 4, 8 );
// " "
/ / :
btnl = new ButtonO;
btn2 = new ButtonO;
Controls.Add( btnl );
Controls.Add( btn2 );
// "":
btnl.Location = new Point( 129, 7 );
btnl.Size = new Size( 50, 14 );
btnl.Text = "OK";
// "Cancel":
btn2.Location = new Point( 129, 24 );
btn2.Size = new Size( 50, 14 );
btn2.Text = "Cancel";

Windows

//

201

!!!!

//
// Click:
btnl.Click += new EventHandler( OnOK );
btn2.Click += new EventHandler( OnCancel );
// :
private void OnOK( object obj, EventArgs e )

{
MessageBox.Show( "OK button",

"Message" );

}
private void OnCancel( object obj, EventArgs e )

{
MessageBox.Show( "Cancel button",

"Message" );

}
// , :
private Button btnl;
private Button btn2;

}
C# 8.1
C++ (
,
Windows) ,
, .
8.2
( C/C++
), #,
( . . 5.1). C#
,
,
.
8.2 -
,
.
8.2:
btnl.Click += new EventHandler( OnOK );
btn2.Click += new EventHandler( OnCancel );

202

- OnOK ()
OnCancel () Click, But
ton ( ,
), ,
, .
new
EventHandler,
-.
Windows
- o b ject EventArgs, :
private void OnOK( object obj, EventArgs e )
{ MessageBox.Show( "OK button", "Message" ); }
private void OnCancel( object obj, EventArgs e )
{ MessageBox.Show( "Cancel button", "Message" ); }

,
.
, , (
8.2):
btnl.Click += new EventHandler( OnClick );
btn2.Click += new EventHandler( OnClick );
private void OnClick( object obj, EventArgs e )

{
if( obj == btnl )MessageBox.Show( "OK button", "Message" );
else MessageBox.Show( "Cancel button", "Message" );

}
EventArgs - ,
,
.
, EventArgs ( EventArgs). ,

MouseEventArgs ( , EventArgs)
, ,
.

Windows

203

,
C# - ,
,
#, ,
,
.
Windows
C#
. , Main () myDlg
MyDialog
ShowDialog ():
DialogResult res = myDlg.ShowDialog( null );

,
MyDialog,
. , Form
Windows, .

ShowDialog () Form. Win
dows .
MyDialog,
Form,
.
:
MaximizeBox = false;
MinimizeBox = false;
Text = "SimpIeDialog";
ClientSize = new Size( 186, 95 );
FormBorderStyle = FormBorderStyle.FixedDialog;
ShowInTaskbar = false;

( ) Form ( -
, )
. , false
ShowInTaskbar ,
,
. FormBorderStyle FormBorderStyle.FixedDialog, ,
.

204

_____________________________________________________________________ 8

,
FormBorderStyle .
(),
FCL System.Win
dows. Forms.
Form, (, ,

) FormBorderStyle,
- ,
.
.
,
( ) :
Font = new Font( "MS Sans Serif", 8 );
AutoScaleBaseSize = new Size( 4, 8 );


,
,
,
Windows, ,
, 8.1 C++ (,
,
. 8.2). ,
Windows,
,
[9].
Button
btnl btn2 MyDialog (
):
btnl = new ButtonO;
btn2 = new ButtonO;


:
Controls.Add( btnl );
Controls.Add( btn2 );

Windows

205

Controls Form, trolCollection, ( ),


. 6.5
ArrayList ( Add () ).
M yD ialog
(, ) .
8.2, ,
Empty Project C#

Microsoft Visul #.

Windows ,
.
( - ).
ProjDialogl EmptyProject main.cs
8.2, .
(References)
FCL - System.dll, System.Drawing.dll System.Windows.Forms,
dll ( . . 1.4).
References
Microsoft Visual C#
Add Reference...,
(. . 8.9).
Add Reference (
.NET) Select
Selected Components,
.
( -
main.cs), . 8.10.
, , Output ,
Empty Project
Console Application ( Windows-,
). Project | Prop
erties... Property Pages (. . 8.11),
() Common Properties
Output Windows Application (Windows ).

206

A cd R e fe re n c e
NET

-ill

| COM | Projects |
Browse.

Component Name
| Version
System.Messaging.dll
1.0.5000.0
System. Runtime.Remoting
1.0.5000.0
System. Runtime. Serialization.,.,, 1.0.5000.0
System.Secunty
1.0.5000.0
System. ServiceProcess. dll
1.0.5000.0
System.Web.dll
1.0.5000.0
System.Web. Mobile.dll
1.0.5000.0
System.Web.RegularExpressi... 1.0.5000.0
System.Web.5r rvices, dll
1.Q.50CO.O
j) stem, Windows .Form?:,dll
1.0,5000,0
System.Xml.dll
1.0.5000.0
I VISRrnwcprShthl ih
1..5.

J.M>.................... L d
E:\WINDOW5\Microsoft.NET\..
E:\WINDOWS\Microsoft.NET\...
E: \WINDOWS\Microsoft.NET\..
E:\WINDOWS\Microsoft.NET\..
E:\WINDOWS\Microsoft.NET\...
E: \WINDOWS\Microsoft.NET\..
E:\WINDOWS\Microsoft.NET\..
E:\WINDOWS\Microsoft.NET\...
,
E:\WINDOW5\Microsoft.NET\... _ J
E:>WINDOWS;iicrosoft.NET,., \
E:\WINDOWS\Microsoft. NETV..
,
F:\
WTNDOWS\ Mirrn<:nft.NF .. Z j

Selected Components:
Component Name
System.dll
System.Drawing.dll
System .W ndows. Forms.dl

I Source

j
.NET
.NET
.NET

Remove

E:\WINDOWS\Microsoft.NET\Fr...
E:\WINDOWS\Microsoft.NET\Fr...
E ,\WINDOWS\Microsoft.NET\Fr...

OK

Cancel

Help

. 8.9.

^ ld x j

Pro jO ialo g i - M icrosoft Visual t # .NET [d e s ig n ] [m ain .cs}

'?) File

dit

View

Project

I Solution Exzbrer - ProjDial... ^ X

Solution 'ProjDialogl' (1 project)


P P ro jD ialo g l
8- References
* Z) System
* 0 System.Drawing
< 3 System.Windows.For
[ main.cs

_____________ I 2J
Ready

. 8.10.

Build

Debug

MyDialog

lools

Window

-& x

Help

M a x i m i z e B o x e false;
MinitnizeBox = false;
Text - "SimpIeDialog";
C l i e n t S i z e ** n e u Sxze(

186,

95 );

F o r m B o r d e r S t y l e ForinBorderStyle. F i x e d D i a l o g ; ShouInTasktoar false:


Font = n e w F o n t ( 'MS Sans Serif",

AutoScaleBaseSize s new S i z e ( 4 , 8 1 ;

Ln 25

Col 29 _

Ch23

~|!

l.INSl

Windows

207

2Sl

ProiDieJM?! Property <

\r r
- ! Common Properties
General
Designer Defaults
References Path
Build Events
Configuration Properties

U
S A p p lic a tio n
Assembly Name
Output Type
Default Namespace
Startup Object
Application Icon
Supported Runtimes
0 P ro je c t
Project File
Pro'ect Folds c . tputFil*
W rap p e r A s>e m bly fn r A e t
: Wrapper Assembly Key File
Wrapper Assembly Key Name

ProjDialogl
Windows Application
ProjDialogl
(Not set)

!.
UPIT" :# 6 o o k U w s\Pro)Df3logiT

I Output Type
The type of application to build (/target).

Cancel

Help

. 8.11.

ProjDialogl
,
, . 8.1
C++ . 8.4
. 8.5.
, C#
( )
, C++,
,
FCL,
. [5,9],
Microsoft Visual #.
, (. . 8.10)
M aximizeBox F1,
Form (. . 8.12).

208

P roiD ialogt -M ic ro s o ft W su alC #.N E T [d esH jii3-[M 4X M ,u , F f u ^ l y l


&le

Edit

View

Project

Build

Debug

lo o ls

!? x E E S Wfr/ramewo/vSf
3
F o rm .M a xim izeB ox P ro p erty [c*]
1
Gets o r sets a va lu e in d ic a tin g w h e tn e r th e
B- \
o f th e fo rm .

Window

Help

m a x im iz e b u tto n is d is p la y e d in th e ca p tio n b a r J

t*
p u b l i c to$pl M ax i in x z eB ox

u
21

{g e t;

se t;}

P r o p e r ty V a lu e

J~~pi.ne

t r u e to disp la y a m a x im iz e b u tto n f o r th e fo rm ; o th e rw is e j f a ls e . The d e fa u lt is t r u e

J
Ji_

. 8.12.


(
, #).
, . 8.13 , (
) 8.2.
. 8.13 , , FormBorder
Style, MaximizeBox .

Microsoft Visual C# ,
,
, ,
(
C# ).

Windows

209

-lolxi
File

Edit

View

Project

Build

Debug

Tools

Window

Help

&

0 0 .NET Framework Chss Library


F o rm .M a x im iz e B o x P roperty |o]

p u b l i c v o i d C reateM yForm ()

<
/ / C r e a te a new i n s t a n c e o f t h e form .
Form, fo r m l = new Form ;
/ / C r e a te tw o b u t t o n s t o u s e a s t h e a c c e p t and c a n c e l b u t t o n s
B u tt o n b u t t o n ! = new B u tt o n O ;
B u tt o n b u tto n 2 = new B u tto n O f
/ / S e t t h e t e x t o f b u t t o n l t o OK"
b u t t o n l .T e x t = OK";
/ / S e t t h e p o s i t i o n o f t h e b u t t o n on t h e form ,
b u t t o n l .L o c a t i o n - new P o in t ( 1 0 , 1 0 ) ;
/ / S e t t h e t e x t o f b u tto n 2 t o " C a n cel" .
b u t t o n 2 .T e x t * C a n c e l" ;
/ / S e t t h e p o s i t i o n o f t h e b u t t o n b a s e d on t h e l o c a t i o n o f b u t t o n l
b u t t o n 2 .L o c a t io n
=* new P o in t ( b u t t o n l . L e f t , b u t t o n l .H e i g h t + b u t t o n l . Top + 1 0 ) ;
/ / S e t t h e c a p t io n b a r t e x t o f t h e form ,
fo r m l.T e x t = " D ia lo g B ox";
/ / D i s p l a y a h e lp b u t t o n on t h e form .
fo r m l.H e lp B u tt o n = t r u e ;
/ / D e f in e t h e b o r d e r s t y l e o f t h e form t o a d i a l o g b o x .
fo r m l.F o r m B o r d e r S ty le = F o r m B o r d e r S ty le .F ix e d D ia lo g ;
/ / S e t t h e H axim izeB ox t o f a l s e t o rem ove t h e m a xim ize b o x .
fo r m l.H a x im iz e B o x = f a l s e ;
/ / S e t t h e H in im iz eB o x t o f a l s e t o rem ove t h e m in im iz e b o x .

| Done

. 8.13.

JL

210

8.4. Windows-

Microsoft Visual C#

(Empty Project) ,
C# Windows-

,- .

Windows-. Microsoft Visual C#
. .
Windows Application (. . 8.14).

|N e w P ro je c t
; Eroject Types:

x jl

UfB

lem plates:

1 1 Visual Basic Projects

3
Q
S CJ
P i
-D
~ I

Visual C # Projects
Visual J # Projects
Visual C + + Projects
Setup and Deployment Projects
Other Projects
Visual Studio Solutions

Class Library
EjE] Windows Control Library
jj!lSmart Device Application
ASP.NET Web Application
ASP.NET Web Service
3jT ASP.NET Mobile Web Application
g ]W e b Control Library
3 Console Applicat'on

A project for creating an application with a W ndows user interface


Name:

[w in A p p l

Location:

J E:\BOOKS\KUDITS\C#Book\Tests

Browse...

Project will be created a t E:\BOOK5\KUDIT5\C#Book\Tests\WinAppl


TM ore

OK

Cancel

Help

. 8.14.

New Project
, ,
Windows,
( ).

Windows

211

,
Microsoft Visual #,
(, ,
), . 8.15.
9Z W inAppl - Microsoft Visual C# .NET [designJ - [Ftjrml.cs (
File

Edit

View

Project

Build

^1 I W *tr fcli I

Debug

I,-

Data

LJ

Tools

Window

M 4-

Help

$4

Solution Explorer * W nA ppl

J S jx J

pJJJ Solution 'W inAppl' (1 project)


B - ( p W inA pp l

References
* 0 System
- * 0 System.Data
* 0 System.Drawing
* a System.Windows.Forr
* 0 System.XML
App.ico
AssembIyInfo.es

m
1________________i j j
lRes...
f~Ready

. 8.15.

. 8.15 , Windows Application


(References )
. ,
Forml.cs ,

#, ,
. (
[Forml.cs[Design]] ).
#,
Forml.cs
View Code (
View Designer), , . 8.16.
,
#.

212

jn jx j

W in A p p l - M icrosoft Visual C # JNET [d esig n ] - [Ff r m l.c s ]


Rle

Edit

View

Project

Solution Explorer - WinAp p l

a n
^
0

Build

VX

Ipols

Window

Help

\^t MAppi
] u s i n g System;

Solution 'W inAppl' (1 project)


J *] W in A p p l

References
* 0 System
<3 System.Data
* Q System.Drawing
* Q Sy stem. Wndows.Fori
* 0 System.XML
[ 2 ] App.ico
AssemblyInfo.es
3 Form l.cs

01 R e*...

Debug

J 1
Solu... ^ C l a s . . . |

u s i n g System.Drawing;
u s i n g System.Co l l e c t i o n s;
u s i n g Sy s t e m . C o m p o n e n t H odel;
u s i n g S y s t e m . W i n d o w s . F o rms;
u s i n g System.Data;

13 n a m e s p a c e W inAppl

1 ^summry>
S u m m a r y d e s c r i p t i o n for Forml.

</ suztmaryv
p u blic c lass Forml

: S y s t e m . W i n d o w s .Forms

L.______

zl

_-tC

Ready

. 8.16.

,
Windows,
, . 8.17.

. 8.17.

,
/, . ,
, Mi-

Windows

213

crosoft Visual #,
, .
,
( . 8.16),
,
( ,
),
, :
8.3.
^k-k-k-k-k-k-k-k-k-k-k'k-k-k-k-k-kicicicicicic'k'k j

/*

File Forml.cs

*/

using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

^************************* j

namespace WinAppl

{
public class Forml : System.Windows.Forms.Form

{
private System.ComponentModel.Container components = null;
public Forml(){ InitializeComponent(); }
private void InitializeComponent()

{
this.components = new System.ComponentModel.Container();
this.Size = new System.Drawing.Size(300,300);
this.Text = "Forml";

}
protected override void Dispose( bool disposing )

{
if( disposing )
if( components != null )
components.Dispose();
base.Dispose( disposing );
}

214

[STAThread]
public static void Main( )
{ Application.Run( new Forml() ); }

}
}
8.3 ,
, using,
,
, this (,
). ,
, F o rm l
W inAppl, -
.

, 8.3:
8.4.
^ k 'k -k -k 'k - k - k -k -k -k -k -k - k - k - k - k 'k -k -k -k - k - k - k - k - k J

/*

File Forml.cs

*/

J k k i c i c i c - k i c - k i c - k - k ' k i c i c i c - k - k - k ' k - k - k ' k i c i c i c j

using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

public class Forml : Form

{
private Container components = null;
public Forml(){ InitializeComponent(); }
protected override void Dispose( bool disposing )

{
if( disposing )
if( components != null )
components.Dispose();
base.Dispose( disposing );

}
private void InitializeComponent()

{
components = new ContainerO;

Windows

215

Size = new Size(300,300);


Text = "Forml";

}
[STAThread]
public static void Main()
{ Application.Run( new Forml() ); }

}
,
. 8.2,
Forml, , ,
(
Form), (
Main ()).

(
) Run ()
Application,
Forml, :
Application.Run( new Forml() );

,
C/C++ ( )
(., , [2]).
Forml (, InitializeComponent (), )
.
components
Container. (
- ),
, .
FCL IComponent,
components.
Forml Dispose (),
,
, Dis
pose () Container. ,
,

216

, ,
.
Forml.cs
, ( Toolbox)
(
drag and drop) (. . 8.18).

b u tto n 2

-..

. 8.18.


, (
- ). (,
) Properties
(. . 8.19).
. 8.19 ,
button2, Text Cancel.
,
,

, (. . 8.20).
. 8.20 , Cancel (
Forml button2)
Click button2_Click .

:

217

Windows

j
03

*1
u

button2 System.Windows.Forms.Button

m |

Cursor
Default
FlatStyle
Standard
Font
Microsoft Sans Serif, 8.25pt
ForeColor
ControlText
Image
1 1 (none)
ImageAlign
MiddleCenter
Imagelndex
1 1 (none)
ImageList
(none)
RightToleft
No
1
te t
H H H H f l i button2
. TextAlign ____________ MiddleCenter

zi

Text

. 8.19.
2 Forml.cs - [Forml.cs*]
File

Edit

Solu .

View

Project

Budd

Debug

Xools

Window

j [^button2 Chcl^obiecl: sender System.EventArgse ^ l

j^ij Forml

=B

_ 1? X

Help

public static void Main()

tition WinAppl^
WinAppl
,
Reference
] App.ico
^ Assemblyli
3 Forml.cs

{ Application.Run{ new Forml()

); >

private void b u t t o n 2 _ C lick (object sender, System.EventArgs e)

Lil__ L J

d
In 64

Ready

. 8.20.
8.5.
u sin g

System ;

u sin g

S y ste m .D ra w in g ;

u sin g
u sin g
u sin g

S y ste m .C o lle c tio n s;


S y ste m .C o m p o n e n tM o d e l;
S y ste m .W in d o w s.F o rm s;

u sin g

System .D ata;

Co! 5

Ch2

INS

218
p u b lic

c la ss

Form l

Form

\
p riv a te
p riv a te
p riv a te

Windows .Forms .Button buttonsbutton2;


Container components = null;
System .

S y s t e m . Windows.Forms.Button

Forml(){ InitializeComponent(); }
override void Dispose( bool disposing )

p u b lic

p rotecte d

{
if( disposing )
i f ( components != null )
components.Dispose();
b a se

.Dispose( disposing );

}
p riv a te

v o id

I n i t i a l i z e C o m p o n e n t ()

{
this.buttonl = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();

//
// buttonl

//
this.buttonl.Location = new System.Drawing.Point(200, 16);
this.buttonl.Name = "buttonl";
this.buttonl.Size = new System.Drawing.Size(80, 24);
this.buttonl.Tablndex = 0;
this.buttonl.Text = "OK";
this.buttonl.Click += new
System.EventHandler(this.buttonl_Click);

//
// button2

//
this.button2.Location = new System.Drawing.Point(200, 48);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(80, 24);
this.button2 .Tablndex = 1 ;
this.button2.Text = "Cancel";
this.button2 .Click += new
Sys tem.EventHandler(thi s .bu11on2_C1ick);

//
//

Fo rm l

//
t h i s .A u t o S c a l e B a s e S i z e

new

S y s t e m . D r a w i n g . S i z e (5 ,

13);

Windows

219

this.ClientSize = new System.Drawing.Size(292 , 197);


this.Controls.Add(this.button2 );
this.Controls.Add(this.buttonl);
this.Name = "Forml";
this.Text = "Forml";
this.ResumeLayout(false);

}
[STAThread]
public static void Main( )
{ Application.Run( new Forml() ); }
private void button2_Click(object sender, System.EventArgs e)

{
}
private void buttonl_Click(object sender, System.EventArgs e)

{
}
}
buttonl button2, In
itializeComponent () 8.5
,
( this).
, ,
.
8.5
buttonl_Click () button2_Click () ,
, ,
, ,
Show() MessageBox,
Windows:
private void button2_Click(object sender, System.EventArgs e)

{
MessageBox.Show( "Cancel button",

"Message" );

}
private void buttonl_Click(object sender, System.EventArgs e)

{
MessageBox.Show( "OK button",
}

"Message" );

220

, ,
(. . 8.21).

. 8.21.

Cancel ,
.
, . 8.22 ,
( ) Cancel.
ESSO

ill

Cancel button

13
. 8.22.

.
Microsoft Visual C#

,
.
, ,
.

Microsoft Visual C#
[10].
,
.
Windows-, .

Windows

221

, ,
,
, . ,
,
.
,
, .
, ,
8.5
,
. 8.5 M ain (),
, . 8.3:
public static void Main( )

{
//Application.Run( new Forml() );
Forml dig = new Forml();
// :
dlg.MinimizeBox = false;
dlg.MaximizeBox = false;
dig.FormBorderStyle = FormBorderStyle.FixedDialog;
dig.Text = "SimpleDialog";
//
// :
dig.ShowDialog();

}
:

, . ,
, ,
,
,
.
, [1],
,
(
),

.

9.

9.1.
. 7.4 -
.
, .
,
.
(. . 7.15).

. ,
. ,

.
,
,
.


.

[1] T e l P e r s o n l n f :
struct TelPersonlnfo

{
char Name[128];
int TelNum;

};
Name , TelNum .
,
#:
class TelPersonlnfo

{
// TelPersonlnfo:

Windows

223

public TelPersonlnf ( )
{ Name = null; TelNum = 0 ; }
public TelPersonlnfo( string nam )
{ m_Name = nam; m_TelNum = 0 ; }
public TelPersonlnfo( string nam, int num )
{ m_Name = nam; m_TelNum = num; }
// :
public string Name

{
get { return m_Name;
}
set { m_JSTame = value; }

}
public int TelNum

{
get { return m_TelNum;
}
set { m_TelNum = value; }

}
// :
private string m_Name;
private int
m_TelNum;

}
, . 5.1
,
TelPersonlnfo Name TelNum
m_Name m_TelNum.

, -
TelPersonlnfo.
, . 6.5
ArrayL
ist. , .

ArrayList arl = new ArrayList();

TelPersonlnfo
Add () Ar ayLi s t :
TelPersonlnfo tpi = new TelPersonlnf ();
arl.Add( tpi );

224

_____________________________________________________________________ 9


tpi .Count.
i- ()
:
(TelPersonlnfo)arl[i ]).Name

(TelPersonlnfo)arl[i]) .TelNum

ArrayList
, i-ro
( TelPersonln
fo), Name Tel
Num TelPersonlnfo.
,
,

.

9.2.
,
,
.
:

( - ).

(), ,
.
ArrayL
ist ( ) , <
BinarySearch ()
ArrayList.
- Sort ().
: BinarySearch ()
. 3.5 #,
Sort () ,
#, . , . 6.3

Windows

225

Sort () .
, ,
CompareTo () ICom
parable. * ,
.
,
CompareTo ()
TelPersonlnfo:
class TelPersonlnfo : IComparable

{
// IComparable:
public int CompareTo( object ob )

{
if ( String.Compare( m_Name,
((TelPersonlnfo)ob).m_Name ) > 0 )
return 1 ;
else i f ( String.Compare( m_Name,
((TelPersonlnfo)ob).m_Name ) == 0 )
return 0 ;
else
return -1 ;

}
// TelPersonlnfo:
public TelPersonlnf ( )
{ Name = null; TelNum = 0 ; }
public TelPersonlnf ( string nam )
{ m_JNTame = nam; m_TelNum = 0 ; }
public TelPersonlnf ( string nam, int num )
{ m_Name = nam; m_TelNum = num; }
// :
public string Name

{
get
set

{return
{m_Name

m_Name;
}
= value; }

}
public int TelNum

{
get
set
}

{return
m_TelNum; }
{m_TelNum = value;
}

226

1 1 :
private string m_Name;
private int
m_TelNum;

}
Com
pareTo () 6.4 . 6.3, ,
( -
, )
Compare () String.
CompareTo () Sort ()
.

BinarySearch () ArrayList, , .
TelPersonlnfo
, ,

.
,

buttonl (
,
):
private void buttonl_Click(object sender, System.EventArgs e)

{
if( textBoxl.Text != "" && textBox2.Text != "" ) //

{
int ind = ArL.BinarySearch(new TelPersonlnfo(textBoxl.Text));
if( ind < 0 ) //

{
ArL.Add( new TelPersonlnfo( textBoxl.Text,
Convert.ToInt32( textBox2.Text ) ) );
ArL.Sort();
textBox3.Text = " ";

}
else
textBox3.Text = " ";

}
else if( textBoxl.Text != "" && textBox2.Text == "" ) //

Windows

227

int ind = ArL.BinarySearch(new TelPersonlnfo(textBoxl.Text));


if( ind >= 0 )
textBox3.Text = Convert.ToString(
((TelPersonlnfo)ArL[ind]).TelNum );
else
textBox3.Text = " ";

}
else // ( )

{
int num = ArL.Count;
i f ( num > 0 )

{
textBoxl.Text = ((TelPersonlnfo)ArL[0]).Name;
textBox2.Text = Convert.ToString(
((TelPersonlnfo)ArL[num - 1]).TelNum );
textBox3.Text = "" ;

}
}
}

- b u t t o n l _ C l i c k .
,
(
) te x tB o x l () te x tB o x 2 (
). - te x tB o x 3 ,
.
( )
te x tB o x l .T e x t, T e x t -
.
.

9.3.
.

, ,
,
.
. 9.1.
Telephons,
. Input data .

228

xj

Telephons
Input data

OK
Exit

. 9.1.

.

,
,
.
,
,
.
, ,
(. . 9.2).
. 9.2 ,
(
Properties ) ReadOnly True (
False).

, .
()
:
textBox3.Text = " ";

, textBox3
.
textBoxl textBox2
, Input data.
buttonl.

Windows

229

3 0

textBoH3 System.Wmdows.Forms.TextBox
>

I - / 1

HideSeiection
ImeMode
MaxLength
Multiline
PasswordChar
Readonly
Tablndex
TabStop
Visible
WordWrap
C o n fig u ra tio n s

True
NoControl
32767
False

H I T ru e
2
True
True
True

R e a d o n ly

. 9.2.

F o r m l.c s ,
, M ain () (
main main.cs, ),

b u t t o n l :
9.1.

/*************************/
/*
File Forml.cs
*/
/************************* j
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace TelBookProj
{
/// <summary>
III Summary description for Forml.
Ill </summary>
public class Forml : System.Windows.Forms.Form
{

230

_____________________________________________________________________ 9

private Sys tem.Windows.Forms.GroupBox groupBoxl;


private Sys tem.Windows.Forms.TextBox textBoxl;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button buttonl;
private Sys tem.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Button button2;
I I I <summary>
I I I Required designer variable.
I l l </summary>
private System.ComponentModel.Container components = null;
public Forml( ArrayList arl )

{
11
II

Required for Windows Form Designer support

11
InitializeComponent();

11

TODO: Add any code after InitializeComponent call

11
ArL = arl;

}
<summary>
Clean up any resources being used.
</summary>
protected override void Dispose( bool disposing )
III
III
Ill

{
if( disposing )

{
if (components != null)

{
components.Dispose();

}
}
base.Dispose( disposing );

}
#region Windows Form Designer generated code
I I I <summary>
I I I Required method for Designer support - do not modify
I I I the contents of this method with the code editor.
I l l </summary>
private void InitializeComponent()

Windows

231

this.groupBoxl = new System.Windows.Forms.GroupBox();


this.textBox2 = new System.Windows.Forms.TextBox();
this.textBoxl = new System.Windows.Forms.TextBox();
this.buttonl = new System.Windows.Forms.Button();
this.textBox3 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.groupBoxl.SuspendLayout();
this.SuspendLayout();

//
// groupBoxl

//
this.groupBoxl.Controls.Add(this.textBox2);
this.groupBoxl.Controls.Add(this.textBoxl);
this.groupBoxl.Location = new System.Drawing.Point(16, 16);
thi s .groupBoxl.Name = "groupBoxl";
this.groupBoxl.Size = new System.Drawing.Size(320, 72);
this.groupBoxl.Tablndex = 0;
this.groupBoxl.Tabstop = false;
this.groupBoxl.Text = "Input data";

//
// textBox2

//
this.textBox2.AutoSize = false;
this.textBox2.Location = new System.Drawing.Point(176, 24);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(128, 32);
this.textBox2.Tablndex = 1;
this.textBox2.Text =

//
// textBoxl

//
this.textBoxl.AutoSize = false;
this.textBoxl.Location = new System.Drawing.Point(16, 24);
this.textBoxl.Name = "textBoxl";
this.textBoxl.Size = new System.Drawing.Size(128, 32);
this.textBoxl.Tablndex = 0;
this.textBoxl.Text =

//
// buttonl

//
this.buttonl.Location = new System.Drawing.Point(40, 104);
this.buttonl.Name = "buttonl";
this.buttonl.Size = new System.Drawing.Size(12 0, 32);

232

this.buttonl.Tablndex = 1;
this.buttonl.Text = "OK";
this.buttonl.Click += new System.EventHandler(this.buttonl_Click);

11
II

textBox3

//
this.textBox3.AutoSize = false;
this.textBox3.Location = new System.Drawing.Point(192, 104);
this.textBox3.Name = "textBox3";
this.textBox3.Readonly = true;
this.textBox3.Size = new System.Drawing.Size(128, 32);
this.textBox3.Tablndex = 2;
this.textBox3.Text =

//
// button2

//
this.button2.DialogResult =
System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(120, 152);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(120, 32);
this.button2.Tablndex = 3;
this.button2.Text = "Exit";

//
// Forml

//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(3 52, 197);
this.Controls.Add(this.button2 );
this.Controls.Add(this.textBox3);
this.Controls.Add(this.buttonl);
this.Controls.Add(this.groupBoxl);
thi s .Name = "Forml";
this.Text = "Forml";
this.groupBoxl.ResumeLayout(false);
this.ResumeLayout(false);

}
#endregion
private void buttonl_Click(object sender, System.EventArgs e)

{
if( textBoxl.Text 1= "" && textBox2.Text != "" ) //

Windows

233

int ind = ArL.BinarySearch( new


TelPersonlnfo(textBoxl.Text));
if( ind < 0 ) //

{
ArL.Add( new TelPersonlnfo( textBoxl.Text,
Convert.ToInt32( textBox2.Text ) ) );
ArL.Sort();
textBox3.Text = " ";

}
else
textBox3.Text = " ";

}
else if( textBoxl.Text != "" && textBox2.Text == "" )
{ //
int ind = ArL.BinarySearch( new
TelPersonlnfo(textBoxl.Text));
if( ind >= 0 )
textBox3.Text = Convert.ToString(
((TelPersonlnfo)ArL[ind]).TelNum );
else
textBox3.Text = " ";

}
else // ( )

{
int num = ArL.Count;
if( num > 0 )

{
textBoxl.Text = ((TelPersonlnfo)ArL[0]).Name;
textBox2.Text = Convert.ToString(
((TelPersonlnfo)ArL[num - 1]).TelNum );
textBox3.Text = "";

}
}
}
// ( ):
ArrayList ArL;

}
}
, 9.1
Forml arL ArrayList

.
Forml:

234

11
// TODO: Add any code after InitializeComponent call

11
ArL = arl;

, ,

.
9.1
, , . 8.4,
,
, .
.

9.4.
,
,
.
T e le p h o n s .
. 7,

.
PutDatalntoDB () G e tD a ta FromDB() MyFiles:
9.2.
I'k'k'k'k'k-k-k'k'k-k-k'k'k'k'k'k'k-k'k'k'k'k-k'k'k j

File MyFiles.cs

I*

*/

/************************* j
using System;
using System.Collections;
using System.10;
class MyFiles

{
public static void PutDatalntoDB(string FileName,ArrayList arl)

{
int size, len, Ind = 0; string strAux;
// 1. chAr char
// :
size = arl.Count;

Windows

235

char[] chAr = new char[ (128+7) * size ];


strAux = new String( ' ', (128+7) * size );
strAux.CopyTo( 0, chAr, 0, (128+7) * size );
// chAr
/ / arl:
for( int i = 0 ; i < size; ++i )

{
// - :
strAux = ((TelPersonlnfo)arl[i]).Name;
len = strAux.Length;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 128;
// - :
strAux = Convert.ToString(
( (TelPersonlnfo)arl[i]).TelNum );
len = strAux.Length;
StrAux.CopyTo( 0, chAr, Ind, len );
Ind += 7;

}
// 2. chAr :
FileStream fsW = new FileStream( FileName, FileMode.Create,
FileAccess.Write );
BinaryWriter bw = new BinaryWriter( fsW );
///////////////////
bw.Write( chAr );

///////////////////
bw.Close();
fsW.Close();

}
public static int GetDataFromDB(string FileName,ArrayList arl)

{
int TargetNum, len, Ind = 0; string TargetStr; char[] inBuf;
if( File.Exists( FileName ) )

{
FileStream fsR = new FileStream( FileName, FileMode.Open,
FileAccess.Read );
len = (int)fsR.Length;
if( len > 0 )

{
BinaryReader br = new BinaryReader( fsR );

/////////////////////////////

236

inBuf = br.ReadChars( len );


11111111111111111111111111111
.Close();
fsR.Close();

b r

// ArrayList:
char[] NameBuf = new char[128];
chart] NumBuf = new char[7];
while( Ind < inBuf.Length )

{
// - :
Array.Copy( inBuf, Ind, NameBuf, 0, 128 );
TargetStr = ( new string( NameBuf ) ).TrimEnd();
Ind += 128;
// - :
Array.Copy( inBuf, Ind, NumBuf, 0, 7 );
TargetNum = Convert.ToInt32(
( new string(NumBuf) ).TrimEnd() );
Ind += 7;
// :
arl.Add( new TelPersonlnfo( TargetStr, TargetNum ) );

}
return 0;

//

}
fsR.Close();
}
return -7; //

}
}
, P utD a ta ln to D B () GetDataFromDB ()
- ( ).
,
. ,
( )
.
, W rite ()
B in a r y W r ite r ReadChars ()
B in a ry R ea d er. ,
c h a r,

Windows

237


, .

9.2: char,
.
,
Microsoft NET Framework,
(. [5]). ,
C#
. -
.

TelPersonlnfo char (
, GetDataFromDB (),
):
// 1. chAr char
// :
size = arl.Count;
chart] chAr = new chart (128+7) * size ];
strAux = new String( '
(128+7) * size );
StrAux.CopyTo( 0, chAr, 0, (128+7) * size );
// chAr
/ / arl:
for( int i = 0 ; i < size; ++i )

{
// - :
strAux = ((TelPersonlnfo)arl[i]).Name;
len = strAux.Length;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 128;
// - :
strAux = Convert.ToString(
( (TelPersonlnfo)arl[i]).TelNum );
len = strAux.Length ;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 7;

}
[1] , 128
, .

238

_____________________________________________________________________ 9

128+7
,
:
size = arl.Count;
chart] chAr = new chart (128+7) * size ];
strAux = new String( '
(128+7) * size );
strAux.CopyTo( 0, chAr, 0, (128+7) * size );

,
, String

strAux, ()
chAr.
, ( )
,
arl ArrayList:
for( int i = 0 ; i < size; ++i )

{
// - :
strAux = ((TelPersonlnfo)arl[i]).Name;
len = strAux.Length;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 128;
// - :
strAux = Convert.ToString(
( (TelPersonlnfo)arl[i]).TelNum );
len = strAux.Length;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 7;

}

Ind:
Ind += 128;

Ind += 7;


, ( 7 ) -
.

Windows

239

9.5.

,
, 9.1 9.2,
. , ,
main.cs main M a in ()
,
A r r a y L i s t ,
.
Microsoft Visual C#
Windows Application TelBookProj,

, . 9.3 (
Forml.cs), main.cs, TelPersonInfo.cs
MyFiles.cs. ,
. 9.3.
lOJxj

\ TelBookProj - M icrosoft Visual C # T [design] [M yFil s i s }


*X>

File

Edit

View

Project

Build

Debug

Tools

Window

jj

_____ 1

using System ;
using S y s te m .Collections;
j U3ing S y s te m .10;
class HyFiles

{
p u b lic s t a t i c v o i d P u tD a ta ln to D B ( s t r i n g F ileN a .

{
in t s iz e ,
//

le n ,

Ind = 0; s t r i n g str A u x :

'-

____ _____ |
R ead y

3 FT"

l^fMyFiles
ution 'TelBookProj' (1 p rc j^
TelBookProj
References
App.ico
2 j AssemblyInfo.es
Esl Forml.cs
Q main.es
] MyF2es,cs
1 TelPersonInfo.es T

Help

l, Ln5

rhAr

21
'J

Ch

14

,IM5;

. 9.3.


, Forml.cs MyFiles.cs
9.1 9.2 ,
:

240
9.3.

/***************************/
/*

File TelPersonInfo.cs

*/

jie -k-k-k-k-k-k-k-k'k-k-k'k-k'k'k'k'k'k-k'k'k'k'k'k'k'k

using System;
class TelPersonlnfo : IComparable

{
// IComparable:
public int CompareTo( object ob )

{
if( String.Compare( m_Name,
((TelPersonlnfo)ob).mJName ) > 0 )
return 1 ;
else iff String.Compare( mJName,
((TelPersonlnfo)ob).m_Name ) == 0 )
return 0 ;
else
return -1 ;

}
// TelPersonlnfo:
public TelPersonlnfo( )
{ Name = null; TelNum = 0 ; }
public TelPersonlnfo( string nam )
{ m_Name = nam; m_TelNum = 0 ; }
public TelPersonlnfo( string nam, int num )
{ m_Name = nam; m_TelNum = num; }
// :
public string Name

{
get { return m_Name;
}
set { m_Name = value; }

}
public int TelNum

{
get { return m_TelNum;
}
set { m_TelNum = value; }

}
// :
private string m_Name;
private int
m_TelNum;

Windows

241

! * * * * * * * * * * * * * * * * * * * * * * * * * j

/*

File MyFiles.cs

*/

/************************* j
using System;
using System.Collections;
using System.10;
class MyFiles

{
public static void PutDatalntoDB(string FileName,ArrayList arl)

{
int size, len, Ind = 0; string strAux;
// 1. chAr char
I l :
size = arl.Count;
char[] chAr = new chart (128+7) * size ];
strAux = new String( '
(128+7) * size );
strAux.opyTo( 0, chAr, 0, (128+7) * size );
// chAr
/ / arl:
for( int i = 0 ; i < size; ++i )

{
// - :
strAux = ((TelPersonlnfo)arl[i]).Name;
len = strAux.Length;
strAux.opyTo( 0, chAr, Ind, len );
Ind += 128;
// - :
strAux = Convert.ToString(
( (TelPersonlnfo)arl[i]).TelNum );
len = strAux.Length;
strAux.CopyTo( 0, chAr, Ind, len );
Ind += 7;

}
// 2. chAr :
FileStream fsW = new FileStream( FileName, FileMode.Create,
FileAccess.Write );
BinaryWriter bw = new BinaryWriter( fsW );
///////////////////
bw.Write( chAr );

///////////////////

242

bw.Close() ;
fsW.Close();

}
public static int GetDataFromDB(string FileName,ArrayList arl)

{
int TargetNum, len, Ind = 0; string TargetStr; char[] inBuf;
if( File.Exists( FileName ) )

{
FileStream fsR = new FileStream( FileName, FileMode.Open,
FileAccess.Read );
len = (int)fsR.Length;
if( len > 0 )

{
BinaryReader br = new BinaryReader( fsR );
/////////////////////////////
inBuf = br.ReadChars( len );
/////////////////////////////
br.Close();
fsR.Close();
// ArrayList:
char[] NameBuf = new char[128];
char[] NumBuf = new char[7];
while( Ind < inBuf.Length )

{
I l - :
Array.Copy( inBuf, Ind, NameBuf, 0, 128 );
TargetStr = ( new string( NameBuf ) ).TrimEnd();
Ind += 128;
I l - :
Array.Copy( inBuf, Ind, NumBuf, 0, 7 );
TargetNum = Convert.ToInt32(
( new string(NumBuf) ).TrimEnd() );
Ind += 7;
I l :
arl.Add( new TelPersonlnfo( TargetStr, TargetNum ) );

}
return 0 ;

}
fsR.Close();
}

//

Windows

243

return -7; //

}
}
J

kik-k-k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k'k j

File Forml.cs

/*

*/

/************************* j

using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

namespace TelBookProj

{
/// <summary>
I I I Summary description for Forml.
I l l </summary>
public class Forml : System.Windows.Forms.Form

{
private System.Windows.Forms.GroupBox groupBoxl;
private System.Windows.Forms.TextBox textBoxl;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button buttonl;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Button button2;
I I I <summary>
I I I Required designer variable.
I l l </summary>
private System.ComponentModel.Container components = null;
public Forml( ArrayList arl )

{
//
11

Required for Windows Form Designer support

11

InitializeComponent() ;

//
// TODO: Add any code after InitializeComponent call
11

ArL = arl;
}

244

<summary>
Clean up any resources being used.
</summary>
protected override void Dispose( bool disposing )
III
III
Ill

{
if( disposing )

{
if (components != null)

{
components.Dispose();

}
}
base.Dispose( disposing );

}
#region Windows Form Designer generated code
I I I <summary>
I I I Required method for Designer support - do not modify
I I I the contents of this method with the code editor.
I l l </summary>
private void InitializeComponent()

{
this.groupBoxl = new System.Windows.Forms.GroupBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBoxl = new System.Windows.Forms.TextBox();
this.buttonl = new System.Windows.Forms.Button();
this.textBox3 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.groupBoxl.SuspendLayout();
this.SuspendLayout();

//
// groupBoxl
11

this.groupBoxl.Controls.Add(this.textBox2);
this.groupBoxl.Controls.Add(this.textBoxl);
this.groupBoxl.Location = new System.Drawing.Point(16, 16);
thi s .groupBoxl.Name = "groupBoxl";
this.groupBoxl.Size = new System.Drawing.Size(320, 72);
thi s .groupBoxl.Tablndex = 0;
this.groupBoxl.TabStop = false;
this.groupBoxl.Text = "Input data";
11
11
11

textBox2

Windows

245

this.textBox2.AutoSize = false;
this.textBox2.Location = new System.Drawing.Point(176, 24);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(128, 32);
this.textBox2.Tablndex = 1;
this.textBox2.Text = "";

//
// textBoxl

//
this.textBoxl.AutoSize = false;
this.textBoxl.Location = new System.Drawing.Point(16, 24);
this.textBoxl.Name = "textBoxl";
this.textBoxl.Size = new System.Drawing.Size(128, 32);
this.textBoxl.Tablndex = 0;
this.textBoxl.Text = "";

//
// buttonl

//
this.buttonl.Location = new System.Drawing.Point(40, 104);
this.buttonl.Name = "buttonl";
this.buttonl.Size = new System.Drawing.Size(120, 32);
this.buttonl.Tablndex = 1 ;
this.buttonl.Text = "OK";
this.buttonl.Click += new System.EventHandler(this.buttonl__Click);

//
// textBox3

//
this.textBox3.AutoSize = false;
this.textBox3.Location = new System.Drawing.Point(192, 104);
this.textBox3.Name = "textBox3";
this.textBox3.Readonly = true;
this.textBox3.Size = new System.Drawing.Size(128, 32);
this.textBox3.Tablndex = 2;
this.textBox3.Text = "";

//
// button2

//
this.button2.DialogResult =
System.Windows.Forms.DialogResult.Cancel;
this .button2 .Location = new Sys tem. Drawing. Point (12 0, 152);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(120, 32);
this.button2 .Tablndex = 3;

246

9
this.button2.Text = "Exit";

//
Forml

11

//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(352, 197);
this.Controls.Add(this.button2);
thi s .Controls.Add(thi s .text);
this.Controls.Add(this.buttonl);
this.Controls.Add(this.groupBoxl);
this.Name = "Forml";
this.Text = "Forml";
this.groupBoxl.ResumeLayout(false);
this.ResumeLayout(false);

}
#endregion
private void buttonl_Click(object sender, System.EventArgs e)

{
if( textBoxl.Text != "" && textBox2.Text != "" ) //

{
int ind = ArL.BinarySearch( new
TelPersonlnfo(textBoxl.Text));
if( ind < 0 ) //

{
ArL.Add( new TelPersonlnfo( textBoxl.Text,
Convert .'ToInt32 ( textBox2 .Text ) ) );
ArL.Sort();
textBox3.Text = " ";

}
else
textBox3.Text = " ";

}
else if( textBoxl.Text != "" && textBox2.Text == "" )
{ //
int ind = ArL.BinarySearch( new
TelPersonlnfo(textBoxl.Text));
if( ind >= 0 )
textBox3,.Text = Convert .ToString (
((TelPersonlnfo)ArL[ind]).TelNum );
else
textBox3.Text = " ";

Windows

247

else // ( )

{
int num = ArL.Count;
if ( num > 0 )

{
textBoxl.Text = ((TelPersonlnfo)ArL[0]).Name;
textBox2.Text = Convert.ToString(
((TelPersonlnfo)ArL[num - 1]).TelNum );
textBox3.Text = "";

}
}
}
// ( ):
ArrayList ArL;

}
}
f kkk-kkkkkkkkkkk-kkkk-k-kk j

File main.cs

/*

*/

j
kkkkkkkkkkkkkkkkkkkkkkkkk j

Using
using
us ing
using

System;
System.Collections;
Sys tem.Windows.Forms;
TelBookProj;

class main

{
1 1 // - :
static ArrayList arl = new ArrayList();
static string FileName = "Telephons";

[STAThread]
public static void Main( )

{
// :
int ret = MyFiles.GetDataFromDB( FileName, arl );
if( ret == -7 )
MessageBox.Show( " ", "" );
//Application.Run( new Forml() );
Forml dig = new Forml( arl );

248

_____________________________________________________________________ 9

// :
dig.MinimizeBox = false;
dlg.MaximizeBox = false;
dig.FormBorderStyle = FormBorderStyle.FixedDialog;
dig.Text = "Telephons";

Il
// :
dig.ShowDialog();
// :
MyFiles.PutDatalntoDB( FileName, arl );

}
}
, 9.3 .
, (
, ),
.
, main.cs. -,

using TelBookProj;

F orm l 1 B o o k P ro j.
-, , . 8.4, M ain ()
,
Application.Run( new Forml() );

,
( . 9 [1]):
Forml dig = new Forml( arl );
// :
dlg.MinimizeBox = false;
dlg.MaximizeBox = false;
d i g .FormBorderStyle = FormBorderStyle.FixedDialog;
dig.Text = "Telephons";

Il
// :
d i g .ShowDialog();

Windows

249

, , ,
main.cs - main:
static ArrayList arl = new ArrayList();
static string FileName = "Telephons";


, .
Array
List, (
MainO). Main()
:
int ret = MyFiles.GetDataFromDB( FileName, arl );
if( ret == -7 )
MessageBox.Show( " ", "" );

, (
, ),

.
(
),
, ,
, Main()
PutDatalntoDB () MyFiles
() :
I I :
MyFiles.PutDatalntoDB( FileName, arl );

.
-

.
, . 9.4 ,
() (1234568)
.
.
,
Input data . , ,
. , ,

250

*J

Telephone
Input data
I

1234568

OK

Exit

. 9.4.

,
,
.
*1

Telephons

16666666

Exit

. 9.5.

,
,
.
(. . 9.6).
. 9.5 ,
1234567.

Windows

Telephons
Input data -

251

*J
H

Ll
1234567

OK

Exit

. 9.6.

,
, ,
. 9.7, .
xj

Telephbns
Input data
[qwerty

OK

Exit

. 9.7.

9.3
,
.
9.3, , C#
Microsoft NET Framework Windows
.
9.3 ,

252

. - ,
-
, ,
.
.

, , ,

.

.
, - ,
, (
), , C++
[2].

Microsoft
Developer Studio NET (2003)
Microsoft Visual C# NET
(2003) Microsoft Visual C++ NET (2003)

Microsoft Developer Studio NET (2003) (


2005 )
NET-, Windows.
- C# C++ ( ).
Microsoft Developer
Studio NET (2003) .

, . .1.
M icrosoft D evelo p m en t Environm ent [d ts n jn ] - [S ta rt J
*X ) File

Edit

View

Tools

Window

.= .|g j_ x j
.

Help

- .3

|t

P ro je c t*

M & P ro U e

&

Open an Existing P roject


M odified

Nam e

Today
5/26/2006

WinAppl
ProjDialogl

5/16/2006

Test

4/22/2006

Lj

New P ro ject ]

R ead/

Open P roject

.. ...................................................................

. .1.

,
, .

254

Tools | Options Options (. .


.2), At startup
"Show Start Page" "Show empty environment",
.
*1

M o t io n s

Environment

G
Qj
GJ
C]
Q)

Settings

Documents
Dynamic Help
Fonts and Colors
Help
International Settings
Keyboard
Projects and Solution*
T a sklist
Web Browser
Source Control
Text Editor
Database Tools
Debugging
Device Tools
HTML Designer

<i

Tabbed documents
< M DIenvronm ent

At startup:_______
| Show Start Page

Reset Window Layout


P* Show status bar
R Animate environment tools
Speed- ---------J ..- ...- +
P Enable Command Window autocompletion
Display

110

items in window menu

Display

14

items in most recently used lists

Docked Tool W'ndow Behavior


P Close button affects acbve tab only
Auto Hide button affects active tab only

J*
OK

Cancel

Help

. .2.

View | Solution Ex
plorer View | Class View, Output (
Output).
Microsoft Developer
Studio NET (2003) .
(. . .).

Microsoft Developer Studio NET (2003)

255

% M icros..ft Developm ent Environment [lt ign]


File

dit

View

lools

Window

.=JSl2<l

El

256

Microsoft Visual C# NET (2003)


, Windows #,
File | New | Project,
New Project, . .4.
New P ro je ct
Templates:

project Types:
Cl
O
. Q
CU
i CD

Cl
Cl

Visual Basic Projects


Visual C# Projects
Visual J# Projects
Visual C ++ Projects
Setup and Deployment Projects
Other Projects
Visual Studio Solutions

}j,K5F,:i4tr,W
B'D'Kppiii:act,6n-----lftASP.NET Web Service
ASP.NET Mobile Web Application
ip W e b Control Library
J p Console Application
g l Windows Service


Empty Web Project
^ N e w Project In Existing Folder

An empty project for creating a local application


Name:

JProjectName

Locatfon:

j E:\MyTmp

^1

growse...

Project will be created at E:\MyTmp\ProjectName.


*M ore

OK

Cancel

Help

. .4.

New Project Visual C# Projects


:
Empty Project, Windows Application Class Library.
, .
,
sin.
(. . .5).

Microsoft Developer Studio NET (2003)

Pro jectN am e - Microsoft: Visual Or


File

Edit

View

- 12^

Project

Build
Debug

257

-NET [d e ttg n j

Debug

Tools
-

[4 *

Window

Help

3 i5? 3 i # -

Solution Explorer-Projects.. ^ x

3
I ^

&

Solution 'ProjectName' (1 project)

) References

.
^ S o l u tio n E xp l...| Class VieN |
lO utput

I
l
Ready

. .5.

Microsoft Visual C# .NET,


, #.
.
C#
.
Project | Add Existing Item.

258

(, )
Project | Add New
Item... (. . .6).
Add New K e rn - ProJectNam e
Categories1

Local Project Items

templates:
IFpl Windows Form
j^ ] Class
cB] Component Class
OJ User Control
^ D a t a Form Wizard
& ^D ata Set
g ] XML File
!jj,| XML Schema

u_

i H
Custom Control
j g HTML Page
Inherited Form
T^W e b Custom Control

A blank code file


Name:

j CodeFilel.es
Open

Cancel

Help

. .6.

"Add New Item" ,


Code File (
#). , Open.
.
.
Build | Build Solu
tion.
F5.

Microsoft Developer Studio NET (2003)

259

Windows Application (
),
()
.
, . .7.
W W indows A pplication! - M icrosoft Visual C # [des- <] - [F* m l.c s s s u
______________________________________________i
File

dit

View

t, '

SP -

a m H

Project

Build

m <o _

Debug

Debug

Data

,:

Tools

Window

, &

..

Help

::

- 1 X

-j & ^

Solution WindowsApplicationl' (1
Q*] W indow sA pplicationl
^jj References
App.ico
[**1 AssemblyInfo.es


Solution E x p l . . . i C l a s s View
Output
Ready

. .7.

,

.
#,
Forml.cs,
View Code (. . .8).
View Designer
.


Properties.
(. . .9).
,
Properties.

260

QC W indows A pplication 1 M icr


File

Edit

uJp -

View

Project

o ft Visual C #
Build

Debug

Solution Explorer - Windows.. X

sja

______

Q J Solution 'Windows Application (1 p


3 W indowsApplication 1
^ References
j App ico
| f ] AssemblyInfo.es
] Forml.cs

Debug

[d - ^ n ] - m U

lools

Window

]]*]

Help

i? x

n d o p p i c - i l.FofiTti

:OirpurrXi

jr ]

"3

0 u s i n g System;

using
using
using
using
U3ing

S y s t e m . Drawing;
S y s t e m . Collections;
S y s t e m . ComponentHodel;
S y s t e m . Windows .Forms;
S y s t e m . Data;

3 namespace UindowsApplicationl

{
///
^

Solution Expl...

Class View

j Output______ _
Ready

Lnl

C o ll

Ch 1

. .8.
|P r o ^ * .rtie s

ill

| F o rm l System.Windows.Forms.Form

<w

- *

3 ]

i'h

AccessrbleRoIe
S p e & ra n c e
BackColor
Backgroundlmage
Cursor
S Font
ForeColor
FormBorderStyle
RightToLeft
Te%t
0 B e h a v i& f

Default
f | Control
1 1 (none)
Default
Microsoft Sans Serif; 25pt
H H ControlText
Sizable
No
F o rm l

__ J

^TeKt

. .9.

Microsoft Visual C#
NET (2003).

Microsoft Developer Studio NET (2003)

261

Microsoft Visual C++ NET (2003)


Microsoft Developer Studio NET (2003)
Microsoft Visual C++ NET (2003) ,
File | New | Project "New Project (Project Types)
Visual C++ Projects (. . .10).
New P ro ject
Project Types.
__I
__|
_J
^
,__|
S CJ
___|

*1

Visual Basic Projects


Visual C# Projects
Visual J# Projects
Visual C ++ Projects
Setup and Deployment Projects
Other Projects
Visual Studio Solutions

Templates:
7 7
? MFC Application
{ M F C DLL
$ jf MFC ISAPI Extension Dll
J * Win32 Console Project
] Win32 Project
^W in d ow s Control Library (.NET)
^ W in d o w s Forms Application ( NET)
i p Windows Service (.NET)

A Console app'-cahon type of Win32 project.


Name:
Location:

j projName
| E:\Documents and Settings\Administrator\My Docurnen

Browse,.

Project will be created at E:\. ..\Administrator\My Documents\Visual Studio Projects\projName.


*M o re

OK

Cancel

Help

. .10.

.
Win32 Console Project (
) Win32 Project (
).

262


, , .
.11.
W in32 A pplication W iza rd - projNanw;

Welcome to the Win32 Application Wizard


This wizard generates a Win32 application project The project can be a Windows application, a
console application, a DLL, or a static library,

These are the current project settings:


Consde application
Click F inish from any window to accept the current settings.
A fter you create the project, see the project's readm e.txt file fo r nformation
about the project features and files that are generated.

Finish

Cancel

Help

. .11.

Application Settings,
(. . . 12).
Empty project,
. Finish .

, sin (
solution).
C++
.
Project | Add Existing Item.

Microsoft Developer Studio NET (2003)

W in32 A pplication W iza rd - p rojN am e

2<J

A p p lic a t io n S e t t in g s
Specify the type of application you will build with this project and the options or libraries you
want supported.

Application type:
Windows application

( Console application

Add support for:

DLL

Static library
Addfcional options:

P* mpixpfoiec
p*

WL

Finish

. .12.

263

Cancel

Help

(, )
Project | Add New
Item... "AddNew Item" (. . . 13).
Add New Ite m - T est Pro j
Templates:

Categories:

Tf ] Windows Form (.NET)

321]

[$] HTML Page ( htm)


5 3 Static Discovery File (.disco)
ji] Header File (.h)
J ) Midi File (.idl)
5 Resource File (.rc)
Server Response File (.srf)
^M od u le-D e fin itio n File (.def)
-^Registration Script (.rgs)
ASP.NET Web Service
j*ATL Server Web Service
Bitmap File (.bmp)

zi

Creates a C + + source file.


Name:

| SomeFileName

Location:

| e:\MyTmp\TestProj\

Browse..

Open

Cancel

Help

..13.

C++ File (.) (


), Header File (.h).
Open
.
,
Ctrl+F7.

F5.

Microsoft Developer Studio NET (2003)

265

Microsoft Developer Studio NET


(2003) , ,
, . . 14.
00 M icrosoft D e v d fu m u n t Environment {design J
File

da

yew

.j&
I Solution Explorer

1a Soiubo...

Tools

Window

..=..15.1 x ll

Help

- (3

3 5* ^

Class ...

Output

ill

........ ................... 3

<1

. .14.

5
9-

Debug

Ready

XI

i
Ln 1

Col 1

fj
Chi

266


(. . . 15).
# 9 TestP roj - M icrosoft Visual C + + [rie tig it] - [S oroef
File

Edit

w? H

View

Project

Build

Debug

Debug

lools

"3

main

int m m (
Solution 'TestProj' (1 project)

He*p

Solution Explorer - TestProj

JO lx J

]
Window

void J

3 J P T e s tP ro j
^

References
Source Files
0 SomeFtleName.cpp
P i Header Files
C l Resource Files

r e t u r n 0;

SJRes... ^Solu... ^Clas... [ 4|

JI

I Output___________________________
0

Task List

Build succeeded

Output
Ln 4

Col 12

Ch 12

INS

. .15.

Win32 Project Project | Add


Resource, "Add Resource" (
- Dialog) - . . . 16.
New.

. (
) resource.h
Project | Add Existing Item.
(
ResourceView )
. "Prop
erties" . , . . 17
.

Microsoft Developer Studio NET (2003)

Add R esource

*1

Resource type:
^
$

New

Accelerator
Bitmap
Cursor

Im port..,
Custom.,

^H SJ

Cancel

HTML

D Icon
Menu

Help

ah? String
Toolbar
m Version

. .16.

Pro***ties
I ID D _D IA LO G l (D ia lo g )
r--: w

ElgEditor

| C3T|R

Set Foreground
System Modal
Visible__________

False
False
False

font
Font(SizeJ
Use System Font
M is c

Center Mouse
Class Name
Context Hrlp

_ fnntfrni____

MS Shell Dlg(8)
True
| iDD_DIALOGi (Dialog)
False

False
- f i a t e ___ ____________

..17.


.
Microsoft Visual ++
NET (2003).

[1]. . . . - .: -, 2006.
[2]. . . Windows C/C++. .1.- .: ,
2004.
[3]. . . Windows C/C++. .2.- .: ,
2006.
[4]. . JL, . ., . ., . ..
.- .: , 2004.
[5]. . . C# .NET- .: , 2006.
[6]. . ., . . #. .-.: -, 2003.
[7]. . Windows 95. .1 .2.- .: BHV, 1997.
[8]. . . Microsoft NET Framework - .:
, 2005.
[9]. . Microsoft Windows #. .2.- .:
Microsoft Press, 2002.
[10]. . ., . . #..: -, 2003.

. .

,
C# JAVA

Web-

'

ISB N 5-9579-0015-

C++

C++

J1. .
ISB N 5-93378-020-0


ISB N 5-91136-006-3

;

I

I
I


ISB N 5-9579-0107-5

,
ISB N 5-93378 063-4


ISB N 5-9579-0082-6

II

:
- ok@kudits.ru
- zakaz@okc.ru
-
121354, . , / 18, " - "
./: (495) 333-82-11, 333-65-67
E-mail: zakaz@ kudits.ru

- : http://books.kudits.ru