Вы находитесь на странице: 1из 744

#

""
-
2004

32.973.26-018.2.75
57
681.3.07
""
. ..
..
"" :
info@williamspublishing.com, http://www.williamspublishing.com

, .
57

#. : . . . :
"", 2004. 752 . : . . . .

ISBN 5-8459-0563- (.)


# , .NET,
: , , , , ,
, , , . #.
C++, Java #
, , . , #.
32.973.26-018.2.75

.

, , ,
Osborne Publishing.
Authorized translation from the English language edition published by McGraw-Hill Companies,
Copyright 2003
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording or by any information storage
retrieval system, without permission from the Publisher.
Russian language edition published by Williams Publishing House according to the Agreement with
R&I Enterprises International, Copyright 2004

ISBN 5-8459-0563- (.)


ISBN 0-07-213485-2 (.)

"", 2004
by The McGraw-Hill Companies, 2003

18

I. #

21

1. #

22

2. #

30

3. ,

53

4.

80

5.

6. ,

102
126

7.

154

8.

179

9.

224

10.

256

11.

277

12. ,

319

13.

349

14. -

375

15.

409

16. ,

431

17. ,

449

18. ,

484

II. #

501

19. System

502

20.

541

21.

575

22.

610

23. Internet

645

III. #

669

24.

670

25. Windows-

689

26.

707

IV.

731

. XML

732

. #

737
"

740

17

18

I. #

21

1. #

22

#
,
C++
Internet Java
#
# .NET Framework
.NET Framework
CLR


2. #
-


csc.exe



Visual Studio IDE
" ", " "





if
for



#

23
23
24
25
26
27
27
28
28
29
30
31
32
32
33
33
34
34
34
35
35
38
40
41
42
44
45
45
47
48
50
50
51
51
52

3. ,

53


#


decimal

54
54
55
57
58
60

bool













4.








, ,


?

61
62
65
65
66
66
68
68
69
70
72
73
74
76
78
80

81
82
84
87
89
89
90
90
96
99
99
101
101

5.

102

if
if-
if-else-if
switch
switch
for
for





for
while
do-while
foreach
break
continue
return
goto
6. ,

103
104
105
106
110
110
112
112
114
115
116
116
117
117
119
120
120
122
123
123
126
127

Building



Building


Building
new
new
""

this
7.



" "






Length
Length
\
foreach

.




switch-
t
8.
*

#
public private
:


ref- out-
ref
out
ref out

127
128
132
133
134
134
137
138
140
142
144
144
146
146
147
148
149
149
151
154
155
155
157
158
159
159
160
161
162
164
165
167
168
172
172
173
175
177
178
179
180
180
182
182
187
189
191
191
193
195
197
199




this
Main()
Main()
Main()

static

9.

224




#-

true false
"

,



10.

225
226
228
232
236
237
240
~240
242
246
250
251
256

257
257
260
263
264
266
271
271

11.

277







base







sealed
object

object

202
203
208
212
213
213
213
215
218
223

'

278
281
283
285
286
290
291
293
296
297
301
305
305
309
313
313
315
317

12. ,

319











.NET Framework
:




13.
System. Exception

try- catch-




catch-

try-



finally
4
" '



checked unchecked
14. -
#- -



Stream



-


FileStream -

320
321
325
327
328
330
331
331
332
333
334
334
335
340
343
345
347
347
347
349
350
350
351
351
353
354
356
357
358
358
360
360
362
363
365
367
370
372
375
376
376
376
377
377
378
378
380
380
380
382
383

10


FileStream

FileStream
-
StreamWriter
StreamReader


BinaryWriter
BinaryReader
-

MemoryStream
StringReader StringWriter

383
385
386
387
389
389
391
392
394
394
395
396
400
402
404
405

15.


System.Delegate






.NET Framework
EventHandler
:

409

16. ,




using
using


#define
#if #endif
#else #elif
#undef
#error
#warning
#line
#region #endregion
internal
internal
17. ,

410
413
415
416
416
418
419
421
425
426
428
429
431

432
432
434
436
437
438
440
441
441
442
442
444
445
446
446
446
447
447
447
449

450
11

is
as
typeof

: System.Type


GetMethods()









AttributeUsage
Conditional
Obsolete
18. ,




"*" "&"
unsafe
fixed









sizeof
lock
readonly
stackalloc
using
const volatile
II. #
19. System

System
Math



12

450
451
453
454
454
455
455
458
459
462
466
471
474
474
474
475
475
477
480
480
481
482
484

485
486
486
487
487
488
489
489
491
492
492
494
494
495
496
496
496
496
497
498
499
501
502

503
504
509
510
511

Decimal
Char
Boolean
Array



BitConverter
Random
GC
Object
IComparable
IConvertible
ICloneable
IFormatProvider IFormattable
20.

#
String
String
, String
String
String





,
""
Substring()



String. Format() ToString()

String. Format()
ToString()

-



21.


Thread



,
IsBackground

514
518
523
523
524
526
527
532
534
536
537
537
538
538
540
541

542
542
543
543
544
544
544
547
549
552
555
556
557
558
558
559
560
561
562
564
565
565
569
571
573
575

576
577
577
580
581
583
585
586
588
13



Monitor lock
Wait(), Pulse() PulseAll()
Wait() PulseQ

MethodlmplAttribute
,
Abort()
Abort()




22.



ICollection
IList
I Dictionary
IEnumerable, I Enumerator I Dictionary Enumerator
IComparer

IHashCodeProvider
Dictionary Entry

Array List
Array List-

Hashtable
SortedList
Stack
Queue
BitArray



I Dictionary Enumerator
,
IComparable
IComparer

23. Internet

System.Net

Internet-
WebRequest
WebResponse
HttpWebRequest HttpWebResponse


, Create()
, GetReponse()
14

592
593
594
594
595
598
599
601
603
604
606
606
608
608
610

611
612
612
613
614
615
615
616
616
616
617
621
622
623
625
629
631
633
636
636
637
638
639
641
642
644
645

646
647
647
648
650
650
650
653
653
654

, GetResponseStream()

UR1
HTTP-

cookie-
LastModified
: MiniCrawler
WebClient

III. #

654
654
656
657
658
659
660
661
665

"

24.



#-

#- -
IComponent

Component

CipherLib
, CipherComp
Dispose()
Dispose(bool)

using



25. Windows-

Windows-
Windows-,

Windows
Windows-
Form
Windows-,
Windows-

(IDE)









26.

669
670

671
671
672
672
672
673
673
674
675
676
677
678
683
684
685
686
688
689

690
691
691
692
692
692
694
694
695
695
696
696
696
697
699
700
702
706
707

708
709

15








IV.
. XML
XML
XML-
XML-
. #

16

710
711
713
719
720
728
728
731
732
733
734
734
737
740


(Herbert Schildt) , , C++, Java #. 3 . . , , C++, C++: A Beginner's Guide, C++from the Ground Up, Java 2: A Beginner's Guide
Windows 2000 Programming from the Ground Up.
( . ). : (217) 586-4683.


, - :
, . , , , . , - . .
, .
, (, , ) . , : .
#.
Microsoft .NET Framework, #
. (Anders Hejlsberg).
# - : C++.
, . , C++. , #
: Java. ,
, # Java " ". ,
,
.
, , # , . , # , (), , .
, ;
, COM (Component Object Model
Microsoft , , ).
. Java # , . ,
Java, C# . , #
C++ Java, (type checking)
(template class). , # , ( ).

,
. # . ,
# . , .


# . # , # .
, .
I, #.
II, #.
III, #.
I #.
, , ,
, - ,
.
II #. .NET Framework.
. .NET Framework , II , System. #. , , .
, #.
III #. 24 , 25 Windows Windows Forms. 26
(recursive descent parser).


.
C++ Java, # ,
# . , #,
, .


, Visual Studio .Net 7 ( ),
.NET Framework.

- Web-
, , Web-
: www.osborne.com.

19


# "" , . ,
.
#
#: A Beginner's Guide.
, C++, :
C++: Beginner's Guide
C++
Teach Yourself C++
C++from the Ground Up
STL Programming from the Ground Up
The C/C++ Programming Annotated Archives
, Java,
:
Java 2: Beginner's Guide
Java
Java 2: Programmer's Reference
, ,

Teach Yourself

ILJ
, , . , ,
.
,
. , Web-
. ,
, , ,
.
, ,
. . :
E-mail

info@williamspublishing.com

WWW

http://www.williamspublishing.com

115419, , / 783
1
03150, , / 152
20

#
I #. ,
. ,
# (,
-
), #.

# . , .
, , #
.
# ( Microsoft .NET Framework) . # ,
Windows, Internet, .
# "" .
# , ,
. # .NET Framework.

#
. , .
" "
, , .
.
#.
# "" . ( C++)
Java.
#. #
.

,
.
(Dennis Ritchie) 1970- PDP11 DEC (Digital Equipment Corporation), UNIX. , Pascal,
, .
1960- .
,
"-" (spaghetti code) goto.
.
, . .

1. #

23

, , , , .
, (
), . ,
, , ,
, . 1980-
.
.
. , . " " , ,
,
5 000.

C++
1970- , " ". ,
. - (). ,
, . , , , . C++.
C++ (Bjarne Stroustrup)
Bell Laboratories ( , -), 1979-.
" ", 1983
C++. C++ . , , C++. , , - . , C++ . "" C++ , "" . , - , .
1980- C++ 1990-
. ,
. C++ -
.
, C++ .
. ( ) , .

24

I. #

Internet Java

Java, Oak ( . "").
1991 Sun Microsystems.
Java (James Gosling).
(Patrick Naughton), (Chris Warth), (Ed
Frank) (Mike Sheridan).
Java - , "" C++. Java
( ), . Internet ,
. , ,
, ,
. Internet,
,
. , Java.
, , Java (
) ( ) , Java Internet, a
,
. 1993 , , ,
Internet.
Internet , "" . ,
,
.. Internet.
Java
, - (bytecode), .. , Java-. - Java (Java Virtual Machine JVM) -
. , Java- , JVM. JVM ,
.
Java- - - ++, .
. , /++- ,
, . , /++-,
, ()
. . ,
Java- . #.

1. #

25

, Java C++. , C++.


Java- C++ , ,
, C/C++- Java. ,
Java ( ), .
" "
C++, Java . , Java ,
C++ "" "" .

#
Java , Internet, .
(cross-language interoperability)
, (mixed-language programming). , ,
. (),
, ,
.
, Java Windows.
Java- Windows ( Java), Java Windows . Windows ,
Windows Java.
, Microsoft #. # 1990- .NET- Microsoft.
- 2000 . #
(Anders Hejlsberg) , . ,
1980- Turbo Pascal, .
# , C++ Java. .
. ,
C++,
Java. # , ,
"" ""
.
"", .
# . 1.1. "" # .
# , .
, # , C++.
C++, # .
# Java . , Java
C++.
. Java C# .
# Java. # Java , ,
26

I. #

"". Java, #. , Java, , #,


Java.

C++

Java

. 1.1. #
# , .
.
# - . , #
, : ,
. -
.

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

.NET Framework
.NET Framework
, .
" "
, Windows. , .NET Framework no
Windows, .. ,
, , Windows.
.NET Framework #
. , Common Language Runtime (CLR), ,
. CLR
.NET Framework, ,
.
1. #

27

, .NET-,
. , , , - , .NET- . ,
. , : , .
, .NET-
, (.. ), .NET. # .NET- , # .NET-.

- J CLR
CLR .NET-. . , , , Microsoft
(Microsoft Intermediate Language MSIL). MSIL , . , MSIL . MSIL - Java,
.
CLR-
. , , MSIL-,
, CLR-.
.NET Framework
.
, Microsoft,
-. "" . "yust-/n-rime",
( ). .
.NET- CLR- -,
MSIL- "" ,
. , "" , , MSIL-. ,
,
"" , ""
MSIL-.
MSIL- (metadata). , ,
. ,
MSIL-.

I
, (managed code). CLR. ,
. , 28

I. #

, , MSIL-, CLR-, , -,
.NET Framework. ,
, , .
? Windows- .NET Framework , CLR-. ,
#- .


,
CLR-, ,
,
(Common Language
Specification CLS). , . CLS- ,
, . CLS-
(Common Type System
CTS). CTS- . , #
CLS-, CTS-.

1. #

29

, , ,
.
, , "". # . . #, ,
. , .
I.

-
# - (). - #, # - . ,
,
.
"", .
, , . ,
(
) . ,
. ,
, . (,
FORTRAN COBOL), . , .

, .
, ,
, - , . " " - . , ,
. ,
- .
- .
.
, :
(.. , , ), (..
, ). . , .
2. #

31

- -. , : . - ,
. , ,
.
-
-, #, : , .

, () , , . -
,
. . . , ,
.
,
.
. ,
,
. , ( ,
) .
,
.
# .
. , , .
# . .
, , , .
, , . , , (instance variable), , , - (member method),
. "" , # . C++, , , ,
, #- , /++- .
# C++, "" , #-.

( polymorphism, " ")


, . .
() , . , : ,
. ,
. , , , ,
, , .
32

I. #

. , , (stack), .. , "
". , ,
. , , . , . "" , . #
"" ,
. , , ,
.
: "
". ,
.
, . (
) () . . .

,
.
. ()
. , ,
, . , (, .), . , (, .), . ,
( , .).
, .
, .
, , () . , .


.
/*
.
Example.cs.
*/

2. #

33

using System;
class Example {
// Main()
public static void Main() {
Console.WriteLine(" .");

# Visual Studio .NET. , , : c s c . e x e (Integrated Development Environment IDE). . (


, , .)

esc.
, , Visual Studio, # , . #- .
1. , .
2. .
3. .


, , Web-
Osborne : www.osborne.com. . - , Notepad. ,
, , , #-. ,
Example. cs.


, #-, c s c . e x e ,
.
C:\>csc Example.cs
esc Example.exe,
MSIL- . MSIL- , -. Example.exe
Common Language Runtime -.
: Example. ( -, MSIL-) , .NET
Framework, CLR.
34

I. #

csc.exe , , vcvars32 .bat, //Program


Files/Microsoft
visual studio .NET/Vc7/Bin. .
# Microsoft Visual Studio
.NET&Visual Studio .NET Command Prompt ^Visual Studio .NET Tools
^, .


.
I :\>Example
:
I .

Visual Studio IDE


7 Visual Studio .NET, Visual Studio
IDE . ,
Visual
Studio ( 7), . (
Visual Studio, , .)
1. () #-, File^New^Project
( <=> => ).
2. ( Project Types ( )) Visual C# Projects ( Visual C#), ( . 2.1) Templates () Empty Project
( ).
New Project
Templates:

Project Types:
wJ Visual Basic Projects
il* Visual C# Projects
' (LJ Visual C++ Projects
; d Setup and Deployment Projects
E&J Other Projects

ASP.NET
Web Ap...

ASP.NET Web Control;:


WebS...
Library

I P
Console
Application

Windows
Service

' Visual Studio Solutions

;An empty projectforcreating a local application


jProjectl
J D:\Work\Nina\Visual Studio Projects
location:
Project will be created at D:\WorkVSIina\Visual Studio Projects\projectl.
OK

Cancel

Browse..
Help

Puc. 2.1. New Project ( )

2. #

35

3. ,
S o l u t i o n Explorer ( ) ,
, Add^Add New Item (^
) , 2 2
4. Add New Item ( ) Categories () Local Project Items ( ), Templates Code File (
) , 2 3

I] >
Sou
l to
i n Projectl (1 project)
li
+ a Bud
Rebud
li
c r HA<&Newtlem
A$j
f\
Add Existing Item
Add Reference
tJ New Fod
l er
Add Web Reference
Add Wn
idows Form
Set as Startup Project
.3 Add Inherited Form
Debug
>i
Save Projectl
Add User Control
3 Add Inherited Confrol
X Remove
ij Add Component
Rename
Add Ca
lss

Properties

2 2
Add&Add New Item

User Control Data Form


Wizard

XML File

Name

Data Set

XML
Schema

IcodeFilelcs
Open

Cancel

Help

2 3 Add New Item


36

I. #

5. Example.cs. (, , , Web Osborne : www.osborne.com.)


, . 2.4.
f Exampte.cs*

1 I F
#-.
Example.cs.

using System;
*"j class Example

iL
. 2.4. Example, cs

6. Build^Build Solution (1^ ).


7. Debug^Start Without Debugging
( ).
, . 2.5.
!^D:\Work\Nta\V^
-.
Press any key to continue,

;*!

. 2.5. Add New Item

\\\'d

,
, . #-.
. .

2. #

37

, ( ) , , , , .

" ",
" 9'
, Example.cs , .
, .
(, Java),
, #-
.
Example, cs, , , Sample, cs, T e s t . c s X.cs.
.cs,
. , .
( , , ) Example.cs.
, . ,
.
.
/*
#-.
Example.cs.
*/
. # , .
, , , .

Example.cs. ,
.
# . , , . /* , (*/).
, , . , , .
.
I u s i n g System;
, System. #
(namespace) . , , . , , ,
, .
System, , .NET Framework, #.
38

I. #

using , .
.
1 c l a s s Example {
c l a s s , . , # . Example .
({) (}) . ,
, , . , ,
# . ,
-.
.
I // Main().
, #.
/ / .
,
, ()
.
.
I p u b l i c s t a t i c void Main() {
Main(). ,
# (method). , . #-
Main (). ( : /++-
main().)
, #.
,
.
p u b l i c (access specifier).
, . p u b l i c ,
, ,
, . (
p u b l i c p r i v a t e , , () .) Main () public-, ( ) (
).
1

#
, Main () public-. , Visual Studio .NET. -.
Main () public.
,
Main ().

s t a t i c Main() . ,
2. #

39

Main () . void
, Main () .
, .
Main () , . , Main () ( ) , .
({), Main().
,
.
. ,
Main ().
I Console.WriteLine(" #-.");
" #-. "
. WriteLine (). ,
. .
, WriteLine () . Console
, -
. Console WriteLine (),
, WriteLine () Console. , # ,
- .
, ,
WriteLine (), ,
u s i n g System. # .
, , , .
(}) Main (),
Example.
. # .
. ,
Main main WriteLine w r i t e l i n e , . , # , Main (),
. , Main
(main), . , , Example.exe .


, (
). . ,

(). #- - , "".
, "" ,
. , 40

I. #

( ) , IDE "" , 2 6 (
esc)

Description

__

, expected
Type or namespace definition or end of file expected

File

_ _

_ trie

D \Work\Nma\Visual \Projectl\fxampte cs

13

D \Work\Nna\Visual \Projectl\|Example cs

17

i
2 6
, ,
,

, , " "
, , , "" , , "" "
"



I u s i n g System;
, , , #
, ,
I Console.WriteLine(" #-.");


I System.Console.WriteLine(" #-.");
,
// u s i n g System.
class Example {
// #- ( ) .
public static void Main() {
// Console.WriteLine .
System. Console. WriteLine ( " . ") ;

2. #

41

System ,
, #-
u s i n g System ( ,
). , , , .


, .
, . . ,
, .
.
// .
u s i n g System;
c l a s s Example2 {
p u b l i c s t a t i c void Main() {
i n t x; // .
i n t ; // .
= 100; // 100.
Console.WriteLine("

" + ) ;

' - / 2;
Console.Write(" / 2: " ) ;
Console.WriteLine();

:
100
/ 2: 50

? ,
I i n t x; // .
. # . , . .
, .. . #
i n t . , i n t x; i n t .
.
I i n t ; // .
, ,
. .
, , :
42

(. #

_;
, _ . i n t , C#
.
100.
I = 100; // 100.
# (=).
, ,
, .
,
" ".
1 Console.WriteLine(" " + ) ;
"" , . , " + " , WriteLine ()
.
, 2.
| - / 2;
2,
. ,
50. . , #
, :
+

:
Console.Write(" / 2: " ) ;
Console.WriteLine();

. -, "
/ 2: " WriteLine (),
Write (). . ,
. , Write ()
WriteLine (), , . -, ,
WriteLine () , .. . , WriteLine (),
Write () #-.
,
. . ,
:
I i n t , ; // .

2. #

43


i n t . i n t . , . , int-
18, 18,3. , i n t
, #.
# , f l o a t double,
, . (
double " ".)
double , :
I double r e s u l t ;
r e s u l t double. r e s u l t
double, , 122,23, 0,034 19,0.
i n t double,
:
/*

int double.
*/
using System;
class 1 {
public static void Main() {
int ivar;
// int.
double dvar; // double.
ivar = 1 0 0 ;

// ivar
// 100.

dvar = 100.0; // dvar


// 100.0.
Console.WriteLine(
" ivar: " + ivar);
Console.WriteLine(
" dvar: " + dvar);
Console.WriteLine(); // .
// 3.
ivar = ivar / 3;
dvar = dvar / 3.0;
Console.WriteLine("ivar : " + ivar);
Console.WriteLine("dvar : " + dvar);

:
I i v a r : 100
I dvar: 100
44

I. #

lvar : 33
dvar : 33.3333333333333
, i v a r 3 , 33, .. .
dvar 3 .
, , . , . , # 100
, 100.0 .
,
WriteLine .
, .. . ,
^ , 3,1416.
// .
using System;
class Circle {
static void Main() {
double radius;
double area;
radius = 10.0;
area = radius * radius * 3.1416;
Console.WriteLine(" " + area);

:
I 314.16
, .


, ,
.
, #. , , , .

i f
i f
. i f #
. , C++
Java, . :

i f () ;
2. #

45

(
). , . ( ) . :
I i f (10 < 11) Console.WriteLine("10 1 1 " ) ;
10 11, .. , WriteLine () . :
I i f ( 1 0 < 9) Console.WriteLine(" . " ) ;
10 9, WriteLine ()
.
# , . :
<

<=

>

>5

==

!=

if.
// if.
using System;
class IfDemo {
public static void Main() {
int a, b, c;
a = 2;
b = 3;
if(a < b) Console.WriteLine(" b " ) ;
// ,
if(a == b) Console.WriteLine(
" .");
Console.WriteLine();
= - b; // -1.
Console.WriteLine(" - 1 " ) ;
if( >= 0) Console.WriteLine(
" ");
if( < 0) Console.WriteLine(" ");
Console.WriteLine();
= b - ; // 1.
Console.WriteLine(" 1");
if( >= 0) Console.WriteLine(
" ");
if( < 0) Console.WriteLine(" ");

46

I. #

:
b
-1

1

.
1 i n t a, b, ;
, . , ^
, .

f o r
, . #
. for.
, C++ Java, , for #
, . for .
for{; ; ) ;
. , . , for
, .
, ,
. , for.
//

for.

using System;
c l a s s ForDemo {
public s t a t i c void Main() {
i n t count;
for(count = 0; count < 5; count = count+1)
Console.WriteLine(" : " + count);
Console.WriteLine("!") ;

:
: 0
: 1
: 2
: 3
: 4
!

2. #

47

count.
for . ( ) count < 5.
, WriteLine (),
.
, , , .
, #-,
, ,
. ,
, :
I count = count + 1;
, # , . "" (++)
:
I

COUnt++;

, for
:
I f o r ( c o u n t = 0; count < 5; count++)
, , , .
# (). ,
.

U
, , #
.
. .
, , . ,
_ if- for-. if-:
i f ( w < h) {
v = w * h;
w = 0;
}

w h, , w < h,
. ,
,
. , ,
, .
.
, .
I // .

48

I. #

using System;
class BlockDemo {
public static void Main() {
int i, j, d;
i = 5;
j = 10;
// if-
// , ,
if(i != 0) {
Console.WriteLine("i ");
d = j / i;
Console.WriteLine("j / i " + d);

:
i
j / i 2

i f- ,
. if- (
), ,
. .
| i = 5;

i = 0;
.
. 1 10 .
// 1 10.
using System;
class ProdSum {
static void Main() {
int prod;
int sum;
int i;
sum = 0;
prod = 1;
for(i=l; i <= 10; i++) {
sum = sum + i;
prod = prod * i;
Console.WriteLine(" " + sum);
Console.WriteLine(" " + prod);

:
2. #

49

I 55
I 3628800
( ) ,
.
for-.
. . , ({ })
. ,
, .



# , .. .
, , .
,
( ).
# ; ,
. , #
= ;
= + 1;
Console.WriteLine(x

+ "

" + );

.
I = ;
= + 1; Console.WriteLine(x + " " + ) ;
,
. , .
Console.WriteLine(" " +
+ + z +
" , ");


, , , , . # ,
, .. , . , . , , , . ,
( ),
( ).
, .
50

I. #

#
# 77 , . 2.1. ( ) #. , .

2.1. #
abstract

event

new

as

explicit

null

switch

base

extern

object

this

struct

bool

false

operator

throw

break

finally

out

true

byte

fixed

override

try

case

float

params

typeof

catch

for

private

uint

char

foreach

protected

ulong

checked

goto

public

unchecked

class

if

readonly

unsafe

const

implicit

ref

ushort

continue

in

return

using

decimal

int

sbyte

virtual

default

interface

sealed

volatile

delegate

internal

short

void

do

is

sizeof

while

double

lock

stackalloc

else

long

static

enum

namespace

string

# , ,
, .
.
. ,
.
, l i n e _ c o u n t . # , .. myvar MyVar . .
Test

2
MaxLoad
up
_top
my_var
sainple23
, . , 12
. ,
,
, .

2. #

51

# , "" ,
"@". , @for
#-. , - for, @ .
, @ -.
//

@-.

using System;
c l a s s IdTest {
s t a t i c void Main() {
i n t @if;
/ / if

for(@if = 0; @if < 10; @if++)


Console.WriteLine("@if " + 0 i f ) ;

, @if .
@if
@if
@if
@if
@if
@if
@if
@if
@if
@if

0
1
2
3
4
5

7
8
9

( )
- . , @
( ),
.

-J #

, ,
#- WriteLine () Write (). ,
Console, System,
.NET Framework. , #-
.NET Framework, -, , (GUIs). , # # ( ) .NET-. , #. #-,
. I .NET-, .NET-
II.

52

I. #

#: ,
. ,
. #
, .
, # .


# , # . ,
. . ,
. , ,
. , ,
. , , . , , .

#
# :
. , .
# 13 , . 3.1. ,
# .
" " , . ( :
.) , #
, (, C++).
.
# .
, # . , i n t .
.

,
.
3.1. #

bool

, , /

byte

8-

char

decimal

double

54

I, #

. 3.1

float

int

long

sbyte
8-
short

uint

ulong

ushort


# : char, byte, sbyte, s h o r t , u s h o r t ,
int, u i n t , long ulong. char
( ). .
. 3.2.
3.2.

byte
sbyte

8
8
16
16
32
32
64
64

short
ushort

int
uint
long
ulong

0-255
-128127
-32 768-32 767
0-65 535
-2 147 483 648-2147 483 647
0-4 294 967 295
-9 223 372 036 854 775 808-9 223 372 036 854 775 807
0-18 446 744 073 709 551615

, # :
, .
.
, , ,
(sign flag). , , , 1, .
.
, , , . , .
,
, ( )
"" . ,
32 767 s h o r t :
01111111 11111111
3. ,

55

1,
1 ( ).
, u s h o r t ( "" ), 65 535.
, i n t .
i n t , . ,
, i n t , . , u i n t ( ). , , long, ulong. , , ,
. ,
long.
// .
using System;
class Inches {
public static void Main() {
long inches;
long miles;
miles = 93000000; // 93 000 000
// 5 280 , 12
inches = miles * 5280 * 12;
Console.WriteLine(" : " +
inches + " .");

:
1 : 5892480000000 .
, i n t u i n t .
b y t e
sbyte. b y t e 0 255.
b y t e , ,
. sbyte. b y t e for, 1 100.
// b y t e .
using System;
class Use_byte {
public static void Main() {
byte x;
int sum;

56

I. #

sum = 0 ;
for(x = 1; x <= 100; x++)
sum = sum + x;
Console.WriteLine("
+ sum) ;

1 100 "

:
I 1 100 5050
for 0 100 , byte, , .
, ,
byte sbyte, , i n t u i n t , short
ushort.

.
: f l o a t double. f l o a t 32
, 1,545 3,4+38.
double (.. ) 64 , 5324 1,7+308.
double. double-
# ( .NET Framework). , Sqrt (), System.Math, double-,
double-. Sqrt () , .
// .
using System;
c l a s s FindRadius {
p u b l i c s t a t i c void Main() {
double r;
double a r e a ;
area = 10.0;
r = Math.Sqrt(area / 3.1416);
Console.WriteLine("

" + ) ;

:
| 1.78412203012729
3. ,

57

,
S q r t ( ) : Math. , ,
, Sqrt () Math. ( WriteLine () Console.)
, "" .
, #.
double. ,
( ) 0,1 1,0.
// Math.Sin ,
// Math. Cos () n M a t h . T a n O .
using System;
class Trigonometry {
public static void Main() {
double theta; // .
for(theta = 0.1; theta <= 1.0; theta = theta + 0 . 1 ) {
Console.WriteLine(" " + theta +
11
" + Math.Sin(theta));
Console.WriteLine(" " + theta +
" " + Math.Cos(theta));
Console.WriteLine(" " + theta +
" " + Math.Tan(theta));
Console.WriteLine();

:
0.1 0.0998334166468282
0.1 0.995004165278026
0.1 0.100334672085451
0.2 0.198669330795061
0.2 0.980066577841242
0.2 0.202710035508673
0.3 0.29552020666134
0.3 0.955336489125606
0.3 0.309336249609623
, Math. Sin (), Math.Cos () Math.Tan(). Math. Sqrt ()
double
double. .

J T n n

decimal

, # decimal, , .
decimal 128 7,9+28 58

I. #

128 .
.
decimal, 28 ( 29).
.
, decimal
.
// decimal .
using System;
class UseDecimal {
public s t a t i c void Main() {
decimal price;
decimal discount;
decimal discounted_price;
// .
%
price = 19.95m;
discount = 0.15m; // 15%.

discounted_price = price - ( price * discount);


Console.WriteLine(" : $" +
discountedjprice);

:
: $16.9575
, decimal- . , decimal. decimal (,
10) . (
.)
decimal. , .
/*
decimal
.
*/
using System;
class FutVal {
public static void Main() {
decimal amount;
decimal rate_of_return;
int years, i;
amount = 1000.0M;
rate_of_return = 0.07M;
years = 10;

. ,

59

Console.WriteLine(" : $" + amount);


Console.WriteLine(" : " + rate_of_return);
Console.WriteLine(" " + years + " ");
for(i = 0 ; i < years; i++)
amount = amount + (amount * rate_of_return);
Console.WriteLine(" $" +
amount);

:
: $1000
: 0.07
10
$1967.15135728956532249
( ) !
, , .

# 8- ,
(, C++), 16-.
# Unicode (), 16- ,
.
(, , , ) , (, ),
, .
"" , 16-
. , # char 16- , 065 535. 8-
ASCII Unicode 0127.
, ASCII- #-.
,
. , X ch, :
1 char ch;
I ch = 'X';
char-, ch,
WriteLine ().
I Console.WriteLine(" ch: " + ch) ;
char # , . , char .
, .
char ch;
ch = 10;
// , .

10 ,
char.
. " ",
.
60

I. #

b o o l
bool /, #
t r u e f a l s e . , bool . # bool . , 1
t r u e , 0 f a l s e .
bool :
// b o o l .
using System;
class BoolDemo {
public static void Main() {
bool b;
b = false;
Console.WriteLine("b " + b ) ;
b = true;
Console.WriteLine("b " + b ) ;
// bool if-.
if(b) Console.WriteLine(" .");
b = false;
if(b) Console.WriteLine(
" .") ;
// bool.
Console.WriteLine("10 > 9 " + (10 > 9));

:
b False
b True
.
10 > 9 True
, ? -, bool-
WriteLine True False. -,
bool- if-, ..
if- .
1 i f ( b == t r u e ) . . .
-, (,
"<") bool-. 10 > 9 True. 10 > 9,
, ,
" + " , ">".

3. ,

61


WriteLineO
, #. # , . - ,
. , , . ,
, #.
"".
:
Console.WriteLine(
" " + 2 + " $" + 3 + " .");

,
"" . ,
,
13. :
Console.WriteLine(
" 10/3 : " + 1 0 . 0 / 3 . 0 ) ;
:
| 10/3 : 3.33333333333333
, ,
. , .

WriteLine (), .

WriteLine (" ",


argO, argl, . . . , argN);
WriteLineO , " + " . _ : "" "".
, " ",
. :
{_ , : )
_
( ). , .
WriteLineO
, ( ) , _. , _ , , . . ,
{0} , {1} argl ..
.

62

I. #

I Console.WriteLine("

{0} {1} . " , 28, 2 9 ) ;

:
I 28 2 9 .
, {0} 28,
{1} 29. ,

( 28 29). ,
" + " , .
"" , .
Console.WriteLine(
" {0,10} {1,5} . " , 28, 2 9 ) ;

:
I
28
2 9 .
, , . ,
. , .
, , ,
. ,
> .
// .
using System;
class DisplayOptions {
public static void Main() {
int i ;
Console. WriteLine ( "^^") ;
f o r ( i = 1; i < 10;
Console.WriteLine("{0}\t{1}\t{2}" /


1
1
1
2
4
8
3
9
27
64
4
16
5
25
125

36
216
7
49
343
64
512
8
9
81
729
. , .
. ,
WriteLine (). *'#", . 3. ,

63

, . 10 3. .
Console.WriteLine(
"

10/3

{0:#.##}",

10.0/3.0);

-:
I 10/3 : 3.33
# . ##, WriteLine () . , , , .
.
Console.WriteLine("{0:###,###.##}",

123456.56);

:
| 123,456.56
, . :
decimal balance;
balance = 12323.09m;
Console.WriteLine(" {0:C}, balance);
:
I $12,323.09
, .
/*

.

*/
using System;
class UseDecimal {
public static void Main() {
decimal price;
decimal discount;
decimal discounted_price;
// .
price = 19.95m;
discount = 0.15m; // 15%.
discounted_price = price - ( price * discount);
Console.WriteLine(" : {0:}",
discounted_price);

, ,
:
I : $16.96
64

I. #


# , . , 100 . . ,

. .
#- .
. ,
. , ' \ f % ' .
. , 10
-100 . , . 11.123.
# (
).
# , .
: ? ,
, 12, 123987 0.23? , # , .
-, , , , i n t .
, , ,
i n t , u i n t , long ulong. -,
double.
, #, , . long, 1 L. , 12 i n t ,
12L long. , U. , 100 i n t ,
100U u i n t . u l
UL (, 987 654UL ulong).
f l o a t , f F (,
10.19F).
decimal, m (,
9. 95).
i n t - , uint-, long-
ulong- , byte, sbyte, s h o r t u s h o r t , , , .


, , 16, . 0 9 F,
"" 10, 11, 12, 13, 14 15. ,
10 16. #,
, 3. ,

65

.
( ""). .
count = OxFF; // 255
i n c r = Oxla;
// 26


,
, (,
),
. , ,
# , .
# (ESC-), . 3.3.
, .
, ch :
ch =

'\t';

ch :
ch = \';

3.3.
ESC-
\
\
\f
\
\
\t
\v
\0
\f
\"
\\

()

( )




-
()


# : .
, . ,
I " "
. ( WriteLine ()) .
, . , , . ESC-, \n, \ t \ " .
II/
ESC- ,
u s i n g System;
66

I. #

class StrDemo {
public static void Main() {
Console.WriteLine(
" \ \ ");
Console.WriteLine ("OflMH\tflBa\tTpii") ;
Console.WriteLine (llepe\t\tec") ;
// .
Console.WriteLine("\"3?\", .");

"?", .
, \
,
WriteLine () . , , ESC \. ,
( ESC- \ " ) .
(verbatim) . @, , .
. , , ., . (").
,
(""). ,
.
// .
u s i n g System;
c l a s s Verbatim {
p u b l i c s t a t i c void Main() {
Console.WriteLine(@"
,
.
1 2
5 6

Console.WriteLine(@" :
3
4
7
8
Console.WriteLine(
@" : "" # . " " " ) ;

3. ,

67


,
.
:
1 2
3
4
5
6
7
8
: " #."
,
, .
, .

.
, .
. . (,
X') char. ,
(, "X"), - .


2,
:
_;
, _ . .
. , . ,
bool . , .
, m t char.
# . , , , , ""
. "" # .
. , , , , .


.
.
. .
:

68

_ ;

I. #

, , , . .
:
i n t count = 1 0 ; // count
// 10.
char ch = 'X 1 ;
// ch X.
f l o a t f = 1.2F
// f
// 1.2.
(
)
. ,
i n t a, b = 8, c = 1 9 , d; // b
// .



, # , , . , , , , .
// .
using System;
c l a s s Dynlnit {
p u b l i c s t a t i c void Main() {
double s i = 4 . 0 , s 2 = 5 . 0 ;

// .

// hypot.
double hypot = Math.Sqrt( (si * s i ) + (s2 * s2)

'
);

Console.Write(" " +
s i + " " + s2 + " " ) ;
Console.WriteLine("{0:#.###}.",

hypot);

:
I 4 5 6.4 03.
: s i , s2 hypot. ( s i
s2) , , hypot,
. ,
M a t h . S q r t ( ) . ,
,
. Math. Sqrt () ( ) ,
hypot. , ,
, , .
3. ,

69

, , Main(). # .
, .
, (scope) .
, ,
, .
.
# , . ( , )
, ,
, .
, ,
. ,
.
, , , (.. ) , .
, / .
.
. ,
.
. , ,
, . : , , .
,
:
// .
using System;
class ScopeDemo {
public static void Main() {
int x; //
// Main().
= 10;
if( 10) { // ,
int = 20; //
// .
// .
Console.WriteLine(" : " + + " " + ) ;
= * 2;
}
// = 100; // ! .
// .
Console.WriteLine(" " + ) ;

70

I. #

, Main () .
i f .
, . , ,
I // = 100; // ! .
. ,
, if-.
if-,
(.. ) , .
,
. ,
, . , ,
, .
,
. ^
. , , , . , ,
. , .
,
, ,
, , :
//

using System;
class VarlnitDemo {
public s t a t i c void Main() {
/
int x;
for(x = 0; x < 3; x++) {
int = -1; //
// .
Console.WriteLine(" : " + ) ; //
// -1.
= 100;
Console.WriteLine(" : " + ) ;

:
; - 1
: 100
: - 1
: 100
: -1
: 100

3. ,

71

, for
1. 100, .
:
, , ,
, , . , - .
/*

,
, .
***

. ***

*/
using System;
class NestVar {
public static void Main() {
int count;
for(count = 0; count < 10; count = count+1) {
Console.WriteLine("This is count: " + count);
int count; // !!!
for(count = 0; count < 2; count++)
Console.WriteLine(" !");

C/C++, ,
, , . , C/C++ count
for .
.
#, , , .


. , ,
f l o a t i n t .
int i;
float f;
i = 10;
f = i;
// float- int-.
,
( )
"" . , 72

I. #

, int- i , f l o a t ,
f. , # , .
, bool i n t . -
. .


,
;
(.. ),
.
,
. , i n t "" ,
byte, i n t , b y t e
, .
,
, . , , long double , .
//
// long double.
using System;
class LtoD {
public static void Main() {
long redouble D;
L = 100123285L;
D = L;
Console.WriteLine("L D: " + L + " " + D ) ;

long
double, ( double long) , . ,
:
// *** . ***
using System;
class LtoD {
public static void Main() {
long L;
double D;
D = 100123285.0;
L = D; // !!!
. ,

73

Console.WriteLine("L D: " + L + " " + D ) ;

decimal f l o a t ( double),
char ( bool). , char bool .


,
.
. . :
(_)
_ . , , / i n t ,
:

double , ;
// . . .
(int) ( / ) ;

, , double,
i n t . ,
/ , . (
) i n t , .
, double i n t .
, . , long i n t , long , i n t , "" long. . ,
1,23
1. (0,23) .
, ,
.
// .
using System;
class CastDemo {
public s t a t i c void Main() {
double x, y;
byte b;
int i ;
char ch;
uint u;

74

I. #

short s;
long 1;
x = 10.0;
= 3.0;
// double int.
i = (int) (x / y ) ; // .
Console.WriteLine(
" / : " + i ) ;
Console.WriteLine();
// int byte .
i = 255;
b = (byte) i;
Console.WriteLine("b 255: " + b +
11
11
. );
// int byte
i = 257;
b = (byte) i;
Console.WriteLine("b 257: " + b +
11
.");
Console.WriteLine();
// uint short ,
= 32000;
s = (short) u;
Console.WriteLine("s 32000: " + s +
" .");
// uint short .
= 64000;
s = (short) u;
Console.WriteLine("s 64 000: " + s +
" -- .");
Console.WriteLine();
// long uint .
1 = 64000;
u = (uint) 1;
Console.WriteLine("u 64000: " + +
" -- .");
// long uint .
1 - -12;
u = (uint) 1;
Console.WriteLine("u -12: " + +
" -- .");
Console.WriteLine();
// byte char.
b = 88; // ASCII- X.
ch = (char) b;
Console.WriteLine("ch 88: " + ch);

. ,

75

:
/ : 3
b 255: 255 ,
b 257: 1 -- .
s 32000: 32000
s 64000: -1536

,
.

64000: 64000 -- ,
-12: 4294967284 -- .
ch 88: X
. ( / ) i n t , ..
.
, b 255, b y t e 255.
b 257 , 257
byte. ,
i n t b y t e .
s s h o r t 32 000 ( u i n t ) , short- 32 000. , 64 000 s h o r t ,
.
,
u i n t s h o r t .
( u i n t ) 64 000
( 1 long).
, 64 000 u int-.
12, , ,
u i n t .
, long u i n t .
, byte- char "
", .. ,
.

I
,
. , . , s h o r t long,
.
, .
""
. .

76

I. #

decimal, TO " ", .. "


" decimal ( f l o a t double, ).
double, TO double.
f l o a t , TO
float.
ulong, TO
ulong ( sbyte, s h o r t , i n t long,
).
long, TO
long.
u i n t , sbyte, s h o r t i n t ,
long.
u i n t , TO
uint.
i n t .
""
. - .
, f l o a t double
decimal. ulong
. - ,
.
-, . ,
i n t , . , char-, sbyte-, byte-,
ushort- short-
i n t . "" int- (integer promotion). , "" i n t .
, , . ,
byte "" i n t , - byte.
.
. ,
, byte-. . byte-
"" i n t , ,
i n t . , byte-
byte- int-.
VL . :
// !
using System;
class PromDemo {
public static void Main() {
byte b;
. ,

77

b = 10;
b = (byte) (b * b ) ; // !I
Console.WriteLine("b: "+ b ) ;

, b * b . , * b b "" i n t , .. b * b int-, byte . , , , , , .


char. ,
"" -
char- i n t .

c h a r c h l = f a ' , ch2 = ' b 1 ;


chl

= (char) ( c h l + c h 2 ) ;
c h l 2 i n t ,
int- char-.

(, ). , i n t (.. sbyte-, byte-, s h o r t - ushort-),
"" i n t . To char. ,
uint- long.


, .
. , , . 1 10. . , Math. Sqrt () i n t .
// .
using System;
class CastExpr {

public s t a t i c void Main() {


double n;

for(n = 1.0; n <= 10; n++) {


Console.WriteLine(
" {0} {1}",
n, Math.Sqrt(n));
Console.WriteLine(" : {0}" ,
(int)
Math.Sqrt(n));
Console.WriteLine(

78

I. #

" : {0}",
Math.Sqrt(n) - (int) Math.Sqrt(n) );
Console.WriteLine();

1 1
: 1
: 0
2 1.4142135623731
: 1
: 0.414213562373095
3 1.73205080756888
: 1
: 0.732050807568877
4 2
: 2
: 0
5 2.23606797749979
: 2
: 0.23606797749979
6 2.44 948974278318
: 2
: 0.44*9489742783178
7 2.64575131106459
: 2
: 0.645751311064591
8 2.82842712474619
: 2
: 0.82842712474619
9 3
: 3
: 0
10 3.16227766016838
: 3
: 0.16227766016838
, , Math.Sqrt (), int, . ( ,
):
I Math.Sqrt(n) - (int) Math.Sqrt(n)
double. int
Math. Sqr t ().

3. ,

79

# ,
. # : , , . ?. # , , .


# .

++

#- +, -, * / ( , ).
.
, , .
, (/)
. , 10/3 3.
(%). , : . , 10 % 3 1. #
% , .
, 10,0 % 3,0 1. ( C/C++
.)
^ .
// %.
using System;
class ModDemo {
public static void Main() {
int iresult, irem;
double dresult, drem;
iresult = 10 / 3;
irem = 10 % 3;
dresult = 10.0 / 3.0;
drem = 10.0 % 3.0;
4.

81

Console.WriteLine(
" 1 0 / 3 : " +
iresult + " " + irem);
Console.WriteLine(
" 10.0 / 3.0: " +
dresult + " " + drem);

:
1 0 / 3 : 3 1
10.0 / 3.0: 3.33333333333333 1

, % , 1, , .


(++) ()
, . , , .
, 1,
1 . ,
1 = + 1;
:


I = - 1;
:

,
. ,

| = + 1;


I ++; // .
:
I ++; // .
, : .
,
. , #
, , .
, # , , .
:
| = 10;
= ++;

82

'

I. #

11.
,
10:
= 10;
= ++;

11. ,
11 (
).
. , :
/*

++.
*/
using System;
class PrePostDemo {
public static void Main() {
int x, y;
int i;
x = 1;
Console.WriteLine(
", = + ++;");
for(i = 0; i < 10;
= + ++; // ++
Console.WriteLine( + " " ) ;
}
Console.WriteLine();
= 1;
Console.WriteLine(
", = + + + ; " ) ;
f o r ( i = 0; i < 10;
= + ++; // ++
Console.WriteLine( + " " ) ;
}
Console.WriteLine();

:
, = + ++;
2
4

8
10
12
14
4.

83

16
18
20
,
3
5
7
9
11
13
15
17
19
21

= + ++;

,
I = + ++;
, .
.

1 = + ++;
-. ( ) , , , . , ++ ++ , ,
.
.
1 + ++;
, .
, . , .

I
" " (/)
,
. /-, . .
, .

==
1=
>
<
>=
<=
84

I. #


bool.

# (, == !=) . , <, >, <=


>=, , . , . bool
, t r u e f a l s e . , #
t r u e > f a l s e .
, bool,
bool. &,
|, ! , ,
.

p & q

P 1

false

false

false

false

false

true

true

false

false

true

true

false

false

true

false

true

true

true

true

true

false

false

true

true

IP

, " "
, .
, .
//
/ / .
using System;
class RelLogOps {
public s t a t i c void Main() {
int i , j ;
bool bl, b2;

i = 10;
j = 11;
if(i < j) Console.WriteLine ("i < j");
if(i <= j) Console.WriteLine("i <= j");
if(i != j) Console.WriteLine ("i != j");
if(i == j) Console.WriteLine(" .");
4.

85

if(i
if(i

>= j) Console.WriteLine(" .");


> j) Console.WriteLine(" .");

bl = t r u e ;
2 = f a l s e ;
i f ( b l & 2) Console.WriteLine(" .")
i f ( ! ( b l & 2)) Console.WriteLine("!(bl
& 2) ")
i f ( b l t 2) Console.WriteLine("bl
| 2 ~ ");
i f ( b l 2) Console.WriteLine("bl A 2 - - ");

:
1

<=

!=j
! (bl & b 2 )
b l I b 2 - -
b l A b2
. , . #. , #
, ,
. ,
,
, . ( , .) :

true
true

true
false

true
false

false

false

true

false

true

true

, ! | .
! I q
:
// #.
using System;
class Implication {
public static void Main() {
bool p=false, q=false;
int i, j ;
for(i = 0 ; i < 2; i
f o r ( j = 0; j < 2; 3++)
if(i==0) P = true;
i f ( i = = l ) P = false;
if(j==0) q = true;
i f ( j = = l ) q = false;
86

I. #

Console.WriteLine(
"p " + p + ", q " + q ) ;
if(!p
I q)
Console.WriteLine(" " +
p + " " + q + " " + true);
Console.WriteLine();

:
True, q True
True True True
True, q False
False, q True
False True True
False, q False
False False True


# (short-circuit) ,
. , , , , .
, , . ,
.
, .
&&,
| | ( &
I, ).
, , .
,
. , d
. .
d / n , , d . , .
// .
u s i n g System;
class SCops {
public static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
4.

87

Console.WriteLine(d + " -- " + n ) ;


d = 0; // d .
// d ,
// .
if(d != 0 && ( % d) == 0)
Console.WriteLine(d + " -- " + n ) ;
/*
.
( ). */
if(d != 0 & ( % d) == 0)
Console.WriteLine(d + " " + n ) ;

, i f d . ,
. , d 2, . ( d ) , ,
. , , .
"",
: " #
?". , , ,
.
, :
// .
using System;
class SideEffects {
public static void Main() {
int i ;
i = 0;
/* i , ,
. */
if(false & (++i < 100))
Console.WriteLine(" .");
Console.WriteLine(
" if : " + i ) ; // : 1
/* i ,
. */
if(false && (++i < 100))
Console.WriteLine(" .");
Console.WriteLine(
" if : " + i ) ; // - 1 !!

I. #

, if- i
if-.
if- i ,
f a l s e . . /,
, , , .
. , .


"" 2. .
(=). # ,
. .

= ;

.
,
. , , .
i n t , , z;
= = z = 100;

// ,
// z 100.

, z 100 . , . ,
z = 100 100, ,
. (
) .


# ,
.
. :
| = + 10;
, :
+= 10;
+= 10. .
| = - 100;
:
| -= 100;
, 100.
4.

89

(.. , ).
:
= ;
,
.
.
+=
-=
*=
/=
%=
&=
1=

, .
.
-, "" . -,
( ).
.


# ,
#. . bool, f l o a t double.
,
(), .
, ,
. . 4.1.
4.1.

&



1 ( )

, ,
, , &, |, ~, . , , . ,
.
( ).
90

I. #


0
0
1
1

0
1
0
1

& q

~J

. , 0 0 . :
1101
1010 1010
&
1000 0010

& .
( ) . , 9 0000 1001. 8
(0000 1000 ).
//
// "" .
using System;
class MakeEven {
public s t a t i c void Main() {
ushort num;
ushort i ;
for(i = 1; i <= 10; i++) {
num = i ;
Console.WriteLine("num: " + num);
num = (ushort) (num & OxFFFE); // num & 1111 1110
Console.WriteLine("num : "
+ num + " \ n " ) ;
}

:
num: 1
num : 0
num: 2
num : 2
num: 3
num : 2
num: 4
num : 4
num: 5
4.

91

num : 4
num:
num :
num: 7
num :
num: 8
num : 8

num: 9
num : 8
num: 10
num : 10
OxFFFE, , 1111 1111 1111 1110. , num & OxFFFE
, . , "", ,
"" ( ).
. ,
, .
//
// , ,
using System;
class IsOdd {
public static void Main() {
ushort num;
num = 10;
if((num & 1) == 1)
Console.WriteLine(" .");
num = 11;
if((num & 1) == 1)
Console.WriteLine(num + "

.");

:
1 11 .
i f num
1. num (.. ), num & 1 .
. i f ,
.
,
&, , b y t e . .
92

I. #

// , ,
using System;
class ShowBits {
public s t a t i c void Main() {
int t ;
byte val;
val = 123;
for(t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write ("1 " ) ;
if((val & t) == 0) Console.Write ("0 ") ;

:
0 1 1 1 1 0 1 1
for
val. , , 1, 0.
, , .
, 1, ,
. :
1101
1010 1010
1111 1011
.
//
// "" ,
using System;
c l a s s MakeOdd {
public s t a t i c void Main() {
ushort num;
ushort i ;
f o r ( i = 1; i <= 10; i++) {
num = i ;
Console.WriteLine("num: " + num);
num = (ushort) (num | 1 ) ; // num | 0000 0001
Console.WriteLine(
"num : "
+ num + " \ n " ) ;

4.

93

:
num: 1
num : 1
num: 2
num : 3
num: 3
num : 3
num: 4
num : 5
num: 5
num : 5
num:
num : 7
num: 7
num : 7
num: 8
num : 9
num: 9
num : 9
num: 10
num : 11
, for, 1, 0000 0001. , 1 , .
, , ( ). , , ""
, , .. .
(XOR)
, , .. . :
0111 1111
1011 1001
1100 0110
XOR , . XOR Y, XOR
Y, . ,

R1
R2

= X
= Rl

Y;
Y;

R2 . ,
XOR, (Y), ().
94

I. #

,
, .
,
. :
// XOR
/ / .
u s i n g System;
c l a s s Encode {
p u b l i c s t a t i c void Main() {
char chl = f H f ;
char ch2 = ' i ' ;
char ch3 = f ! f ;
i n t key = 88;
Console.WriteLine(" : " +
chl + ch2 + ch3);
// ,
chl - (char) (chl A key);
ch2 = (char) (ch2 key);
ch3 = (char) (ch3 A key);
Console.WriteLine(" : " +
chl + ch2 + ch3);
//
chl
ch2
ch3

,
= (char) (chl A key);
= (char) (ch2 A key);
= (char) (ch3 key);

Console.WriteLine(" : " +
chl + ch2 + ch3);

:
: Hi!
: >1
: Hi!
, XOR,
, () .
( 1)
. , ( ), 1001 ,
~ 0110 1001.
1 .
// .
u s i n g System;
c l a s s NotDemo {
p u b l i c s t a t i c void Main() {
4.

95

sbyte b = -34;
int t;
for(t=128; t > 0; t = t/2) {
if((b
& t) != 0) Console.Write("1 " ) ;
if((b
& t) == 0) Console.Write("0 " ) ;
}
Console.WriteLine() ;
// ,
b = (sbyte) ~b;
for(t=128; t > 0; t = t/2) {
if((b
& t) != 0) Console.Write("1 " ) ;
if((b
& t) == 0) Console.Write("0 " ) ;

:
1 1 0 1 1 1 1 0
0 0 1 0 0 0 0 1


# .
# :

;
_.

, _ ,
.
, ,
, .
, , . , . , . :
. , ,
, .
, . ,
, .
,
. , ,
, .. " " 1, 0. "" .
, .
v a l 1, 128,
1000 0000. , , , .
96

I. #

//
using System;

class ShiftDemo {
public static void Main() {
int val = 1;
int t;
int i;
for(i = 0; i < 8; i++) {
for(t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 " ) ;
if((val & t) == 0) Console.Write("0 " ) ;
}
Console.WriteLine();
val = val 1; // .
}
Console.WriteLine();
val = 128;
for(i = 0; i < 8;
for(t=128; t
0; t = t/2) {
i = 0) Console.Write("1 " ) ;
if((val & t) !=
if((val & t) == 0) Console.Write("0 " ) ;
Console.WriteLine();
val = val >> 1; // .

0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0

:
0 0 0 0 0 0 1
0 0 0 0 0 1 0
0 0 0 0 1 0 0
0 0 0 1 0 0 0
0 0 1 0 0 0 0
0 1 0 0 0 0 0
1 0 0 0 0 0 0
0 0 0 0 0 0 0
0
1
0
0
0
0
0
0

0
0
1
0
0
0
0
0

0
0
0
1
0
0
0
0

0
0
0
0
1
0
0
0

0
0
0
0
0
1
0
0

0
0
0
0
0
0
1
0

0
0
0
0
0
0
0
1


2, 2. . . , , ( ) . :
//
// 2.

4.

97

using System;
class MultDiv {
public static void Main() {
int n;
n = 10,Console. WriteLine (" n: " + n ) ;
// 2.
n = n 1;
Console.WriteLine(
" n n = n * 2: " + n ) ;
// 4.
n = n 2;
Console.WriteLine(
" n n n * 4: " + n ) ;
// 2.
n = n 1;
Console.WriteLine(
" n n = n / 2: " + n ) ;
// 4.
n = n >> 2;
Console.WriteLine(
" n n = n / 4: " + n ) ;
Console.WriteLine();
// .
n = 10;
Console.WriteLine(" n: " + n ) ;
// 2, 30 .
n = n << 30; // : .
Console.WriteLine(
" 30 : " + ) ;


: 10
- *
n = n *
n = n /
n = n /

:
2:
4:
2:
4:

20
80
40
10

: 10
30 : -2147483648
.
10 30 (.. 230)
, ""
, i n t . ,

I. #

, i n t . .
,
2. ( ,
,
3.)



, . ,
(XOR) 127.
1 = 127;
I = 127;

# ?.
? ift h e n - e l s e . ? , . :
1 ? 2

3;

1 bool. 2 3 . .
?- . !. , 2, ?-. 1 , ?-
. , absval val.
absval = v a l < 0 ? - v a l : v a l ; //
// v a l .
absval v a l ,
. v a l , absval " ",
.
?. 100 ,
.
// ?.

using System;

class NoZeroDiv {
public s t a t i c void Main() {
int result;
int i;

4.

99

for{i = -5; i < 6;


result = i != 0 ? 100 / i : 0;
i f ( i != 0)
Console.WriteLine("100 / " + i + " " + r e s u l t ) ;

.
100 / -5 -20
100 / -4 -25
100 / -3 -33
100 / -2 -50
100 / -1 -100
100 / 1 100
100 / 2 50
100 / 3 33
100 / 4 25
100 / 5 20
:
r e s u l t = i != 0 ? 100 / i : 0;
r e s u l t 100
i. , i
. ( i = 0) r e s u l t
.
, ?. , , . .
, ?, bool,

if. , , , ( ).
// ?-.
using System;
class NoZeroDiv2 {
public s t a t i c void Main() {
int i ;
for(i = -5; i < 6;
i f ( i != 0 ? true : false)
Console.WriteLine("100
/ " +i +
11
" + 100 / i) ;
if. i ,
if- f a l s e , , , . ( ) .

100

I. #

#
( ). , , :
=10/*(127/);
= 10 / *
{121);
( , ) , .
. ,
, !
( , ,
) . , ,
?
= y/3-34*temp+127;
X = (/3) - (34*temp) + 127;


. 4.2 #- (
). , .
4.2. #-

( ) [ ] . ++()() c h e c k e d new s i z e o f
!

/ %

<<=>>=

typeof

unchecked

+() -() ++()()

is

I
&&
II

4.

101

#. :
(if, switch), ( for-, while-, d o while- foreach-) (break, c o n t i n u e , goto, r e t u r n
throw). throw, #-
( 13),
.

i f
i f 2, . :
if() ;
else ?
#.
e l s e . . if- :

if ()

else

, , , if-;
else- ( ).
. , if-,
bool.
, if-else-
, .
// ,
// .
using System;
class PosNeg {
public s t a t i c void Main() {
int

i;

for(i=~5; i <=* 5;
Console.Write(" " + i + ": ") ;
if(i < 0) Console.WriteLine(" "
else Console.WriteLine(" ");

5.

103

:
-5:
- 4 :
-3:
- 2 :
-1:
0:
1:
2:
3:
4:
5:
, i , if- ( "": );
else- ( "": ). .

if-
if- , (. ) if-. if- . ,
else- if-, ,
else-. :
if

(i == 10)
{
if (j < 20)
a = b;
if(k
> 100)
= d;

else a = ; // else-
// if(k > 100).
}
else a = d; // else- if(i == 10).
, else- i f (j < 20), (
if- , "else-"). else- i f ( > 100), .
.
. , else-, : " ".
// , ,
// .
using System;
class PosNegZero {
public static void Main() {
int i;
for(i=-5; i <= 5; i

104

I. #

Console.Write(" " + i + ": " ) ;


if(i < 0) Console.WriteLine(" ");
else if(i == 0) Console.WriteLine(" ");
else Console.WriteLine(" ");

-5:
- 4 :
-3:
- 2 :
-1:
0:
1:
2:
3:
4:
5:

i f - e l s e - i f
,
if-, "" i f - e l s e - i f . :
if {)
;
else if{)
;
else if{)
;

else
;
. . - , , , "" . ,
, else- ( , , ). e l s e , , .
if-else-if-''" ,
( ).
// ,
// .
using System;
5.

105

class Ladder {
public s t a t i c void Main() {
int num;
for(num = 2; num < 12; num++) {
if((num % 2) == 0)
Console.WriteLine(" " +
num + " 2 . " ) ;
else if((num % 3) == 0)
Console.WriteLine(" " +
num + " 3 . " ) ;
else if((num % 5) == 0)
Console.WriteLine(" " +
num + " 5.");
else if((num % 7) == 0)
Console.WriteLine(" " +
num + " 7.");
else
Console.WriteLine(num +
" 2, 3, 5 7 . " ) ;

:
2 2.
3 3.
4 2.
5 5.
2.
7 7.
8 2.
9 3.
10 2.
11 2, 3, 5 7.
, else- ,
if-.

s w i t c h
switch. switch
. . if-,
switch . .
.
, .
switch :
switch() {
case 1:

break;
case 2:
106

I. #


break;
case :

break;

default:

break;

switch
(, char, byte, s h o r t i n t ) s t r i n g (
). , , .
switch- ;
case- ,
. case- switch-
.
default- ,
case- switch. d e f a u l t . , case-
. - , ,
case- ,
break.
switch- .
// s w i t c h .
using System;
class SwitchDemo {
public static void Main() {
int i;
for(i=0; i
switch (i) {
case 0:
Console.WriteLine("i
break;
case 1:
Console.WriteLine("i
break;
case 2:
Console.WriteLine("i
break;
case 3:
Console.WriteLine("i
break;
case 4:
Console.WriteLine("i
break;
default:
Console.WriteLine("i
break;

5.

.");
.");
.");
/
.");
.");
.");

107

i
i
i
i
i
i
i
i
i
i

:
.
.
.
.
.
.
.
.
.
.

, , case-, i.
. i , default-.
switch- i n t .
, , switch- , char.
case- char- char-.
// char
// switch-.
u s i n g System;
c l a s s SwitchDemo2 {
p u b l i c s t a t i c void Main() {
char ch;
f o r ( c h = ' A f ; ch<= ' E ' ; ch++)
switch(ch) {
case ' A ' :
Console.WriteLine("ch
break;
case f B f :
Console.WriteLine("ch
break;
case f C f :
Console.WriteLine("ch
break;
case r D r :
Console.WriteLine("ch
break;
case f E ' :
Console.WriteLine("ch
break;

" ) ;
" ) ;
" ) ;
D " ) ;
" ) ;

:
ch
ch

108

I. #

ch

I ch D
I ch
, default- . , . ,
.
# , , case-, , . ,
"", . case-
break. ("" ,
goto, ,
break "".) break,
case-, switch ,
switch. default- "" break.
""
# , C++ Java. case-
"" , case-,
.. "" . # ""
. -, case-, ,
case- . -, case- "",
.
"" case , , , , case
.
// "" case- "".
using System;
class EmptyCasesCanFall {
public static void Main() {
int i ;
for(i=l; i < 5;
switch(i) {
case 1:
case 2:
case 3: Console.WriteLine("i 1, 2 " ) ;
break;
c a s e 4: C o n s o l e . W r i t e L i n e ( " i 4 " ) ;
break;

5.

109

:
1, 2 3
1, 2 3
1, 2 3
4
, i 1,2 3,
WriteLine ( ) , i 4, . case-
"", case-
.
case- case-, .
i
i
i
i

switch
switch case-
switch.
switch. , case- switch ,
. , :
switch(chl) {
case f A f :
Console.WriteLine(
" - switch.");
switch(ch2) {
case 'A 1 :
Console.WriteLine(
" - switch.");
break;
case '': // ...
} // switch,
break;
case 'B f : // ...

f o r
2, for.
, ,
. . , for
:
for{; ; ) ;
for ,
:
for{; ; )
{

,
.
110

I. #

, .
bool,
. ,
f o r . - ,
,
. , f o r . f o r ,
. , , for.
for ,
,
. , 100 100 , 5.
// for
// .
using System;
class DecrFor {
public s t a t i c void Main() {
int x;
for(x = 100; x > -100; x -= 5)
Console.WriteLine(x);

,
for. , ,
. :
for(count=10; count < 5; count++)
+= count; // .
,
count .
(count < 5) . .
for , . , f o r 2 20. ,
.
/*
.
,
.
*/
using System;
class FindPrimes {
public static void Main() {
int num;
int i;
int factor;
bool isprime;
for(num = 2; num < 20; num++) {
5.

111

isprime = true;
factor = 0;
// , num i .
for(i=2; i <= num/2; i++) {
if((num % i) == 0) {
// num i ,
// num ,
isprime = falserfactor = i;

if(isprime)
Console.WriteLine(num + " -- .");
else
Console.WriteLine("
num + " " + factor);

:
2 -- .
3 .
4 2
5 -- .
3
7 .
8 4
9 3
10 5
11 .
12
13 .
14 7
15 5
16 8
17 -- .
18 9
19 .

for
for #,
.


for .

^ . :
// for.
using System;
class Comma {
112

I. #

public static void Main() {


int i, j ;
for(i=0, j=10; i < j; i++, j )
Console.WriteLine("i j: " + i + " " + j ) ;

:
3-: 0 10
1 9
j
j: 2 8
j: 3 7
i: 4 6

. i j .
i , j
.
.
for , .

for. ,
( 100).
^ : .
/*
for
.
*/
1

i
i
i
i

using System;
class Comma {
public static void Main() {
int i, j;
int smallest, largest;
int num;
num = 100;
smallest = largest = 1;
for(i=2, j=num/2; (i <= num/2) & (j >= 2 ) ; i++, j ) {
if((smallest == 1) & ((num % i) == 0))
smallest = i;
if((largest == 1) & ((num % j) == 0))
largest = j;

Console.WriteLine(" : " + l a r g e s t ) ;
Console.WriteLine(" : " + s m a l l e s t ) ;
:
5.

113

: 50
: 2

for
, .
i .
2 ,
( num). j . , num,
, . , i j . .


, for, , bool. , jpaMMe done.
// bool.
using System;
class forDemo {
public static void Main() {
int i, j ;
bool done = false;
for(i=0,

j=100;

!done; i++, j )

i f ( i * i >= j) done = t r u e ;
Console.WriteLineC'i,

j : " + i + " " + j);

:
0 100
1 99
2 98
3 97
4 96
5 95
i, j: 6 94
i, j: 7 93
i, j: 8 92
i, j: 9 91
i, j: 10 90
for , bool- done
t r u e . t r u e , i j .

114

I. #


# (, , ) .
^ . :
// for .
using

System;

class Empty {
public static void Main() {
int i;
for(i = 0; i < 10; ) {
Console.WriteLme (" " + i) ;
i++; // .

for. i , .
, : i 10. i
, , :
0
N'1
*
2
3
N'4
5
6
7
8
9
for
^ .
// for .
using System;
class Empty2 {
public static void Main() {
int i ;
i = 0; // .
for(; i < 10; ) {
Console .WriteLme (" " + i) ;
i++; // .

i for,
. for.
5.

115

, , , ,
.


for,
(, ). , , #-
.
f o r ( ; ; ) // .

.
(, ), , " "
.
, . (: break.)


# , for ( - ),
. , .
"" . , "" 1 5.
// .
using System;
class Empty3 {
public static void Main() {
int i ;
int sum = 0;
// 1 5.
for(i = 1; i <= 5; sum +=
Console.WriteLine("

" + sum);

}
}

:
15
,
for, . :
1 sum += i++
, .
, . , sum sum i,
116

I. #

i. , :
sum = sum + i ;

for
, for, . . , ,
1 5. i for.
// f o r .
using System;
class ForVar {
public static void Main() {
int sum = 0;
int fact = 1;
// 1 5.
for(int i = 1; i <= 5; i++) {
sum += i; // i .
fact *= i;
}
// i .
Console.WriteLine(" " + sum);
Console.WriteLine(" " + fact);

for :
. , for. . , i for. - , for.
, for.

w h i l e
while :
whi 1 () ;
,
. ,
bool.
, .
, ,
.
5.

117

, while
.
// .

using System;
class WhileDemo {
public static void Main() {
int num;
int mag;
num = 435679;
mag = 0;
Console.WriteLine(": " + num);
while(num > 0) {
mag++;
num = num / 1 0 ;

Console.WriteLine(": " + mag);

:
: 435679
: 6

while . num.
, mag , num 10.
, num . num ,
, mag .
for, while, a
, .
( ) .
// 2.
u s i n g System;
class Power {
public static void Main() {
int e;
int result;
for(int i=0; i < 10;
result = 1;
e = i;
while(e > 0) {
result *= 2;
e;
Console.WriteLine("2 " + i +
" " + result);
118

I. #

2
2
2
2
2
2
2
2
2
2

:
0 1
1 2
2 4
3 8
4 16
5 32
64
7 128
8 256
9 512

, while ,
. , ,
for, while .

d o - w h i l e
# do-while. f o r while,
, do-while . , do-while .
:
do {
;
} while {);
,
, do-while, while.
do-while , ,
.
do-while
, .
// .
using System;
class DoWhileDemo {
public s t a t i c void Main() {
int num;
int nextdigit;
num = 198;
Console.WriteLine(": " + num);
Console.Write(" : " ) ;
do {
nextdigit = num % 10;
Console.Write(nextdigit);
5.

119

num = num / 10;


} while(num > 0) ;
Console.WriteLine() ;

: 198
: 8 91

. 10. .
num. , . ,
num .

f o r e a c h
foreach .
. # ,
. f oreach 7, .

break

break ,
, , .
break ,
^ , . .
// break .
u s i n g System;
c l a s s BreakDemo {
public s t a t i c void Main() {
/ / break .
f o r ( i n t i=-10; i <= 10; i++) {
i f ( i > 0) break; / / i
Console.Write(i + " " ) ;
}
Console.WriteLine("!");

> 0.

:
-10 -9 -8 -7 -6 -5 -4 -3 -2 - 1 0 !

120

I. #

, , for i 10 10, break "" , i .


break #-,
"". , ,
do-while-, :
// break
/ / do-while.
using System;
class BreakDemo2 {
public s t a t i c void Main() {
int i ;
i = -10;
do {
i f ( i > 0) break;
Console.Write(i + " " ) ;
} while(i <= 10);
Console.WriteLine("!");

. .
// .
using System;
class FindSmallestFactor {
public static void Main() {
int factor = 1;
int num = 1000;
for(int i=2; i < num/2;
if((num%i) == 0) {
factor = i;
break; // , .
Console.WriteLine(
" " + factor);
:
1 2
break for,
.
"" .
break .

5.

121

// break ,
using System;
class BreakNested {
public static void Main() {
for(int i=0; i
Console.WriteLine(
" : " + i ) ;
Console.Write(
11
: ") ;
int t = 0;
while(t < 100) {
if(t == 10) break; // ,
// t 10.
Console.Write(t + " " ) ;
}
Console.WriteLine();
}
Console.WriteLine(" .");


: 0
: 0 1 2 3
: 1
: 0 1 2 3
: 2
: 0 1 2 3
.

:
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9

, break, ,
, .
, , break, . . break, switch, switch,
.

c o n t i n u e
"" ,
"" .
c o n t i n u e . ,
. c o n t i n u e
"" break. ,
c o n t i n u e "" 0 100.
II/
c o n t i n u e ,
u s i n g System;
122

I. #

class ContDemo {
public static void Main() {
// 0 100.
for(int i = 0; i <= 100; i++) {
if((i%2) != 0) continue; //
// .
Console.WriteLine(i);

, ,
WriteLine () .
while do-while c o n t i n u e , ,
" ". for c o n t i n u e , .
.
c o n t i n u e ,
.

r e t u r n
r e t u r n .
. . 6.

g o t o
goto #- . , .
,
, , "-".
goto - , .
""
. , , ( ) goto, , .
.
goto , , ,
. goto , .
goto . # , . goto, . ,
goto 100 :
= 1;
loopl:
if(x

< 100)

goto loopl;

5.

123

goto case- d e f a u l t switch. , , case- default- . , "" , goto. goto


"" switch. , "" goto switch.
, goto switch.
// goto s w i t c h .
using System;
class SwitchGoto {
public static void Main() {
for(int i=l; i < 5; i++)
switch(i) {
case 1:
Console.WriteLine("
goto case 3;
case 2:
Console.WriteLine("
goto case 1;
case 3:
Console.WriteLine("
goto default;
default:
Console.WriteLine("
break;

{
case 1");
case 2 " ) ;
case 3 " ) ;
default");

Console.WriteLine
//

goto case 1; // !
/ / s w i t c h .
}

:
case 1
case 3
default

case 2
case 1
case 3
default

case 3
default
default
, goto case d e f a u l t switch. , case break. goto
case- "" case-124

I. #

, "" (break) . , goto


switch-.
I //
goto case 1; // !...,
. goto
switch ,
.
goto
. :
// goto.
using System;

class Use_goto {
public s t a t i c void Main() {
int i=0, j=0, k=0;
for(i=0; i < 10;
for(j=0; j < 10; j++ ) {
for(k=0; k < 10; k++) {
Consple.WriteLine("i, j , k: " + i + " " +
j + " " + k) ;
if(k == 3) goto stop;

stop:
Console.WriteLine(", ! i f j, k: " + i +
", " + j + " " 4- k ) ;

:
i,

1,

j ,

k:

: 00 00 21
: 0 0 3
:

, ! i , j , : 0, 0 3
, goto,
i f break. goto
. , , , , goto .

5.

125

. #,
. ,
#. - #. , . .
, ,
#, .


#- ,
. , ,
. , , .
, . , .
, , . # . .
, (), ,
. : . ,
, .
. , , ,
.


, , , , .
, , .
, ,
. ,
-, ,
, , , , , .
,
. .
c l a s s .
, , :

class _ {
II .
!;
2;
//. . .
;

II .
_ 1 () {
II

. ,

127

_ 2{) {
//

_ {)
/I

,
. (, p u b l i c ) , , . 2,
. ,
. , , , , ( p r i v a t e ) . ( )
.
public-, , , , . 8.
( ), ,
. , ,
, ( ) ,
. , .
, , .
, ,
Main (). , . , Main() .
, .


, (, , .). (
Building) ( ,
).
Building. : f l o o r s , a r e a occupants. ,
B u i l d i n g .
^. ( .)
class Building {

public int floors;


//
public int area;
//
public int occupants; //
}
, Building,
. :
_;

128

I. #

, , _ .
, , , . Building p u b l i c , , , ,
Building.
c l a s s .
Building.
Building. , c l a s s ;
. , Building.
Building, , , :
Building house = new B u i l d i n g ( ) ; //
// B u i l d i n g .

house Building,
.. "" . .
, , .
, B u i l d i n g f l o o r s , a r e a occupants. "" (.). ""
. :
.
, "", .
, floors 2,
.
I house.floors = 2;
"" , .
, Building.
// , Building.
using System;
c l a s s Building {
public i n t f l o o r s ;
//
public i n t area;
//
public i n t occupants; //
}

// Building,
class BuildingDemo {
public static void Main() {
Building house = new Building(); //
// Building,
int areaPP; // , .
// house,
house.occupants = 4;
house.area = 2500;
house.floors = 2;

6. ,

129

// , .
areaPP = house.area / house.occupants;
Console.WriteLine(
" :\n " +
house.floors + " \ " +
house.occupants + " \ " +
house.area +
" , \ " +
areaPP + " ");

: B u i l d i n g BuildingDemo.
BuildingDemo Main() B u i l d i n g
house, house,
. ,
B u i l d i n g BuildingDemo . , .
, BuildingDemo Building,
, .. public-.
p u b l i c ,
Building, BuildingDemo .
U s e B u i l d i n g . c s , UseBuilding.exe. B u i l d i n g BuildingDemo . :
:
2
4
2500 ,
625
B u i l d i n g BuildingDemo .
B u i l d i n g , cs BuildingDemo. cs, .
.
:
esc B u i l d i n g . c s BuildingDemo,cs
Visual Studio IDE,
.
, : , . ,
.
, ,
. , B u i l d i n g f l o o r s , a r e a occupants, () .
.
// B u i l d i n g .

u s i n g System;

130

I. #

class Building {
public int floors;
//
public int area;
//
public int occupants; //
// Building,
class BuildingDemo {
public static void Main() {
Building house = new Building();
Building office - new BuildingO;
int areaPP; // , .
// house,
house.occupants = 4 ;
house.area = 2500;
house.floors = 2 ;
// office,
office.occupants = 25;
office.area = 4200;
office.floors = 3;
// , .
areaPP = house.area / house.occupants;
Console.WriteLine(" :\n " +
house.floors + " \ " +
house.occupants + " \ " +
house.area +
" , \ " +
areaPP + " ");
Console.WriteLine();
// ,
// .
areaPP = office.area / office.occupants;
Console.WriteLine(" :\n " +
office.floors + " " +
office.occupants + " " +
office.area +
" , \ " +
areaPP + " ");

:
:
2
4
2500 ,
625
:
3
25
4200 ,
168

6. ,

131

, ( house) ( o f f i c e ) . . 6.1.
floors

house

office

area

2500

occupants

floors

area

4200

occupants

25

. 6.1.



Building.
I B u i l d i n g house = new B u i l d i n g ( ) ;
. -,
house Building. ,
. -, house
. " " new. ,
house
Building.

new (.. )
. ( ) , new.
, # .
, ,
.
Building house;
// .
house = new Building(
//
// Building.
house
Building. house , ,
. ( )
house n u l l , ,
.
B u i l d i n g , house.
house .
, , , . -

132

I. #

, . . ,

i n t x;

= 10;

10, i n t , .. ; .

Building

h o u s e = new B u i l d i n g ( ) ;

house , .



,
(, i n t ) . ( )
, . ( ) .
( ) , , , . , :
Building housel = new B u i l d i n g ( ) ;
Building house2 = housel;

, housel house2 , . , housel house2,


. housel house2 house2 ,
housel. ,
housel, house2. ,
1 h o u s e l . a r e a = 2600;
,
Console.WriteLine(housel.area);
Console.WriteLine(house2.area);

2600.
, housel house2,
, . , house2 , .
Building housel = new Building();
Building house2 = housel;
Building house3 = new Building();
Building house2 = house3; // house2
// house3
// .
house2 , house3. , housel, .

6. ,

133


, . Building .
( ) , . (), , , .
.
.
. ,
.
. , Main () ,
. ,
#.
. , g e t v a l , g e t v a l (). .
:
_ (_)
{

//

, ,
. , , , , ,
( p r i v a t e ) , .
public-, , , .
_ ,
. , ,
. ,
void. , , .
,
,
. _ ( ), . , ,
. , _
.

B u i l d i n g
, , , , , . , ,
() ,
, .
,
. , ,
Building,
a r e a occupants,
Building. , B u i l d i n g -

134

I. #

. , "" ,
, ,
"". "" , . , B u i l d i n g , , , - , , .
B u i l d i n g , . , Building
a r e a P e r P e r s o n O , , .
// B u i l d i n g .
using System;
class Building {
public int floors;
//
public int area;
//
public int occupants; //
// ,
// ,
public void areaPerPerson() {
Console.WriteLine(" " + area / occupants +
" ");

// areaPerPerson().
class BuildingDemo {
public static void Main() {
Building house = new Building();
, Building office = new Building();
// house,
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// office,
office.occupants = 25;
office.area = 4200;
office.floors - 3;
Console.WriteLine(" :\n " +
house.floors + " \ " +
house.occupants + " \ " +
house.area +
" , ");
house.areaPerPerson();
Console.WriteLine();
Console.WriteLine(" :\n

6. ,

" +

135

office.floors + " \ " +


office.occupants + " \ " +
office.area +
11
, ");
office.areaPerPerson();

, :
:
2
4
2500 ,
625
:
3
25
4200 ,
168
,
areaPerPerson ( ) . :
I p u b l i c void a r e a P e r P e r s o n ( ) {
a r e a P e r P e r s o n (),
. p u b l i c ,
.
a r e a P e r P e r s o n () void, .. . ,
.
. a r e a P e r P e r s o n () :
Console.WriteLine("
" + a r e a / occupants +
11
" ) ;

, , a r e a occupants.
Building a r e a
occupants, a r e a P e r P e r s o n () ,
, , .
a r e a P e r P e r s o n () , ..
.
Main ( ) :
I house.areaPerPerson();
a r e a P e r P e r s o n () house. ,
, "". ,
, , .
h o u s e . a r e a P e r P e r s o n () , , ,
house. of f i c e . a r e a P e r P e r s o n () , , ,

136

I. #

office. , , areaPerPersonO, , , , .
. area occupants areaPerPersonO , ..
, "". :
, ,
, "". . .
, , , . , . , area
occupants areaPerPersonO , , areaPerPerson ().


. , ( areaPerPersonO).
r e t u r n . r e t u r n : void- ( ), .
, .
void-
r e t u r n :
I return;
, . , , :
p u b l i c void myMethO {
int i ;
for(i=0;
i f ( i == 5) return; / /
/ / i = 5.
Console.WriteLine();

for i 0 5, , i 5,
myMeth().
return. ,
public void myMeth () {

if(done) return;
//...
if(error) return;
}

,
. . ,
, .
6. ,

137

, " ": void-


: r e t u r n .


void- , . ,
. 3,
Math. Sqrt () .
, , . ( Math. S q r t ( ) ) , , , ,
-. , ,
, #-.
,
r e t u r n :

return ;
, .

a r e a P e r P e r s o n {). , , a r e a P e r P e r s o n ()
, . a r e a P e r P e r s o n ( ) ,
, , ( ).

// areaPerPerson().

using System;
class Building {
public i n t floors;
//
public i n t area;
//
public i n t occupants; //
// ,
// ,
public i n t areaPerPerson() {
return area / occupants;

// areaPerPerson().
class BuildingDemo {
public static void Main() {
Building house = new Building();
Building office = new Building();
int areaPP; // ,
// .
// house.
house.occupants = 4;
house.area = 2500;
house.floors = 2;

138

I. #

//
o f f i c e . o c c u p a n t s = 25;
o f f i c e . a r e a = 4200;
o f f i c e . f l o o r s = 3;

office,

// house ,
// ..
areaPP = h o u s e . a r e a P e r P e r s o n ( ) ;
Console.WriteLine(" :\n " +
h o u s e . f l o o r s + " \ " +
house.occupants + " \ " +
house.area +
" , \
areaPP + " ");
Console.WriteLine();
// o f f i c e ,
// ..

areaPP = o f f i c e . a r e a P e r P e r s o n ( ) ;
Console.WriteLine(" :\n " +
o f f i c e . f l o o r s + " \ " +
o f f i c e . o c c u p a n t s + " \ " +
office.area +
" , \ " +
areaPP + " ");
.
areaPerPerson ():
. , , areaPerPerson (). ,

I areaPP = h o u s e . a r e a P e r P e r s o n ( ) ;
, house, areaPP.
, areaPerPerson () , i n t . ,
. , ,
, , ,
,
. , ,
double,
double.
,
. ,
areaPP. areaPerPerson () WriteLine ():
Console.WriteLine(" :\n " +
h o u s e . f l o o r s + " \ " +
I
6. ,

139

house.occupants + " \ " +


house.area + " , \ " +
house.areaPerPerson() +
11
");
WriteLineO
house. areaPerPerson (),

WriteLine (). , house. areaPerPerson () ,


Building, . , .
If (bl.areaPerPerson() > 2.areaPerPerson())
Console.WriteLine(
" . " ) ;


. , , , . , , . , . , .
, , , .
. ChkNum
i s Prime, t r u e ,
, f a l s e . ,
i s Prime bool.
// .
using System;
c l a s s ChkNum {
// t r u e , - ,
public bool isPrime(int x) {
for(int i=2; i < x/2 + 1; i++)
if((x %i) == 0) return false;
return t r u e ;

class ParmDemo {
public s t a t i c void Main() {
ChkNum ob = new ChkNum();
for(int i = l ; i < 10;
if(ob.isPrime(i)) Console.WriteLine(i +
" .");
else Console.WriteLine(i + " .");

140

I. #

1
2
3
4
5
6
7
8
9

.
.
.
.
.
.
.
.
.
,
isPrime , . . -, , isPrime.
. isPrime
1. 1. 2, , 2 .. , ,
isPrime, , .
.
, . , , ChkNum, l e d ( ) , (/east common denominator)
.
// , .
using System;
class ChkNum {
// true, - ,
public bool isPrime(int x) {
f o r ( i n t i=2; i < x/2 + 1; i++)
i f ( ( x %i) == 0) return false;
return t r u e ;
// ,
public int led(int a, int b) {
int max;
if(isPrime(a) | isPrime(b)) return 1;
max = a < b ? a : b;
for(int i=2; i < max/2 + 1;
if(((a%i) == 0) & ((b%i) == 0)) return i;
return 1;

class ParmDemo {
public static void Main() {
ChkNum ob = new ChkNumO;
int a, b;
for(int i=l; i < 10;

6. ,

141

if(ob.isPrime (i))

Console.WriteLine(i +
" .");
else Console.WriteLine(i + " .");
a = 7;
b = 8;
Console.WriteLine(" " +
+ " " + b + " " +
ob.lcd(a, b ) ) ;
= 100;
b = 8;
Console.WriteLine(" " +
+ " " + b + " " +
ob.lcd(a, b));
= 100;
b = 75;
Console.WriteLine(" " +
+ " " + b + " " +
ob.lcd(a, b));

, l c d ( ) . :
1 .
2 .
3 .
4 .
5 .
6 .
7 .
8 .
9 .
7 8 1
100 8 2
100 75 5
, . , :
int myMeth(int a, double b, float ) {
// . . .

B u i l d i n g
B u i l d i n g ( )
. , , ,
.
maxOccupant () .
/* ,

. */

142

I. #

I public int maxOccupant(int minArea) {


1
return area / minArea;

I}

maxOccupant () minArea , . ,
maxOccupant ( ) ,
.

Building,

maxOccupant().
/*
,
,
,
.
*/
using System;
class Building {
public int floors;
//
public int area;
//
public int occupants; //
// ,
/ / ,
public int areaPerPerson() {
return area / occupants;
}
/*
,
. */
public int maxOccupant(int minArea) {
return area / minArea;

// maxOccupant().
c l a s s BuildingDemo {
p u b l i c s t a t i c void Main() {
Building house = new B u i l d i n g ( ) ;
Building office = new B u i l d i n g ( ) ;
// house,
house.occupants = 4;
house.area = 2500;
h o u s e . f l o o r s = 2;
//
o f f i c e . o c c u p a n t s = 25;
o f f i c e . a r e a = 4200;
o f f i c e . f l o o r s = 3;

office,

Console.WriteLine(
" , \" +
" " +
300 + " : " +
6. ,

143

house.maxOccupant(300));
Console.WriteLine(
" , \" +
" " +
300 + " : " +
office.maxOccupant(300));

.
, ,
300 : 8
,
300 : 14


,
. #.
. :
public void m() {
char a, b;
if(a==b) {
Console.WriteLine("");
return;
} else {
Console.WriteLine(" ");
return;
}
Console.WriteLine(" .");
}
WriteLine () ( )
,
m (). . ,
.

Building-
"" :
house.occupants = 4;
house.area = 2500;
house.floors = 2;

.
, "" ,
, . .
144

I. #

. ,
, . . :
_{) {
//
, , , , . , p u b l i c , , , .
, ,
# ,
-, , , - 11-. , .
:
// .
using System;
class MyClass {
public i n t x;
public MyClass() {
x = 10;

c l a s s ConsDemo {
p u b l i c s t a t i c v o i d Main() {
MyClass t l = new M y C l a s s ( ) ;
MyClass t 2 = new M y C l a s s ( ) ;
Console.WriteLine(tl.x

+ " " + t2.x);

MyClass :
p u b l i c MyClass() {
= 10;
}

public- , , MyClass.
10. MyClass () new MyClass. ,
I MyClass tl = new MyClass();
t l MyClass ( ) ,
t l . x 10. t 2 ,
.. t 2 t 2 . x
10. , :
| 10 10
6. ,

145


. , . , : . ,
.
// .
using System;
class MyClass {
public int x;
public MyClass(int i) {
x = i;

c l a s s ParmConsDemo {
p u b l i c s t a t i c v o i d Main() {
MyClass t l = new M y C l a s s ( 1 0 ) ;
MyClass t 2 = new M y C l a s s ( 8 8 ) ;
Console.WriteLine(tl.x + " " + t2.x);

10 88

MyClass ()
i , . ,
I MyClass t l = new MyClass(10);
i 10, .

B u i l d i n g
Building, ,
(.. )
f l o o r s , a r e a occupants. ,
Building.
// B u i l d i n g .
using System;
class Building {
public int floors;
// -
public int area;
//
public int occupants; //
public Building(int f, int a, int o) {

146

I. #

floors = f;
area = a;
occupants = o;
// ,
// ,
public int areaPerPerson() {
return area / occupants;
/*
,
. */
public int maxOccupant(int ininArea) {
return area / minArea;

// Building().
class BuildingDemo {
public static void Main() {
Building house = new Building(2, 2500, 4 ) ;
Building office = new Building(3, 4200, 25);
Console.WriteLine(
" , \" +
" ' " +
300 + " : " +
house.maxOccupant(300)) ;
Console.WriteLine(
" , \" +
" " +
300 + " : " +
office.maxOccupant(300));


.
, house office,
Building(). ,
, . ,
I Building house = new Building(2, 2500, 4 ) ;
Building () 2, 2500 4 ,
new Building. floors,
area occupants, house, 2, 2500
4, .

new
, ,
new. :

__ = new _{) ;
6. ,

147

__
. , _
. , .
, new , #. ,
new "" .
, , new , , . . ( , 13.) ,
, "" ,
.

new
, , , ,
: " new
, i n t f l o a t " . # .
. ,
new . ,
, , .. .
, int char,
. , .
.
new .
:
1 i n t i = new i n t ( ) ;
i n t , i . :
// new .
using System;
class newValue {
public static void Main() {
int i = new int(); // i .
Console.WriteLine(" i : " + i ) ;

:
I i :
, i . : new i , WriteLine ()
.
148

I. #

new . . new .

""
, new
. ,
, . , new - .

,
. . , C++
d e l e t e . # -,
.
# , . . , , , .
()
.
. : ""
, , . , # . , , , .

# , ,
. , "" . ,
, .
:
~_() {
//
}
, _ . , ,
"" (~). ( ,
.)
, . , .
, , ,
.
6. ,

149

,
, ,
. ( #- ++-,
, .) ,
, . ,
.
, .
, , .
// .
using System;
class Destruct {
public int x;
public Destruct(int i) {
x = i;
}
// .
-Destruct() {
Console.WriteLine("
}

" + x) ;

// ,
// .
public void generator(int i) {
Destruct = new Destruct(i);

c l a s s DestructDemo {
public s t a t i c void Main() {
i n t count;
Destruct ob = new Destruct(0);
/* .
- .
: ,

. */
for(count=l; count < 100000; count++)
ob.generator(count);
Console.WriteLine("!");
. . ID
( ) .
. g e n e r a t o r ().
D e s t r u c t , . DestructDemo D e s t r u c t ob. , ob,

150

I. #

100 000 , g e n e r a t o r ().


. , , ,
. , .
(.. "!"),
for.
-
,
. . . II #-.
,
. ,
, -
, .

t h i s
t h i s . . ,
(.. , ).
t h i s . t h i s , , Rect, ( ) ,
.
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;

class UseRect {
public static void Main() {
Rect rl = new Rect(4, 5 ) ;
Rect r2 = new Rect(7, 9 ) ;
Console.WriteLine(
" rl: " + rl.areaO);
Console.WriteLine(
" r2: " + r2.area());

6. ,

151

,
, .. . ,
area ()
I return width * height;
, width height,
, .
:
I return this.width * t h i s . h e i g h t ;
t h i s , area (). , this.width width , t h i s . h e i g h t height .
, area () , t h i s
.
t h i s .
Rect, t h i s :
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
this.width = w;
this.height = h;
public int area() {
return this.width

this.height;

class UseRect {
public static void Main() {
Rect rl = new Rect(4, 5 ) ;
Rect r2 = new Rect (7, 9 ) ;
Console.WriteLine(
" rl: " + rl.area());
Console.WriteLine(
" r2: " + r2.area());

#- t h i s ,
, , . t h i s . , # ,
.
.
t h i s . , (
) Rect ().

152

I. #

public Rect(int width, int height) {


this.width = width;
this.height = height;
}

, , t h i s
.

6. ,

153

# (
s t r i n g ) . f oreach.

(array) , . #
, . . , , .
, . , , , , , ,
. ,
.
# ,
, #- ,
: . , ,
( ) ,
.


.
,
.
, .
.
[] __ = new [] ;
.
, . . ,
. ,
, .
, . , , . , #
new.
ilia

C++,
# ,

7.

155

.
int- ( 10 ), sample.

I i n t [ ] sample = new i n t [10];


.
sample , new.
. . #
. sample 10 ,
0 9. , . ,
sample sample [0], sample [9]. , sample 0 9.
// .
using System;
class ArrayDemo {
public static void Main() {
int[] sample = new int[10];
int i ;
for(i = 0 ; i < 10; i = i+1)
sample[i] = i;
for(i = 0 ; i < 10; i = i+1)
Console.WriteLine("sample[" + i + " ] : " +
sample[i]);

:
sample[0]: 0
sample[1]: 1
sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]:
sample[7]: 7
sample[8]: 8
sample[9]: 9
sample :

2 3 4

CD

rH
CD

CM

CD

00

CD

^r
CD

LO

CD

7
r-

CD

CD

8 9
00

CD

CD

,
. ,
,
nums, for .

156

I. #

//
// .
using System;
class Average {
public static void Main() {
int[] nums = new int[10];
int avg = 0;
nums [0]
nums [1]
nums [2]
nums C3]
nums [4]
nums [5]
nums [6]
nums [7]
nums [8]
nums [9]

=
=
=
=
=
=
=
=
=
=

99;
10;
100;
18;
78;
23;
63$
9;
87;
49;

for(int i=0; i < 10;


avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine(": " + avg)

:
I : 53


nums , ..
.
: . :
[] _ = [vail,
val2,
. ..,
valN];
, , vailvaIN. , . # ,
().
new.
Average.
//
// .
using System;
class Average {
public static void Main() {
int[] nums = { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
7.

157

int avg = 0;;


for(int i=0; i < 10; i )
avg = avg + nums[i];
avg = avg / 10;
Console.WriteLine(": " + avg);

, , , new. , nums
,
.
I i n t [ ] nums = new i n t [ ] { 99, 10, 100, 18, 78, 23,
I
63, 9, 87, 49 };
new- , . :
i n t [ ] nums;
nums = new i n t [ ] { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };

I
|

nums .
. ,
. ,
, nums.
i n t [ ] nums = new i n t [ 1 0 ] { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
nums 10.

" "
# " ". . ,
,
.
// .
using System;
class ArrayErr {
public static void Main() {
int[] sample = new int[10];
int i;
// .
for(i = 0; i < 100; i = i+1)
sample[i] = i;

i 10,
IndexOutOfRangeException, .
158

I. #



, "" .
, , .


- .
.
, , .
10x20
t a b l e , :
I m t [ , ] t a b l e = new i n t [ 1 0 , 2 0 ] ;
, .

, .
new
:
| i n t [ 1 0 , 20]
10x20,
.
,
, . , 10
t a b l e , 3 5, :
1 t a b l e [ 3 , 5] = 10;
,
J 12, .
// .
using System;
class TwoD {
public static void MainO {
int t, i;
int[,] table = new int[3, 4 ] ;
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
table[t,i] = (t*4)+i+l;
Console.Write(table[t,i] + " " ) ;
Console.WriteLine() ;

7.

159

t a b l e [ 0 , 0 ] 1,
t a b l e [ 0 , 1 ] 2, t a b l e [ 0 , 2 ] 3 ..
t a b l e [ 2 , 3 ] 12. , . 7.1.

1
1

10

12

table[1][2]

. 7.1.
TwoD

table,

C++,
# . C++
# .


# .
:
[,

.. , ] = new [1,

..., ] ;

, 4x10x3:
I i n t [, ,] multidim = new m t [ 4 , 10, 3 ] ;
100 multidim,
2,4,1, :
I m u l t i d i m [ 2 f 4, 1] = 100;
, ,
- .
// ,
// -.
using System;
class ThreeDMatrix {
public static void Main() {
int[,,] m = new int[3, 3, 3 ] ;
int sum = 0;
int n = 1;
for(int x=0; x <
for(int y=0;
for(int z=0;
m[x, y, z]

160

3; x++)
< 3; y++)
z < 3; z++)
= n++;

I. #

sum

= m[0,0,0] + m [ l , l , l ]

+ m [ 2 , 2, 2 ] ;

C o n s o l e . W r i t e L i n e ( " : " + s u m ) ;

:
: 42


, . ,
:
[,] _ = {
{val, val, val, ..., val}
{val, valf val, ..., val}

{val,

val,

val,

...,

val}

val .
. ,
.. , ,
.
, s q r s 1 10
.
// .
u s i n g System;

c l a s s Squares {
p u b l i c s t a t i c void Main() {
int[,] sqrs = {
{ 1, 1 },
{ 2, 4 },
{ 3, 9 },
{ 4, 16 },
{ 5, 25 },
{ 6, 36 },
{ 7, 49 },
{ 8, 64 },
{ 9, 81 }f
{ 10, 100 }
int

i, j ;

for(i=0; i < 10; i++) {


for(j=0; j < 2; j++)
Console.Write(sqrs[i,j] + " " ) ;
Console.WriteLine();

7.

161

:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100


, # . ,
, . # ,
, . . , .
, . , , :
[]

[]

= n e w

[][];

. , . , jagged ,
"".
i n t [ ] [ ] j a g g e d = new i n t [ 3 ] [ ] ;
j a g g e d [ 0 ] = new i n t [ 4 ] ;
j a g g e d [ 1 ] = new i n t [ 3 ] ;
j a g g e d [ 2 ] = new i n t [ 5 ] ;

jagged :
jagged[0] [0]

jagged[0] [1]

jagged[0] [2]

jagged[1] [0]

jagged[1] [1]

jagged[1] [2]

jagged[2] [0]

jagged[2] [13

jagged[2] [2]

jagged[0] [3]
jagged[2] [3]

jagged[2] [4]

, , , .

. ,
10 jagged 2 1, :
|

jagged[2][1]

= 10;

, , .
.

162

I. #

// ,
using System;
class Jagged {
public static void Main() {
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5j;
int i;
// .
for(i=0; i < 4; i++)
jagged[0][i] = i ;
// .
for(i=0; i < 3; i++)
jagged[l][i] - i ;
// .
for(i=0; i < 5; i++)
jagged[2][i] = i ;
// .
for(i=0; i < 4; i++)
Console.Write(jagged[0][i] + " " ) ;
Console.WriteLine();
// .
for(i=0; i < 3; i++)
Console.Write(jagged[1][i] + " " ) ;
Console.WriteLine();
// .
for(i=0; i < 5; i++)
Console. Write (jagged [2 ] [i] + " 'MrConsole .WriteLine();

:
0 12 3
0 12
0 12 3 4

'

, . ,
(.. , ), , .

7.

163

. ,
, "" . , :
I int[] [,] j agged = new int[3] [,];
j agged [ 0 ] 4x2:
I jaggedfO] = new int[4][2];
i jagged[0][1,0].
| jagged[0][1,0] = i;

,
, , .
. , , :
// .
using System;
class AssignARef {
public static void Main() {
int i;
int[] numsl = new int[10];
int[] nums2 = new int[10];
for(i=0; i < 10; i++) numsl[i] = i ;
for(i=0; i < 10; i++) nums2[i] = - i ;
Console.Write(" numsl: ") ;
for(i=0; i < 10; i++)
Console.Write(numsl[i] + " " ) ;
Console.WriteLine();
Console.Write(" nums2: " ) ;
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " " ) ;
Console.WriteLine();
nums2 = numsl; // nums2 numsl.
Console.Write(
" nums2 : " ) ;
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " " ) ;
Console.WriteLine();
// numsl
i

164

I. #

// nums2.
nums2[3] = 99;
Console.Write(" numsl \" +
" nums2: " ) ;
for(i=0; i < 10; i++)
Console.Write(numsl[i] + " ")
Console.WriteLine();

:
numsl:
0 1 2 3 4 5 6 7 8 9
nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
nums2
:
0 1 2 3 4 5 6 7 8 9
numsl
nums2: 0 1 2 99 4 5 6 7 8 9
, numsl nums2
.

Length
, # ,
. , Length, , .
.
// Length.
using System;
class LengthDemo {
public static void Main() {
int[] nums = new int[10];
Console.WriteLine(" nums " +
nums.Length);
// Length nums.
for(int i=0; i < nums.Length; i++)
nums[i] = i * i;
// Length nums.
Console.Write(" nums: " ) ;
for(int i=0; i < nums.Length; i++)
Console.Write(nums [i] + " " ) ;
Console.WriteLine();

:
nums 10
n u m s : 0 1 4 9 1 6 2 5 3 6 4 9 64 8 1

^ 7.

165

, LengthDemo for
nums. Length . , , . ,
Length
. , .

, "" . :
// Length 3-- .
using System;
class LengthDemo3D {
public static void Main() {
int[,,] nums = new int[10, 5, 6],
Console.WriteLine(" " + nums.Length);

:
1 300
, Length , nums 300 (10 5 6).
().
Length
. ,
Length .
// .
using System;
class RevCopy {
public static void Main() {
int i,j;
int[] numsl
new int[10],
int[3 nums2
new int[10],
for(i=0; i < numsl.Length;

numsl[i] = i;

Console.Write(" : " ) ;
for(i=0; i < nums2.Length; i++)
Console.Write(numsl[i] + " " ) ;
Console.WriteLine();
// numsl nums2
// ,
if (nums2.Length >~ numsl.Length) //
// , nums2
// .

I. #

for(i=0, j=numsl.Length-1; i < numsl.Length; i++f j )


nums2[j] = numsl[i];
Console.Write(" : " ) ;
for(i=0; i < nums2.Length; i++)
Console.Write(nums2[i] + " " ) ;
Console.WriteLine();

:
:
0 1 2 3 4 5 6 7 8 9
:
9 8 7 6 5 4 3 2 1 0

Length . -, , - ,
. -, for, . , ,
Length,
.

Length

L e n g t h
, ("") . , , ,
> () .

// Length
// .

using System;
c l a s s Jagged {
p u b l i c s t a t i c v o i d Main() {
i n t [ ] [ ] n e t w o r k _ n o d e s = new i n t [ 4 ] [ ] ;
n e t w o r k _ n o d e s [ 0 ] = new i n t [ 3 ] ;
network__nodes [1] = new i n t [ 7 ] ;
network__nodes [2] = new i n t [ 2 ] ;
n e t w o r k _ n o d e s [ 3 ] = new i n t [ 5 ] ;
int

i, j ;

//
// .
for(i=0; i < network__nodes .Length; i++)
for(j=0; j < network_nodes[i].Length; j++)
network_nodes [i] [ j ] = i * j + 70,Console.WriteLine (" : " +
network_nodes.Length + " \ n " ) ;
for(i=0; i < network_nodes.Length;
for(j=0; j < network_nodes[i].Length;
7.

167

Console.Write("
" + i +
11
" + j + " : " ) ;
C o n s o l e . W r i t e ( n e t w o r k _ n o d e s [ i ] [ j ] + "% " ) ;
Console.WriteLine();
}

Console.WriteLine ();

:
: 4
0 0: 70%
0 1: 70%
0 2: 70%

1
1
1
1
1
1
1

0: 70%
1: 71%
2: 72%
3: 73%
4: 74%
5: 75%
6: 76%

2 0: 70%
2 1: 72%
3 0: 70%
3 1: 73%
3 2: 7 6%
3 3: 7 9%
3 4: 82%
, Length
n e t w o r k n o d e s . , .

I network_nodes.Length
, network_nodes ( 4). ""
, , , :
network_nodes[0].Length
.

f o r e a c h
5 , # f oreach, "". , .
foreach .
. # ,
. f oreach :

f oreach ( __ in )
168

I. #

_ , f reach . ( ). , ( )
. ,
. , , .
foreach.
. , .
// foreach.
using System;
class ForeachDemo {
public static void Main() {
int sum = 0;
int[] nums = new int[10];
// nums ,
for(int i = 0; i < 10; i++)
nums[i] - i;
// foreach
// ,
foreach(int x in nums) {
Console.WriteLine(" : " + ) ;
sum += ;
}
Console.WriteLine(" : " + sum);
:
: 0
: 1
: 2
: 3
: 4
: 5
:
: 7
: 8
: 9
: 4 5
, foreach .
foreach ,
,
break. ,
nums.

// break foreach.
using System;

7.

169

class ForeachDemo {
public static void Main() {
int sum = 0 ;
int[] nums = new int[10];
// nums ,
for(int i = 0; i < 10; i++)
nums[i] = i;
// foreach
// ,
foreach(int x in nums) {
Console.WriteLine(" : " + ) ;
sum += ;
if( == 4) break; // , 4.
}
Console.WriteLine(" 5 : " + sum);

:
: 0
: 1
: 2
: 3
: 4
5 : 10
, foreach
.
foreach . : .
// foreach .
using System;
class ForeachDemo2 {
public static void Main() {
int sum = 0;
int[,] nums = new int[3,5];
// nums
for(int i 0; i < 3; i++)
for(int j=0; j < 5; j
nums[i,j] =
// foreach
// ,
foreach(int x in nums) {
Console.WriteLine(" : " + )
sum += ;
}
Console.WriteLine(" : " + sum);

170

I. #


:
:
:
:
:
:
:
:
:
:
:
:
:
:
:
: 90

:
1
2
3
4
5
2
4
6
8
10
3
6
9
12
15

f oreach (
), , . . . .
, f oreach . , .
// f o r e a c h .
using System;
class Search {
public static void Main() {
int[] nums = new int[10];
int val;
bool found = false;
// nums ,
for(int i = 0; i < 10; 2++)
nums[i] = i;
val = 5;
// foreach nums
// .
foreach(int x in nums) {
if(x == val) {
found = true;
break;

if(found)
Console.WriteLine(" ! ") ;
foreach , , ..
, foreach .
7.

171



# s t r i n g .
.
. # : .
, s t r i n g . s t r i n g ,
.
s t r i n g , 2,
.
s t r i n g . ,
I Console.WriteLine(" # .");
" # ." # s t r i n g . , s t r i n g .
.


s t r i n g . , s t r s t r i n g , .
1 s t r i n g s t r = "#- - . " ;
s t r "#- - .".
string- char. :
f
c h a r t ] charray = { f t f ,
e \ 'sf,
4'};
s t r i n g s t r = new s t r i n g ( c h a r r a y ) ;

string- , , . , string-
WriteLine (), .
// .
using System;
class StringDemo {
public static void Main() {
chart] charray = {'A1, f \ ' s 1 , 't 1 , 'r 1 , f i ' , f n', g 1 , '.' };
string strl = new string(charray);
string str2 = " string-.";
Console.WriteLine(strl) ;
Console.WriteLine(str2);

172

I. #

:
A string.
string-.


s t r i n g ,
( . 7.1). s t r i n g
Length, .
,
. :
string str = "test";
Console.WriteLine(string[0]);

t
( "test"). , .
,
.
.

7.1.
s t a t i c string Copy (string s t r )

s t r

int

compareTo ( s t r i n g str)

, s t r , ,
s t r , ,

int

i n d e x O f ( s t r i n g str)

, s t r . - 1 ,

int

LastindexOf ( s t r i n g s t r )

, s t r .
- 1 ,

s t r i n g ToLower ( )

s t r i n g ToupperO

, , " = = " .
, "==" , , .
s t r i n g .
. " !=".
(, " > " ">="), ,
.
,
^.
// .
using System;
class Strops {
public s t a t i c void Main() {
string s t r l =
"B .NET- # .";
string str2 = string.Copy(strl);
7.

773

string str3 = "#-


string strUpf strLow;
int result, idx;

.";

Console.WriteLine("strl: " + strl);


Console.WriteLine(" strl: " +
strl.Length);
// strl.
strLow - strl.ToLower();
strUp = strl.ToUpper();
Console.WriteLine(" strl:\n
strLow);
Console.WriteLine(" strl:\n
strUp);

" +
" +

Console.WriteLine();
// strl .
Console.WriteLine(" strl .");
for(int i=0; i < strl.Length; i++)
Console.Write(strl[i]);
Console.WriteLine("\n");
// ,
if (strl ===== str2)
Console.WriteLine("strl == str2");
else
Console.WriteLine("strl != str2");
if(strl str3)
Console.WriteLine("strl == str3") ;
else
Console.WriteLine("strl != str3");
result = strl.CompareTo(str3);
if(result == 0)
Console.WriteLine("strl str3 .");
else if(result < 0)
Console.WriteLine("strl , str3");
else
Console.WriteLine("strl , str3");
Console.WriteLine();
// str2 .
str2 = " ";
// .
idx = str2.IndexOf("");
Console.WriteLine(
" : " + idx);
idx = str2.LastIndexOf("");
Console.WriteLine(
" : " + idx);

174

I. #

:
strl: .NET- # .
strl: 43
strl:
.net- # .
strl:
.NET- # .
strl .
.NET- # .
strl == str2
strl != str3
strl , str3
:
: 13

,
string strl
string str2
string str3
string str4

" + " () .

= "";
= "";
^
= "";
= strl + str2 + str3;

s t r 4 "".
. s t r i n g
System, s t r i n g , .NET Framework.
, , s t r i n g ,
System. S t r i n g ( ).
System. S t r i n g II.


, . .
//

u s i n g System;
class StringArrays {
public s t a t i c void Main() {
string[] s t r = { "", "", "", "."
Console.WriteLine(" : " ) ;
for(int i=0; i < str.Length; i++)
Console.Write(str[i] + " " ) ; "
Console.WriteLine("\n");

};
t

// .
str[l] = "";
str[3) = ", ?";
Console.WriteLine(" : " ) ;
for(int i=0; i < str.Length;
Console.Write(str[i] + " " ) ;

7.

175

:
:
.
:
, ?

.
. , 19 " ".
// .
using System;
class ConvertDigitsToWords {
public static void Main() {
int num;
int nextdigit;
int numdigits;
int[] n = new int[20];
string[] digits = { "", "", "",
"", "", "",
"", "", "",
"" };
num = 1908;
Console.WriteLine(": " + num);
Console.Write(" : " ) ;
nextdigit = 0 ;
numdigits - 0;
/* .
. */
do {
nextdigit - num % 10;
n[numdigits] = nextdigit;
numdigits++;
num = num / 10;
} while(num > 0 ) ;
numdigits;
// .
for( ; numdigits >= 0; numdigits)
Console.Write(digits[n[numdigits]] + " " ) ;
Console.WriteLine() ;

:
: 1908
:

176

I. #

string- d i g i t s
. , , , int-
. ,
d i g i t s , .


, , : string- . , , , . , .
# . , " " , , .
, "" .
, s t r i n g
, . s t r i n g .
,
, s t r i n g : Substring ().
,
. string-, ,
, .
Substring ():
s t r i n g S u b s t r i n g ( i n t start,
i n t len)
start , len .
, Substring ()
.
// S u b s t r i n g ( ) .
using System;
c l a s s SubStr {
p u b l i c s t a t i c void Main() {
s t r i n g o r g s t r = "C# .";
// .
s t r i n g s u b s t r = o r g s t r . S u b s t r i n g ( 4 , 14);
Console.WriteLine("orgstr:
Console.WriteLine("substr:

" + orgstr);
" + substr);

:
o r g s t r : C# ,
s u b s t r :

7.

177

, o r g s t r , s u b s t r .
string- , ,
. # S t r i n g B u i l d e r ,
System.Text. ,
. s t r i n g , S t r i n g B u i l d e r .

switch-
switch- string-, , , i n t . . ,
"", "" "".
//
// switch.
using System;
class StringSwitch {
public static void Main() {
string[] strs = { "", "", "", "", "" };
foreach(string s in strs) {
switch(s) {
case "":
Console.Write(Inbreak;
case "":
Console.Write(2);
break;
case "":
Console.Write ( 3 ) ;
break;
Console.WriteLine();

:
12321

178

I. #

.
.
, , Main (), s t a t i c .


, . , (
6). -, .
.
,
: . , .
.
, . .
, .
,
, , , . ,
, . , . , " ",
, .

#

: p u b l i c , p r i v a t e , p r o t e c t e d i n t e r n a l .
p u b l i c p r i v a t e .
p r o t e c t e d 9. i n t e r n a l
(assembly) 16.
p u b l i c , , .
p r i v a t e
, . ,
private- .
6,
( p r i v a t e ) . , p r i v a t e .
. :
public string errMsg;
private double bal;
private bool isError(byte status) { // ...

180

I. C#

public private, :
// .
using System;
class MyClass {
private int alpha; // private,
int beta;
// private ,
public int gamma; // public.
/* alpha beta.

private- .
*/
public void setAlpha(int a) {
alpha = ;
}

public int getAlpha() {


return alpha;
}
public void setBeta(int a) {
beta = a;
public int getBetaO {
return beta;

class AccessDemo {
public s t a t i c void Main() {
MyClass ob = new MyClass();
/* private- alpha beta
. */
ob.setAlpha(-99);
ob.setBeta(19);
Console.WriteLine(" ob.alpha " +
ob.getAlpha());
Console.WriteLine(" ob.beta " +
ob. getBetaO ) ;

//
//

// private- alpha beta


// :
ob.alpha = 10; // ! alpha -- !
ob.beta = 9 ;
// ! beta -- !
//
/ / gamma, .
ob.gamma = 99;

, MyClass alpha private-,


beta private- , a gamma public-.
8.

181

alpha b e t a , ""
. , AccessDemo
.
(public-) , setAlphaO getAlpha().

1 // ob.alpha = 10; // ! alpha -- ! ,

. alpha
MyClass , , MyClass (setAlphaO
getAlpha ()), . b e t a .
, ,
, .

p u b l i c p r i v a t e
p u b l i c p r i v a t e -
- . , ,
.
1. , ,
.
2. , , , , .
3. , (.. ),
.
4. , , ,
, .
5. , ,
.
6. ,
.
, ,
. , , "" .

:
. - , . ( , : .
, , .)

182

I. #

- ,
,
.
, , , , .
:
.
. .
Stack,
. .

s t a c k . , " " . s t a c k
,
.
// .
using System;
class Stack {
// .
char[] stck; // .
int tos;
// .
// Stack ,
public Stack(int size) {
stck = new char[size]; // .
tos = 0;
}
// .
public void push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return;
stck[tos] = ch;
tos++;
// ,
public char pop() {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;
tos;
return stck[tos];
// true, ,
public bool full() {
return tos==stck.Length;

8.

183

// true, ,
public bool empty() {
return tos==0;
// ,
public int capacity() {
return stck.Length;
// ,
public int getNum() {
return tos;

Stack .
:
c h a r [ ] s t c k ; // ,
int tos;
// .
s t c k , . , . stack. t o s
.
s t c k t o s ,
"
". s t c k , . ,
t o s "" , , stack. s t c k t o s ,
.
:
// Stack ,
public Stack(int size) {
stck = new char[size]; // .
tos = 0;
}
.
t o s . , t o s , .
push () .
:
// ,
public void push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return;
stck[tos] = ch;
tos++;

184

I. #

, , ch.
, , , .
, t o s s t c k .
, s t c k ,
t o s , t o s . , t o s s t c k .
, pop (). :
// ,
public char pop() {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;

tos ;

return stckftos];

t o s . , ,
. t o s ,
.
push () pop () ,
, ,
, s t a c k
( f u l l ( ) , empty ( ) , c a p a c i t y () getNumO). . .
// true, ,
public bool full() {
return tos==stck.Length;
}
// true, ,
public bool empty() {
return tos==0;
}

'

// ,,
public int capacity() {
return stck.Length;
}
// .
public int getNumO {
return tos;
}
f u l l () t r u e , , f a l s e
. empty () t r u e , , f a l s e . (..
, ), c a p a c i t y ( ) .
, ,
getNumO. , ,
8.

185

, t o s ,
Stack.
.
// Stack.
using System;
class StackDemo {
public static void
Stack stkl = new
Stack stk2 = new
Stack stk3 = new
char ch;
int i ;

Main() {
Stack(lO);
Stack(lO);
Stack(lO);

// stkl.
Console.WriteLine(
" Z stkl.");
for(i=0; !stkl.full(); i++)
stkl.push((char) (fAf + i) ) ;
if (stkl.fulK) ) Console.WriteLine (" stkl .");
// stkl.
Console.Write(" stkl: " ) ;
while( !stkl.empty() ) {
ch = stkl.pop();
Console.Write(ch);
}
Console.WriteLine();
if(stkl.empty()) Console.WriteLine(" stkl .");
// stkl.
Console.WriteLine(
" Z stkl.");
for(i=0; !stkl.full(); i++)
stkl.push((char) (fAf + i));
/* stkl
stk2.
stk2
. */
Console.WriteLine(
" stkl \" +
" stk2.");
while( !stkl.empty() ) {
ch = stkl.pop();
stk2.push(ch) ;
}
Console.Write(" stk2: ") ;
while( !stk2.empty() ) {
ch = stk2.pop();
Console.Write(ch) ;

186

I. C#

Console.WriteLine("\n");
// 5 stk3.
Console.WriteLine(" 5 stk3.");
for(i=0; i < 5; i++)
stk3.push((char) (fAf + i));
Console.WriteLine(
" stk3: " + stk3.capacity());
Console.WriteLine(
" stk3: " +
stk3.getNum());

:
Z stkl.
stkl .
stkl: JIHGFEDCBA
stkl .
Z stkl.
stkl
stk2.
stk2: ABCDEFGHIJ
5 stk3.
stk3: 10
stk3: 5


i n t
double. . , , :
// .
using System;
class MyClass {
int alpha, beta;
public MyClass(int i, int j) {
alpha =' i ;
beta = j ;
}

/* true, ob
, . */
public bool sameAs(MyClass ob) {
if((ob.alpha == alpha) & (ob.beta == beta))
return true;
else return false;

8.

187

// ob.
public void copy(MyClass ob) {
alpha = ob.alpha;
beta = ob.beta;
public void show() {
Console.WriteLine("alpha: {0}, beta: {1}",
alpha, beta);

class PassOb {
public static void Main() {
MyClass obi = new MyClass(4, 5 ) ;
MyClass ob2 = new MyClass(6, 7 ) ;
Console.Write("obi: " ) ;
obi.show();
Console.Write("ob2: " ) ;
ob2.show();
if(obi.sameAs(ob2))
Console.WriteLine(
"obi 2 .");
else
Console.WriteLine(
"obi 2 .");
Console.WriteLine();
// obi 2.
obi.copy(2);
Console.Write("obi : " ) ;
obi.show();
if(obi.sameAs(ob2))
Console.WriteLine(
"obi 2 .");
else
Console.WriteLine(
"obi 2 .");

, :
obi: alpha: 4, beta: 5
ob2: alpha: , beta: 7
obi 2 .
obi : alpha: , beta: 7
obi 2 .
sameAs () () . sameAs() alpha b e t a
alpha b e t a , ob.

188

I. #

t r u e ,
. ()
alpha b e t a , ob,
alpha b e t a .
, MyClass.
, ( ) ,
.



. , . . ,
.
(call-by-value). . , , , , .
(call-by-reference).
, , . , , ,
, .
(, i n t double)
. , , ,
, . :
// .
u s i n g System;
class Test {
/* ,
. */
public void noChange(int i, int j) {
i = i + j;
j
j = -j;

class CallByValue {
public static void Main() {
Test ob = new Test();
int

a = 15, b = 20;

Console.WriteLine(" b : " +
a + " " + b) ;
ob.noChange(a, b ) ;
Console.WriteLine(" b : " +
a + " " + b) ;

8.

189

:
I b : 15 20
I b : 15 20
, , noChange ( ) ,
, .
.
, . , , , , , ,
. (, , , .)
(, ) , ,
, , . , .
,
. , ,
, , .
, . , ,
. , , :
// .
using System;
class Test {
public int a, b;
public Test(int i, int j) {
a = i;
b = j;
}
/* . ob.a ob.b ,
, . */
public void change(Test ob) {
ob.a = ob.a + ob.b;
ob.b = -ob.b;

class CallByRef {
public static void Main() {
Test ob = new Test(15, 20);
Console,WriteLine("ob.a ob.b :
ob.a + " " + ob.b);
ob.change(ob);
Console.WriteLine("ob. ob.b :
ob.a + " " + ob.b);

:
ob.a ob.b : 15 20
ob.a ob.b : 35 -20

190

I. #

, change () ,
.
,
. . ,
.

r e f - out-
, (,
i n t char) . , , , ,
, .
. r e f out,
. , .
ref out,
, .
:
. .
, , . swap ( ) ,
. , i n t , #-
. ref.
, r e t u r n ,
.
. , ? , , .
: . ,
. out.

r e f
ref # . ref
. . sqr (), . ref.
// ref
// .
using System;
class RefTest {
/* .
ref.
public void sqr(ref i n t i) {
i = i * i;
8.

*/

191

class RefDemo {
public static void Main() {
RefTest ob = new RefTestO;
int a = 10;
Console.WriteLine(" : " + a ) ;
ob.sqr(ref a ) ; //
/ / ref.
Console.WriteLine(" : " + ) ;

,
. , sqr ().
: 10
: 100

ref, ,
. , , swap (), , .
// .
using System;
class Swap {
// ,
public void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;

class SwapDemo {
public static void Main() {
Swap ob = new Swap();
int x = 10, = 20;
Console.WriteLine("x :
+ " " + ) ;
ob.swap(ref x, ref y) ;
Console.WriteLine("x :
+ " " + ) ;

192

I. #

:
: 10 20
: 20 10
. , " " ref, .
, , , ,
. , ref,
, .

out

, . , , , ,
,
. , . ref, ref-
. , ref
, . , # , out.
out r e f :
. (
) , out-, . , , out-
"" , ( ) . ,
out- .
out-. Decompose
p a r t s () . , .
// o u t .
using System;
class Decompose {
/*
. */
public int parts(double n, out double frac) {
int whole;
whole = (int) n;
frac = n - whole; //
// frac.
return whole; // .

c l a s s UseOut {
p u b l i c s t a t i c void Main() {
Decompose ob = new Decompose();
8.

193

int i;
double f;
i = ob.parts(10.125, out f ) ;
Console.WriteLine(" " + i ) ;
Console.WriteLine(" " + f ) ;

:
10
0.125

p a r t s () . r e t u r n . out- f . , out-,
, , .
, # out-. out-
, . o u t . isComDenomO . -, , .
t r u e , , f a l s e
. -, ,
isComDenomO out-
.
// out-.
u s i n g System;
class Num {
/* , v .
,
out-. */
public bool isComDenom(int x, int ,
out int least,
out int greatest) {
int i;
int max = x < ? x : y;
bool first = true;
least = 1;
greatest = 1;
// .
for(i=2; i <= max/2 + 1; i++) {
if( ((y%i)==0) & ((x%i)==0) ) {
if(first) {
least = i;
first = false;
}
greatest = i;

if(least

194

!= 1) return true;

I. #

else return false;

c l a s s DemoOut {
public s t a t i c void Main() {
Num ob = new Num();
i n t led, gcd;
if(ob.isComDenom(231, 105, out led, out gcd)) {
Console.WriteLine("Led 231 105 " +
led) ;
Console.WriteLine("Gcd 231 105 " +
gcd) ;
}

else
Console.WriteLine(
" 35 4 9 .");
if(ob.isComDenom(35, 51, out
Console.WriteLine("Led
led) ;
Console.WriteLine("Gcd
gcd) ;
}
else
Console.WriteLine(
" 35 51

led, out gcd)) {


35 51 " +
35 51 " +

.");

, Main() led gcd isComDenomO. ,


out-, a ref-.
t r u e ,
f a l s e . , ,
out- l e d gcd, . (Led least common denominator, .. , a gcd
greatest common denominator, .. .)
:
Lcd 231 105 3
Gcd 231 105 21
35 51 .

r e f out

r e f out
. , .. ,
.
ref out,
. , . , ref-
, .
8.

195

// ,
using System;
class RefSwap {
int a, b;
public RefSwap(int i, int j) {
a = i;
b = j;
public void show() {
Console.WriteLine("a: {0}, b: {1}", a, b)
// ,
public void swap(ref RefSwap obi, ref RefSwap ob2) {
RefSwap t;
t = obi;
obi = ob2;
ob2 = t;

class RefSwapDemo {
public static void Main() {
RefSwap x = new RefSwap(1, 2 ) ;
RefSwap = new RefSwap(3, 4 ) ;
Console.Write("x : ") ;
x.show();
Console.Write(" : " ) ;
.show();
Console.WriteLine();
// , .
.swap(ref , ref ) ;
Console.Write(" : " ) ;
.show();
Console.Write(" : " ) ;
.show();

:
: : 1, : 2
: : 3, : 4
: : 3, : 4
: : 1, : 2

196

I. #

swap () ,
. swap () ,
1 2, , 3 4. swap () ,
3 4, , 1 2. ref-, swapO "" .
, swap ().

,
. ,
. , , , . , . .
. , . params.
params -,
( ). , .
, params
minVal (), .
// params.
using System;
class Min {
public int minVal(params int[] nums) {
int m;
if(nums.Length = = 0 ) {
Console.WriteLine(":
r e t u r n 0;

.");

m = nums [0];
for (int i=l; i < nums.Length; i++)
if(nums[i] < m) m = nums[i];
return m;

class ParamsDemo {
public static void Main() {
Min ob = new Min();
int min;
int a = 10, b = 20;

8.

197

// .
min = ob.minVal(a, b ) ;
Console.WriteLine(" " + min);
// call with 3 values
min = ob.minVal(a, b, - 1 ) ;
Console.WriteLine(" " + min);
// ,
min = ob.minVal(18, 23, 3, 14, 25);
Console.WriteLine(" " + min);
// int-.
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.minVal(args);
Console.WriteLine(" " + min);

:
10
-1
3
8

minVal ()
nums. . minVal
.
params- , , , . , minVal ()
1 min = ob.minVal(1, 2 . 2 ) ;
, double (2.2)
i n t ( i n t nums minVal ()) .
params
, params- , / ,
minVal () :
min - ob.minVal ();
//
min = ob.minVal(3); //

minVal () nums . , minVal ()


. ( .)
, minVal () ,
. () .

. , showArgs () s t r i n g params- .
1 //
I // params-.

198

I. #

using System;
class MyClass {
public void showArgs(string msg, params int[] nums) {
Console.Write(msg + ": " ) ;
foreach(int i in nums)
Console.Write(i + " " ) ;
Console.WriteLine();

class ParamsDemo2 {
public static void Main() {
MyClass ob = new MyClass();
ob.showArgs(" ",
1, 2, 3, 4, 5 ) ;
ob.showArgs(" ",
17, 20);

:
: 1 2 3 4 5
: 17 20

params-, params-
.


, . ,
Rect e n l a r g e ( ) ,
( ) ( ) .
// .
using System;
class Rect {
int width;
int height;
public Rect(int w, int h) {
width = w;
height = h;
}

public int area() {


return width * height;

8.

199

public void show() {


Console.WriteLine(width + " " + height);
/* ,

. */
public Rect enlarge(int factor) {
return new Rect(width * factor, height * factor);

class RetObj {
public static void Main() {
Rect rl = new Rect(4, 5 ) ;
Console.Write(" rl: " ) ;
rl.show();
Console.WriteLine(" rl: " +
rl.areaO ) ;
Console.WriteLine();
// ,
// rl .
Rect r2 = rl.enlarge(2);
Console.Write(" r2: " ) ;
r2.show();
Console.WriteLine(" 2: " +
r2.area());
}
}
:
rl: 4 5
rl: 20
2: 8 10
2: 80
, , , . , , ..
. ,
, .
, , , (class factory). "" , .

,
, .
"" . :
// "" .
using System;

200

I. #

class MyClass {
int a, b; //
// "" MyClass.
public MyClass factory(int i, int j) {
MyClass t = new MyClass();
t.a = i;
t.b = j;
return t; // .
public void show() {
Console.WriteLine(" b: " + a + " " + b) ;

c l a s s MakeObjects {
p u b l i c s t a t i c void Main() {
MyClass ob = new MyClass();
int i, j ;
// "" .
f o r ( i = 0 , j = 10; i < 10; i++, j ) {
MyClass anotherOb = o b . f a c t o r y ( i , j ) ; //
// .
anotherOb.show();
Console.WriteLine();
:
: 0 10
: 1 9
: 2 8
: 3 7
: 4 6
: 5 5
: 6 4
: 7 3
: 8 2
: 9 1
. MyClass , , # . , b .
b "" , f a c t o r y (). ,
b , f a c t o r y ()
.
Main () ob MyClass, for . ,
"" .
1 MyClass anotherOb = o b . f a c t o r y ( i , j ) ; //
8.

201

anotherOb,
, "" .
anotherOb , , , .


# , . ( # C++, ,
, , .) ,
findf a c t o r s () , , .
/ .
using System;
class Factor {
/* ,
num.
out- numfactors
. */
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80]; // 80 ,
int i, j ;
// facts.
for(i=2, j=0; i < num/2 + 1;
if( (num%i)==0 ) {
facts[j] = i;

numfactors = j;
return facts;

class FindFactors {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;

factors = f.findfactors(1000, out numfactors);


Console.WriteLine(" 1000: " ) ;
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " " ) ;
Console.WriteLine();

:
1000:
2 4 5 8 10 20 25 40 50 100 125 200 250 500

202

I. #

F a c t o r findf a c t o r s () :
I public int[] findfactors(int num, out int numfactors) {
, i n t . . , ,
() , .
, someMethO, double-.
p u b l i c d o u b l e t , ] someMethO { // . . .



# . #
, , .
(method overloading), ,
, (overloaded). #.

. .
: , / . . . ( ,
#, ,
.) , . , ( ) .
, :
// .
using System;
class Overload {
public void ovlDemo() {
Console.WriteLine(" ");
}
// ovlDemo()
// ,
public void ovlDemo(int a) {
Console.WriteLine(" : " + a ) ;
}
// ovlDemo()
// ,
public int ovlDemo(int a, int b) {
Console.WriteLine(" int-: " + a + " " + b ) ;
return a + b;
// ovlDemo()

8.

203

// double-.
public double ovlDemo(double a, double b) {
Console.WriteLine(" double-: " +
a + " "+ b ) ;
return a + b;

class OverloadDemo {
public static void Main() {
Overload ob = new OverloadO;
int resl;
double resD;
// ovlDemo().
ob.ovlDemo();
Console.WriteLine();
ob.ovlDemo(2);
Console.WriteLine();
resl = ob.ovlDemo(4, 6 ) ;
Console.WriteLine(" ob.ovlDemo(4, 6 ) :
+ resl);
Console.WriteLine();
resD = ob.ovlDemo(1.1, 2.32);
Console.WriteLine(
" ob.ovlDemo(1.1, 2.2):
resD);

:

: 2
int-: 4
ob.ovlDemo(4, ) : 10
double-: 1.1 2.32
ob.ovlDemo(I.1, 2.2): 3.42
, ovlDemo () .
, ,
, double-. , ovlDemo () void, ..
,
. , , , . ovlDemo () :
// ovlDemo(int) ,
public void ovlDemo(int a) {
Console.WriteLine(" : " + a ) ;

204

I. #

// ! ovlDemo(int) ,
// ,
// ,
p u b l i c i n t ovlDemo(int a) {
Console.WriteLine(" : " + a ) ;
r e t u r n a * a;
}

, , , .
3, # .
. , , .
/*
. */
using System;
class 0verload2 {
public void f ( i n t x) {
Console.WriteLine(" f ( i n t ) :
p u b l i c void f(double x) {
Console.WriteLine("

" + x);

f ( d o u b l e ) :

" + x)

class TypeConv {
public static void Main() {
Overload2 ob = new 0verload2();
int i = 10;
double d = 10.1;
b y t e b = 99;
s h o r t s = 10;
f l o a t f = 11.5F;
ob.f(i); // ob.f(int).
ob.f(d); // ob.f(double).
ob.f(b); // ob.f(int)
// ,
ob.f(s); // ob.f(int)
// ,
ob.f(f); // ob.f(double)
// .

:
f(int): 10
f(double): 10.1
f(int): 99
f(int): 10
f(double): 11.5

8.

205

f (): i n t - ,
double-. f ()
i n t double byte, s h o r t f l o a t . byte short- # i n t (.. f ( i n t ) ) . float-
double f (double).
,
, . f ( ) ,
_byte.
// f(byte).
using System;
class 0verload2 {
public void f(byte x) {
Console.WriteLine(" f(byte): " + x ) ;
}
public void f(int x) {
Console.WriteLine(" f(int): " + x) ;
}
public void f(double x) {
Console.WriteLine(" f(double): " + x) ;

class TypeConv {
public static void Main() {
0verload2 ob = new 0verload2();
int i = 10;
double d = 10.1;
byte b = 99;
short s = 10;
float f = 11.5F;
ob.f(i); // ob.f(int).
ob.f(d); // ob.f(double).
ob.f(b); // ob.f(byte) -
// .
ob.f(s); //
//
ob.f(f); //
//

ob.f(int)
,
ob.f(double)
.

:
f(int): 10
f(double): 10.1

206

I. #

f ( b y t e ) : 99
f ( i n t ) : 10
f ( d o u b l e ) : 11.5

, f (),
byte, f () byte- f (byte), byte-
i n t .
ref-, out- ""
>. , .
p u b l i c void f ( i n t x) {
Console.WriteLine(" f(int): " + x ) ;
}
public void f(ref int x) {
Console.WriteLine(" f(ref int): " + x ) ;
}
,
ob.f(i);

f ( i n t x),
| ob.f(ref i ) ;
f (ref i n t x).
# ,
# "
". , , . , ,
. . , , , . ,
,
, . , abs () () , l a b s () ,
f abs () .
, , ,
.
, . ,
( ) .
# "" , . , # Abs (). #- System.Math, , .
, , .
, , . , Abs () , .
. , . . ,
, .
8,

207

, . , .
-
"" . , ,
,
. , s q r
, , , . ,
. .
# (signature),
. ,

. , , , # . pa rams-, . ,
params
.


, .
. :
// .
using System;
class MyClass {
public int x;
public MyClass() {
Console.WriteLine(" MyClass().");
x = 0;
p u b l i c MyClass(int i) {
Console.WriteLine("
x = i;

M y C l a s s ( i n t ) . " ) ;

public MyClass(double d) {
Console.WriteLine(
" MyClass(double).");
x = (int) d;
}
public MyClass(int i, int j) {
Console.WriteLine(
" MyClass(int, int).");
x = i * j;

208

I. #

class OverloadConsDemo {
public static void Main() {
MyClass tl = new MyClassO;
MyClass t2 = new MyClass(88);
MyClass t3 = new MyClass(17.23);
MyClass t4 = new MyClass(2, 4 ) ;
Console.WriteLine("tl.x:
Console.WriteLine("t2.x:
Console.WriteLine("t3.x:
Console.WriteLine("t4.x:

"
"
"
"

+
+
+
+

tl.x);
t2.x);
t3.x);
t4.x);

:




tl.x: 0
t2.x: 88
t3.x: 17
t4.x: 8

MyClassO.
MyClass(int).
MyClass(double).
MyClass(int, int).

MyClass () , -. ,
new, .
, .
. , s t a c k , :
// .
u s i n g System;
class Stack {
// .
char[] stck; // .
int tos;
// .
// Stack ,
public Stack(int size) {
stck = new char[size]; // .
tos = 0;
// Stack- ,
public Stack(Stack ob) {
// .
stck = new char[ob.stck.Length];
// ,
for(int i=0; i < ob.tos;
8.

209

stckfi] = ob.stckfi];
// tos ,
tos = ob.tos;
// .
public void push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" .");
return;
stck[tos] = ch;
tos++;
// ,
public char pop() {
if(tos==0) {
Console.WriteLine(" .");
return (char) 0;
tos;
return stckftos];
// true, ,
public bool full () {
return tosstck. Length;
// true, ,
public bool empty() {
return tos==0;
// ,
public int capacity() {
return stck.Length;
// ,
public int getNum() {
return tos;

// Stack,
class StackDemo {
public static void Main() {
Stack stkl = new Stack(10);
char ch;
int i ;
// stkl.
Console.WriteLine(

210

I. #

" Z stkl.");
for(i=0; !stkl.full(); i++)
stkl.push((char) (fAf + i));
// stckl.
Stack stk2 = new Stack(stkl);
// stkl.
Console.Write(" stkl: " ) ;
while( !stkl.empty() ) {
ch - stkl.pop();
Console.Write(ch);
Console.WriteLine();
Console.Write(" stk2: ")
while ( !stk2.empty() ) {
ch = stk2.pop();
Console.Write(ch);
Console.WriteLine("\n");

:
Z s t k l .
s t k l : JIHGFEDCBA
s t k 2 : JIHGFEDCBA

StackDemo s t k l ,
. s t k 2 ,
stack.
// Stack- ,
public Stack(Stack ob) {
// ,
stck = new char[ob.stck.Length];
// .
for(int i=0; i < ob.tos; i++)
stck[i] = o b . s t c k [ i ] ;
// tos ,
tos = ob.tos;
s t c k
, , , ob. ,
ob, ,
t o s .
,
.

8.

211

this
. #
t h i s . :
_ (__1) :
t h i s (__2) {
/I . . . ,
// .
}

,
_2.
, .
:
// this.
using System;
class XYCoord {
public int x, y;
public XYCoord() : this(0, 0) {
Console.WriteLine (" XYCoordO");
}
public XYCoord(XYCoord obj) : this(obj.x, obj.y) {
Console.WriteLine(" XYCoord(obj)");
}
public XYCoord(int i, int j) {
Console.WriteLine(" XYCoord(int, int)");
x = i;
= j;

class OverloadConsDemo {
public static void Main() {
XYCoord tl = new XYCoordO;
XYCoord t2 = new XYCoord(8, 9 ) ;
XYCoord t3 = new XYCoord(t2);
Console.WriteLine("tl.x, tl.y: " + tl.x + ", " + tl.y);
Console.WriteLine("t2.x, t2.y: " + t2.x + ", " + t2.y);
Console.WriteLine("t3.x, t3.y: " + t3.x + ", " + t3.y);


XYCoord(int,
XYCoord()
XYCoord(int,
XYCoord(int,
XYCoord(obj)
tl.x, tl.y: 0, 0
t2.x, t2.y: 8, 9
t3.x, t3.y: 8, 9
212

:
int)
int)
int)

I. #

. XYCoord ,
, XYCoord ( i n t , i n t ) . XYCoord ( i n t , i n t ) ,
t h i s . , t l
XYCoord (), t h i s (0, 0), XYCoord (0, 0). t 2 .
t h i s
, .
t h i s .
" " , , . ,
XYCoord :
1 p u b l i c XYCoord(int x) : t h i s ( , ) { }
. , " "
,
.

Main ()
Main (). . ,
. .

Main ()

( ). Main ():
p u b l i c s t a t i c i n t Main()
, void, Main
i n t .
, Main(), ,
( ). , , .
.

Main()
.
,
. Main ().
Main ():
p u b l i c s t a t i c void M a i n ( s t r i n g [ ] args)
p u b l i c s t a t i c i n t M a i n ( s t r i n g [ ] args)
8.

213

void,
, . string-, Main ().
,
.
// .
using System;
class CLDemo {
public s t a t i c void Main(string[] args) {
Console.WriteLine(" " +
args.Length
+
11
. ") ;
Console.WriteLine(" : " ) ;
f o r ( i n t i=0; i<args.Length;
Console.WriteLine(args[i]);
, CLDemo :
CLDemo
:
5 .
:

" "
, . .
, , . : , 1. ""
"" .. , 1.
// .
using System;
class Cipher {
public s t a t i c i n t Main(string[] args) {
// ,
if(args.Length < 2) {
Console.WriteLine(
": " +
"1: / " +
" [ 2 . . . ]");
r e t u r n 1; // .
}

// ,

214

I. #

// "" "".
if(args[0] != "" & args[O] != "") {
Console.WriteLine(
" " +
"\"\" \"\".");
return 1; // .
// .
for(int n=l; n < args.Length; n++) {
for(int i=0; i < args[n].Length;
if(args[0]=="")
Console.Write((char) (args[n][i] + 1 ) );
else
Console.Write((char) (args[n][i] - 1) );
}
Console.Write (" " ) ;
Console.WriteLine();
return 0;

,
"" "", ,
. , Cipher,
.
D:\Cipher

D:\Cipher

. -,
, . , . , 4 ,
.
. ,
"" "", , ,
.
-, , . ,
1, . , 0,
.

# . , ,
, . - .
8.

215


. .
. N 1 N ,
3 1x2x3, 6.
.
.
// .
using System;
class Factorial {
// ,
public int factR(int n) {
int result;
if(n==l) return 1;
result = factR(n-l) * n;
return result;
// ,
public int factl(int n) {
int t/ result;
result = 1;
for(t=l; t <= n; t++) result *= t;
return result;

class Recursion {
public static void Main() {
Factorial f = new Factorial();
Console.WriteLine(
", " +
" .");
Console.WriteLine(" 3 " +
f.factR(3));
Console.WriteLine(" 4 " +
f,factR(4));
Console.WriteLine(" 5 " +
f.factR(5));
Console.WriteLine() ;
Console.WriteLine(
", " +
" .");
Console.WriteLine(" 3 " +
f.factl(3));
Console.WriteLine(" 4 " +
f.factl(4));
Console.WriteLine(" 5 " +
f.factl (5));

216

I. #

,
3
4
5

24
120

,
3
4
5

24
120

f a c t l . , , 1 ( 1) ,
.
f actR () . , 1, 1.
f a c t R ( n - l ) * .
f actR () - 1 . ,
1, .
, 2 f actR ()
, , 1. factRO 1, 2
( ). ,
factRO W r i t e L i n e O , .
,
,
. .
.
, "" .
. displayRev() .
// .
using System;
class RevStr {
// ,
public void displayRev(string str) {
if(str.Length > 0)
displayRev(str.Substring(1, str.Length-1));
else
return;
Console.Write(str[0]);

class RevStrDeino {
public static void Main() {
string s = " ";
RevStr rsOb = new RevStr();

8.

217

Console.WriteLine(" : " + s ) ;
Console.Write(" : " ) ;
rsOb.displayRev(s);
Console.WriteLine();

:
:
:

displayRev () ,
s t r , displayRev ()
-, s t r . ,
. , , .. s t r . .
, , - ,
. . , , .
#- .
, .
,
, . , Quicksort .
, .

(, if-), . , ,
, . .
WriteLine ( ) , ,
, .

s t a t i c
, .
. , , .. . , s t a t i c .
s t a t i c ,
. s t a t i c
, . static-
Main (), .
218

I. #

static-
"". . s t a t i c , . , 10 static- count, Timer, :
I Timer.count = 10;
,
,
. static-, ..
"" .
, static-, . static- , s t a t i c . static- .
, static-, , ; n u l l , bool f a l s e . , s t a t i c .
s t a t i c - , static-
,
. ,
static- Sqrt (), System.Math.
static- static-.
// s t a t i c .
using System;
class StaticDemo {
// ,
public static int val = 100;
// ,
public static int valDiv2() {
return val/2;

class SDemo {
public s t a t i c void Main() {
Console.WriteLine(
" StaticDemo.val
+ StaticDemo.val);
StaticDemo.val = 8;
Console.WriteLine(
" StaticDemo.val " +
StaticDemo.val);
Console.WriteLine("StaticDemo.valDiv2(): " +
StaticDemo.valDiv2() ) ;
:
8.

219

StaticDemo.val 100
StaticDemo.val 8
StaticDemo.valDiv2(): 4
, static- , .. , .
static- .
1. static- t h i s .
2. static- static-.
. ,
,
static-.
3. static- static-.
, .
, static- valDivDenomO :
class StaticError {
int denom = 3 ; //
s t a t i c i n t val = 1024; //
/* !
. */
s t a t i c i n t valDivDenom() {
return val/denom; // !

denom ,
. val , static-.

^tatic- . :
using System;
class AnotherStaticError {
// ,
void nonStaticMeth() {
Console.WriteLine("

n o n S t a t i c M e t h ( ) . " ) ;

/* !
. */
s t a t i c void statiqMeth() {
nonStaticMeth(); // !
(.. )
.
, static- ,
. ,
. ,
:
220

I. #

class MyClass {
// ,
void nonStaticMeth() {
Console.WriteLine(" nonStaticMeth().");
/*
, . */
public static void staticMeth(MyClass ob) {
ob.nonStaticMeth(); // .

static- ,
, . . static-
.
// static- .
using System;
class Countlnst {
static int count = 0;
// ,
public Countlnst() {
count++;
}
// .
-Countlnst() {
count--;
public static int getcountO {
return count;

class CountDemo {
public static void Main
Countlnst ob;
for(int i=0; i < 10;
ob = new Countlnst();
Console.WriteLine(" :
+ Countlnst.getcount());

:
: 1
: 2
: 3
: 4
: 5

8.

221

:
: 7
: 8
: 9
: 10

, C o u n t l n s t , s t a t i c - count . , C o u n t l n s t , s t a t i c -
count . , count , .
.
,
, .
static- .
, "" .
,
, , .. , . "" , s t a t i c , , .
"" , .
// "" .
using System;
class MyClass {
int a, b;
// "" MyClass.
static public MyClass factory(int i, int j) {
MyClass t = new MyClass();
t.a = i;
t.b = j;
return t; // .
public void show() {
Console.WriteLine(" b: " + a + " " + b ) ;

class MakeObjects {
public static void Main() {
int i, j ;
// "" .
for(i=0, j=10; i < 10; i++, j ) {
MyClass ob = MyClass.factory(i, j ) ; //
// .
ob.show{);

222

I. #

Console.WriteLine();

f a c t o r y ()
:
I MyClass ob = M y C l a s s . f a c t o r y ( i , j ) ; // .
, MyClass
"" .


.
,
, . ,
. .
// .
using System;
class Cons {
public static int alpha;
public int beta;

// ,
static Cons() {
alpha = 99;
Console.WriteLine(" .");
}
// ,
public Cons() {
beta = 100;
Console.WriteLine(" .");

class ConsDemo {
public static void Main() {
Cons ob = new Cons();
Console.WriteLine("Cons.alpha: " + Cons.alpha);
Console.WriteLine("ob.beta: " + ob.beta);

:
.
.
Cons.alpha: 99
o b . b e t a : 100
, ,
. static- . , static-
, .
8.

223

#
. . ,
. , .
, , ,
" + " . , , " + " . - .
. . , " + " , , ( ) .
, . -
, #. ,
, #- . , , . #.


. o p e r a t o r ,
, , .
o p e r a t o r : , . ( ) :
// ,
public s t a t i c _ operator {
_ )
{

//
}

// ,
public static _ operator op{
_1 1,
_2 2)
{
//
}
( " + " " / " ) , .
_ , . ,
, .
. ,
1 2.
,
. , -

9.

225

. , #-
, . , " + " i n t s t r i n g .
: ref
out.


, , , " + " " - " .
ThreeD .
" + "
ThreeD-, " - "
jrhr D- .
// .
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD () { x = = z = 0; }
public ThreeD(int i, int j, int k) {
x = i; = j;

k; }

// "+".
public static ThreeD operator +(ThreeD opl,
ThreeD op2)
ThreeD result = new ThreeD();
/*
.
result.x = opl.x + op2.x;
result. = opl. + 2.;
result.z = opl.z + op2.z;


/
//
// ,

return result;
// "-".
public static ThreeD operator -(ThreeD opl, ThreeD op2)
{
ThreeD result = new ThreeD();
/* .
opl - , 2 - . */
result. = opl.x - 2.; //
result. = opl. - 2.; // ,
result.z = opl.z - op2.z;
return result;
// X, Y, Z.

226

I. #

public void show()


{
Console.WriteLine(x + ", " + + ", " + z) ;

c l a s s ThreeDDemo {
p u b l i c s t a t i c void Main() {
ThreeD a = new ThreeD(1, 2, 3 ) ;
ThreeD b = new ThreeDdO, 10, 10);
ThreeD = new ThreeD();
Console.Write(" : " ) ;
a.show();
Console.WriteLine();
Console.Write(" b: " ) ;
b. show() ;
Console.WriteLine();
= a + b; // b.
Console.Write(" + b:
.show();
Console.WriteLine();

");

c = a + b + c ;
// a, b .
Console.Write(" + b + : " ) ;
.show();
Console.WriteLine();
= - a; // .
Console.Write(" - : " ) ;
.show();
Console.WriteLine();
= - b; // b .
Console.Write(" - :
.show();
Console.WriteLine();

");

:
:

1,

: 10,

2,

10,

10

+ : 1 1 , 12,

13

+ + :

24,

- :

22,

2 1 , 22,

26

23

- : 1 1 , 12, 13
.
" + " . " + " ThreeD , o p e r a t o r s - ( ) . , . 9.

227

ThreeD,
.
" + " , , , 10 12. 10+12 22, 10, 12 .
,
, , .
, o p e r a t o r * () ThreeD.
# ,
, ThreeD,
"+" , ++ , +b, ThreeD, .
( ThreeD),
.
.
o p e r a t o r * () , . " + "
ThreeD " + " , .
o p e r a t o r - ( ) . " - " " + " , . , , (..
, ).
, .
,
, .


, . ,
, , . , , , ""
ThreeD.

// "-".
public static ThreeD operator -(ThreeD op)
ThreeD result = new ThreeD();
result.x = -op.x;
result. = -op.;
result.z = -op.z;
return result;
, ,
"".
o p e r a t o r - ( ) . , . "". ,
= -
, , b .

228

I. #

.
(++) (). (" ")
, , " + " " - " , , . , . , operator++ () ThreeD.
// "++".
public s t a t i c ThreeD operator ++(ThreeD op)
// "++" .
op.x++;
op.y++;
op.z++;
return op;
: ,
, . , ,
"++", . , , "++" .
, ,
, " " "++".
// .
using System;
// ,
class ThreeD {
int , , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j ; z = k; }
// "+".
public static ThreeD operator +(ThreeD opl, ThreeD op2)
ThreeD result = new ThreeD();
/*
. */
result. = opl.x + 2.;
result. = opl. + 2.;
result.z = opl.z + op2.z;
return result;
// "-".
public static ThreeD operator -(ThreeD opl, ThreeD op2)
ThreeD result = new ThreeD();
/* .
9.

229

- opl result.
result.
result.2

, 2 - . */
= opl.x - 2.;
= opl. - 2.;
= opl.z - op2.z;

return result;
// "-".
public static ThreeD operator -(ThreeD op)
{
ThreeD result = new ThreeD();
result.x = -op.x;
result. = -op.;
result.z = -op.z;
return result;
// "++".
public static ThreeD operator ++(ThreeD op)
{
// "++" .
op.x++;
op.y++;
op.z++;
, return op;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z ) ;

class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3 ) ;
ThreeD b = new ThreeDdO, 10, 10);
ThreeD = new ThreeD();
Console.Write(" : " ) ;
a.show();
Console.WriteLine() ;
Console.Write(" b: " ) ;
b.show();
Console.WriteLine();
= a + b; // b.
Console.Write(" + b: " ) ;
.show();
Console.Wri teLine() ;
c = a + b + c;.// a, b .
Console.Write(" + b + : " ) ;

230

I. #

.show();
Console.WriteLine() ;
= - a; // .
Console.Write(" - : " ) ;
.show();
Console.WriteLine();
= - b; // b .
Console.Write(" - : " ) ;
.show();
Console.WriteLine() ;
= -; // - .
Console.Write(" -: " ) ;
.show();
Console.WriteLine();
++; // .
Console.Write(" ++: ") ;
.show();

:
: 1, 2, 3
: 10, 10, 10
+ : 11, 12, 13
+ + : 22, 24, 26
- : 21, 22, 23
- : 11, 12, 13
-: -1, -2, -3

++: 2, 3, 4
, "++" " " , . ,

8
.
" + + " . ,
"++" . " " .

9.

231

i-J
#-

. () . ThreeD. , " + " , ThreeD-
.
ThreeD. , -
ThreeD-. .
" + " , , :
// " + "
// int-.
public s t a t i c ThreeD operator +(ThreeD opl, i n t op2)
ThreeD r e s u l t = new ThreeD();
r e s u l t . x = opl.x + op2;
r e s u l t . = opl. + op2;
r e s u l t . z = opl.z + op2;
return r e s u l t ;
, i n t . ,
int- ThreeD-.
, , , , . .
ThreeD,
operator+().
/* :
+ + int-. */
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) {
x = i; = j; z = k; }
// " + "
// " + ".
public static ThreeD operator +(ThreeD opl, ThreeD op2)
ThreeD result = new ThreeD();
/*
. */
232

I. #

r e s u l t . x = opl.x + op2.x;
r e s u l t . = opl.y + op2.y;
r e s u l t . z = opl.z + op2.z;
return r e s u l t ;
// "+"
// " + int-".
public static ThreeD operator +(ThreeD opl, int op2)
{
ThreeD result = new ThreeD();
result.x = opl.x + op2;
r e s u l t . = opl.y + op2;
r e s u l t . z = opl.z + op2;
return r e s u l t ;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z ) ;

class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3 ) ;
ThreeD b = new ThreeD (10, 10, 10);
ThreeD = new ThreeD();
Console.Write(" : " ) ;
a.show();
Console.WriteLine();
Console.Write(" b: " ) ;
b.show();
Console.WriteLine();
= a + b; // +
Console.Write(" + b: " ) ;
.show();
Console.WriteLine();
= b + 10; // + int-
Console.Write(" b + 10:
.show();

" ) ;

:
: 1, 2, 3
: 10, 10, 10
+ : 11, 12, 13
b + 10: 20, 20, 20

9.

233

, " + "
, .
" + " ,
.
" + " ThreeD, . . o p e r a t o r * (ThreeD, i n t ) , .
I obi = 2 + 10;
, , :
obi = 10 + 2;
, , .
. , " + " . i n t ,
ThreeD. o p e r a t o r + ( )
" + i n t -", " i n t - + ". " + " ( ),
, . ThreeD, " + "
.
/* "+" :
+ ,
+ int-
int- + . */
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) {
x = i; = j; z = k; }
// "+"
// " + ".
public static ThreeD operator +(ThreeD opl, ThreeD op2)
{
ThreeD result = new ThreeD();
/*


. */
result. = opl.x + 2.;
result. = opl. + 2.;
result.z = opl.z + op2.z;
return result;
}
// "+"
// " + int-".

234

I. #

public static ThreeD operator +(ThreeD opl f int op2)


{
ThreeD result = new ThreeD();
result.x = opl.x + op2;
result. = opl.y + op2;
result.z = opl.z + op2;
return result;
// "+"
// "int- + ".
public static ThreeD operator +(int opl, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op2.x + opl;
result. = op2.y + opl;
result.z = op2.z + opl;
return result;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z ) ;

class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
Console.Write(" : " ) ;
a.show();
Console.WriteLine() ;
Console.Write(" b: " ) ;
b.show();
Console.WriteLine();
= a + b; // +
Console.Write(" a + b: " ) ;
c.show();
Console.WriteLine() ;
= b + 10; // + int-
Console.Write(" b + 10: " ) ;
.show();
Console.WriteLine() ;
= 15 + b; // int- +
Console.Write(" 15 + b: " ) ;
.show();

9.

235

:
: 1, 2, 3
: 10, 10, 10
+ : 11, 12, 13
b + 10: 20, 20, 20
15 + : 25, 25, 25

111
(, "==" "<") , . ,
: t r u e f a l s e . . , .
ThreeD, "<" ">".
// "<" ">".
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD () { = = z = 0; }
public ThreeD(int i, int j , int k) {
x = i;

= j ; z = k;

// "<".
public static bool operator <(ThreeD opl, ThreeD op2)
{
if((opl.x < op2.x) && (opl. < op2.y) &&
(opl.z < op2.z))
return true;
else
return false;
}
// ">".
public static bool operator >(ThreeD opl, ThreeD op2)
{
if((opl.x > op2.x) && (opl. > op2.y) &&
(opl.z > op2.z))
return true;
else
return false;
}
// X, Y, Z.
public void show()

236

I. #

Console.WriteLine(x + ", " + + ", " + z ) ;

class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7 ) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(1, 2, 3 ) ;
Console.Write(" : " ) ;
a.show();
Console.Write(" b: " ) ;
b.show();
Console.Write(" : " ) ;
.show();
Console.WriteLine() ;
if(a
if(a
if(a
if(a

>
<
>
<

c)
c)
b)
b)

Console.WriteLine("a >
Console.WriteLine("a <
Console.WriteLine("a >
Console.WriteLine("a <

b
b

- ")
- ")
- ")
- ")

:
: 5, 6, 7
: 10, 10, 10
: 1, 2, 3
> -
< b -
: . , "<", ">", .
:

"==" " ! = " ,


Object.Equals () Object.GetHashCode (). ( )
11.

t r u e f a l s e
t r u e f a l s e .

.
t r u e f a l s e , if, while, for do-while, ?-. (, ).

9.

237

t r u e f a l s e .
. :
p u b l i c s t a t i c bool o p e r a t o r true{_ op)
{

I/ true f a l s e .
}

public s t a t i c bool operator false{_

op)

//

true

false.

, bool.

t r u e f a l s e ThreeD. , ThreeD- , . , .
.
// t r u e f a l s e ThreeD.
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i , i n t j , i n t k) {
x = i;

= j ; z = k; }

// true.
public static bool operator true(ThreeD op) {
if((op.x != 0) M (op. != 0) || (op.z != 0))
return true; // 0.
else
return false;
}
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op. == 0) && (op.z == 0))
return true; // ,
else
return false;
// " .
public static ThreeD operator (ThreeD op)
op.x;
op.y;
op.z;
return op;
// X, Y, Z.

238

I. #

public void show()


{
Console.WriteLine(x + ", " + + ", " + z) ;

class TrueFalseDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7 ) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(0, 0, 0 ) ;
Console.Write(" : " ) ;
a. show() ;
Console.Write(" b: " ) ;
b.show();
Console.Write(" : " ) ;
.show();
Console.WriteLine() ;
if(a) Console.WriteLine("a - .");
else Console.WriteLine("a - .");
if(b) Console.WriteLine("b - .");
else Console.WriteLine("b - .");
if() Console.WriteLine(" - .");
else Console.WriteLine(" - .");
Console.WriteLine();
Console.WriteLine(
" , ThreeD.")
do {
b.show();
b;
} while(b);

:
: 5, 6, 1
: 10, 10, 10
: 0, 0, 0
- ,
b - ,
- .
, ThreeD.
10, 10, 10
9, 9, 9
8, 8, 8
7, 7, 7
6, ,
5, 5, 5
4, 4, 4
3, 3, 3
2, 2, 2

9.

239

, ThreeD if- while-. if-, ThreeD-


t r u e .
. do-while- . ,
b (..
). b ,
() ( t r u e ) , .


, # : &, | , !, &&
| |. , &, | , !.
& & | | , .


. , , & | , bool. ! , , bool.
&, |, !
ThreeD. , , ThreeD-
, . , .
// !, | &
// ThreeD.
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) {
x = i; = j; z = k; }
// "|".
public static bool operator |(ThreeD opl, ThreeD op2)
{
if( ((opl.x != 0) || (opl. != 0) || (opl.z != 0)) |
((op2.x != 0) || (op2.y != 0) || (op2.z != 0)) )
return true;
else
return false;
}
// "&".
public static bool operator &(ThreeD opl, ThreeD op2)

240

I. #

if( ((opl.x != 0) && (opl.y != 0) && (opl.z != 0)) &


((op2.x != 0) && (op2.y != 0) && (op2.z != 0)) )
return true;
else
return false;
// "!".
public static bool operator !(ThreeD op)
{
if((op.x != 0) || (op. != 0) || (op.z != 0))
return false;
else return true;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z ) ;

class TrueFalseDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7 ) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(0, 0, 0 ) ;
Console.Write(" : " ) ;
a.show();
Console.Write(" b: " ) ;
b.show();
Console.Write(" : " ) ;
.show();
Console.WriteLine();
if(!a) Console.WriteLine("a - .");
if(!b) Console.WriteLine("b - .");
if(!c) Console.WriteLine(" - .");
Console.WriteLine();
if (a & b) Console.WriteLine("a & b - .");
else Console.WriteLine("a & b - .");
if(a & c) Console.WriteLine("a & - .");
else Console.WriteLine("a & - .");
if(a | b) Console.WriteLine("a | b - .");
else Console.WriteLine("a | b - .");
if(a | c) Console.WriteLine("a | - .");
else Console.WriteLine("a | ~ .");

:
: 5, , 7
: 10, 10, 10

9.

'

241

: , ,
- .

& b - ,
& - ,
| b - ,
| - .
o p e r a t o r | ( ) , o p e r a t o r &() o p e r a t o r ! () bool. , "" (.. , bool). ,
bool. ,
,
bool. , ,
, .

& & | | , , . -,
& | . -, &- |- , . -, , . -,
t r u e f a l s e .
.
, & |
ThreeD, && | | , .
/* !, | &
ThreeD.
&& ||. */
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
xv

// |"
// .
public static ThreeD operator |(ThreeD opl, ThreeD op2)
{
if( ((opl.x != 0) || (opl. != 0) || (opl.z != 0)) |
( ( o p 2 . x ! = 0) | |
( o p 2 . y ! = 0)
r e t u r n new T h r e e D ( 1 , 1, 1 ) ;
else
r e t u r n new T h r e e D ( 0 , 0, 0 ) ;

242

||

(op2.z

!= 0))

I. #

// " & "


// .
public static ThreeD operator &(ThreeD opl, ThreeD op2)
{
if( ((opl.x != 0) && (opl. != 0) && (opl.z != 0)) &
( ( o p 2 . x ! = 0) && ( o p 2 . y ! = 0)
r e t u r n new T h r e e D ( 1 , 1, 1 ) ;
else
r e t u r n new T h r e e D ( 0 , 0, 0 ) ;

&& ( o p 2 . z

0))

// "!".
public static bool operator !(ThreeD op)
{
if(op) return false;
else return true;
// true.
public static bool operator true(ThreeD op) {
if((op.x != 0) || (op. != 0) || (op.z != 0))
return true; //
// ,
else
return false;
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op. == 0) && (op.z == 0))
return true; // ,
else
return false;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z)

class TrueFalseDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7 ) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(0, 0, 0) ;
Console.Write(" : " ) ;
a.show();
Console.Write(" b: " ) ;
b.show();
Console.Write(" : " ) ;
.show();
Console.WriteLine();

9.

243

if(a) Console.WriteLine("a - .");


if(b) Console.WriteLine("b - .");
if() Console.WriteLine(" - .");
if(!a) Console.WriteLine("a - .");
if(!b) Console.WriteLine("b - .");
if(!c) Console.WriteLine(" - .");
Console.WriteLine();
Console.WriteLine(" & | " ) ;
if(a & b) Console.WriteLine("a & b - .");
else Console.WriteLine("a & b - .");
if(a & c) Console.WriteLine("a & - .");
else Console.WriteLine("a & - .");
if(a | b) Console.WriteLine("a | b - .");
else Console.WriteLine("a | b - .");
if(a | c) Console.WriteLine("a | - .");
else Console.WriteLine("a | - .");
Console.WriteLine();
// && ||,
/ / .
Console.WriteLine(
" "" && | | " ) ;
if(a && b) Console.WriteLine("a && b - .");
else Console.WriteLine("a && b - .");
if(a && ) Console.WriteLine("a && - .");
else Console.WriteLine("a && - .");
if(a || b) Console.WriteLine("a M b - .");
else Console.WriteLine("a || b - .");
if(a || c) Console.WriteLine("a II - .");
else Console.WriteLine("a II - .");

:
: 5, , 7
: 10, 10, 10
: 0, 0, 0
- ,
b - .
- .
& |
& b - ,
& - ,
| b - ,
| - .

244

I. #

"" && ||
&& b - ,
&& - .
|| - ,
' | 1 - .
& |. .

// "|"
// .
public static ThreeD operator |(ThreeD opl, ThreeD op2)
{
if( ((opl.x != 0) || (opl. != 0) || (opl.z != 0)) |
((op2.x != 0) || (op2.y != 0) || (op2.z != 0)) )
return new ThreeD(1, 1, 1 ) ;
else
return new ThreeD(0, 0, 0 ) ;
}
// " & "
// .
public static ThreeD operator &(ThreeD opl, ThreeD op2)
{
if( ((opl.x != 0) && (opl. != 0) && (opl.z != 0)) &
( ( o p 2 . x ! = 0) && ( o p 2 . y ! = 0)
r e t u r n new T h r e e D ( 1 , 1 , 1 ) ;
else
r e t u r n new T h r e e D ( 0 , 0 , 0) ;

&& ( o p 2 . z

!= 0))

,
ThreeD, , .
, ThreeD (.. , ). , ThreeD- (.. , ). ,
I i f ( & b) Console.WriteLine("a & b - .");
I e l s e Console.WriteLine("a & b - .");
& b ThreeD-, . ThreeD t r u e f a l s e ,
t r u e ,
bool. t r u e ,
" & b - . ".
,
ThreeD . .
o p e r a t o r t r u e ( " | | " )
o p e r a t o r f a l s e ( "&&"). , &- |- . "&" " | " . , &&- | | -
&- | - ,
. , , :
9.

245

if(a |J ) Console.WriteLine("a II - .");


t r u e .
, | - .
-:
I i f ( | | a) C o n s o l e . W r i t e L i n e ( " II - .");
t r u e , . | -, ,
, .
, , , , .
t r u e f a l s e , . , . ,
"&" " | ",
.


,
. . ( ). # o p e r a t o r , .
. , . #- ,
" ".
: . :
p u b l i c s t a t i c e x p l i c i t o p e r a t o r _ (
__ v) [ r e t u r n ; ]
public s t a t i c implicit operator _ (
_ v) [return ;]
_ , ; _ ,
; v .
_,
.
i m p l i c i t , , .. ,
_.
e x p l i c i t , . , ,
e x p l i c i t - , implicit- .
ThreeD. ,

246

I. #

ThreeD ,
i n t . .
implicit- , :
public static implicit operator int(ThreeD opl)
return opl.x * opl. * opl.z;
,
.
// implicit- .
using System;
// ,
class ThreeD {
int x, , z; // 3-- .
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j , int k) {
x = i ; = j ; z = k;

// "+".
public static ThreeD operator +(ThreeD opl, ThreeD op2)
ThreeD result = new ThreeD();
result.x = opl.x + op2.x;
result. = opl. + op2.y;
result.z = opl.z + op2.z;
return result;
// ThreeD int.
public static implicit operator int(ThreeD opl)
return opl.x * opl. * opl.z;
// X, Y, Z.
public void show()
Console.WriteLine(x + ", " + + ", " + z ) ;

c l a s s ThreeDDemo {
p u b l i c s t a t i c v o i d Main() {,
ThreeD a = new T h r e e D ( 1 , 2, 3 ) ;
ThreeD b = new ThreeD(10, 10, 1 0 ) ;
ThreeD = new T h r e e D ( ) ;
int i;
C o n s o l e . W r i t e ( " :
a.show();
9.

");

247

Console.WriteLine();
Console.Write(" b: " ) ;
b.show();
Console.WriteLine() ;
= a + b; // b.
Console.Write(" + b: " ) ;
c.show();
Console.WriteLine() ;
i = a; // int.
Console.WriteLine(
" i = a: " + i) ;
Console.WriteLine();
i = a * 2 - b ; // int.
Console.WriteLine(
" * 2 - b: " + i)

: 1, 2, 3
: 10, 10, 10
+ : 1 1 , 12, 13
i = :
* 2 - : -988
,
ThreeD ( i = ),
.
6, ,
. int-,
. =
+ b o p e r a t o r i n t () .
, . ,
- double- long-.
.
, , ,
, . , . .
, , ,
i n t :
// .
using System;
// .

248

I. #

class ThreeD {
int x, y, z; // 3-- .
public ThreeD() { x = = z = 0; }
public ThreeD(int i, int j, int k) {
x = i; = j; z = k; }
// "+".
public static ThreeD operator +(ThreeD opl, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = opl.x + op2.x;
result. = opl. + op2.y;
result.z = opl.z + op2.z;
return result;
/ / explicit-,
public static explicit operator int(ThreeD opl)
{
return opl.x * opl. * opl.z;
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + + ", " + z) ;

class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3 ) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
int i;
Console.Write(" : " ) ;
a.show();
Console.WriteLine();
Console.Write(" b: " ) ;
b.show();
Console.WriteLine() ;
= a + b; // b.
Console.Write(" + b: " ) ;
c. show() ;
Console.WriteLine();
i = (int) a; //
// int,
// .
Console.WriteLine(" i = : " + i ) ;
Console.WriteLine();
/
i = (int)a * 2 - (int)b; // .

9.

249

Console.WriteLine(
" * 2 - b :

ff

+ i);

e x p l i c i t , i n t . ,
I i = ( i n t ) a;
, .
.

. ,
double i n t .
Object .
,
.
. (
. 11.)
. ( . 12.)
,
.

, . ,
. -,
, , .
-, . ,
.



, ,
#-.

. ,
" + " , ThreeD,
" + " , . , , " + " , (/). , ( ) ,
.

250

I. #

.
. , ,
. . , ( , "+="). , .
&&
| |
[]
()
new
is
sizeof
typeof
?
->
=
(())
, , , ,
.
, "+=". , , . , "+="
operator+ (). ,
ThreeD.
ThreeD a = new ThreeD(l, 2, 3 ) ;
ThreeD b = new ThreeD(10, 10, 10);
b += a; // b .

o p e r a t o r + ( ) ThreeD, b 11,12,13.
. ( [ ] ) , ( o p e r a t o r ()),
, .


ThreeD. , . , , , .

, . , ,
, . . , nybble. ,
1 nybble, . ,
. nybble- .
Nybble, . i n t ,
015.
:

Nybble- Nybble-;

9.

251

int- Nybble-;

Nybble- int-;

(>) (<);

int- Nybble-;

Nybble- int-.

, ,
#.
Nybble, . .
Nybble, NybbleDemo, .
// 4- Nybble.
using System;
// 4- .
class Nybble {
int val; // - int.
public Nybble() { val = 0 ; }
public Nybble(int i) {
va1 = i;
val = val & OxF; // 4 .
}
// " + "
// Nybble + Nybble.
public static Nybble operator +(Nybble opl, Nybble op2)
{
Nybble result = new Nybble();
result.val = opl.val + op2.val;
result.val = result.val & OxF; //
// 4 .
return result;
}
// "+"
// Nybble + int.
public static Nybble operator +(Nybble opl, int op2)
{
Nybble result = new Nybble();
result.val = opl.val + op2;
result.val = result.val & OxF; //
// 4 .
return result;

252

I. #

// "+"
// int + Nybble.
public static Nybble operator +(int opl, Nybble op2)
{
Nybble result = new Nybble();
result.val = opl + op2.val;
result.val = result.val & OxF; //
// 4 .
return result;
// "++".
public static Nybble operator ++(Nybble op)
{
op.val++;
op.val = op.val & OxF; //
// 4 ,
return op;
// ">".
public static bool operator >(Nybble opl, Nybble op2)
{
if(opl.val > op2.val) return true;
else return false;
// "<".
public static bool operator <(Nybble opl, Nybble op2)
{
if(opl.val < op2.val) return true;
else return false;
// Nybble- int.
public static implicit operator int (Nybble op)
{
return op.val;
// int- Nybble-.
public static implicit operator Nybble (int op)
{
return new Nybble(op);

class NybbleDemo {
public static void Main() {
Nybble a = new Nybble(1);
Nybble b = new Nybble(10);
Nybble = new Nybble();
int t;
Console.WriteLine("a: " + (int) a ) ;

9.

253

Console.WriteLine("b: " + (int) b ) ;


// Nybble- if-,
if(a < b) Console.WriteLine(" b\n");
// Nybble-.
= a + b;
Console.WriteLine(
" = a + b: " + (int) c ) ;
// int- Nybble-.
a += 5;
Console.WriteLine(" += 5: " + (int) a ) ;
Console.WriteLine();
// Nybble- int-,
t = a * 2 + 3;
Console.WriteLine(
" * 2 + 3: " + t) ;
Console.WriteLine();
// Nybble-
// int- .
= 19;
Console.WriteLine(
" = 19: " + (int) a ) ;
Console.WriteLine();
// Nybble- .
Console.WriteLine(
" for- Nybble-.");
for( = 0; < 10; ++)
Console.Write((int) a + " " ) ;
Console.WriteLine();

:
: 1
: 10
b
= + : 11
+= 5:
* 2 + 3: 15
= 19: 3
for- Nybble-.
0 1 2 3 4 5 6 7 8 9

, .
Nybble 254

I. #

#. Nybble-
int-, int- Nybble-, Nybble-
. , ,
:
J t = * 2 + 3;
t i n t ,
Nybble.
Nybble- int-. , i n t ,
int- .
int- Nybble- Nybble int-. ,
|
= 19;
. i n t Nybble-. Nybble-, () 19 (1910 = 100112).
, 19 ,
Nybble. 3 (00112 = 310),
. .
Nybble- int- for.
for
.

9.

255

, : . , #
. ,
, .
. ,
#: , .

,
" [ ] " . , ""
o p e r a t o r (), (indexer).
.
,
. ,
.
, .


.
_ this[int ] {
// ,
get {
// ,
// .
// ,
set {
// ,
// .

,
_ , . .
( ) . ,
i n t ,
,
.
( ) get
s e t . ,
. , . ,
s e t , .
get , 10.

257

. s e t ( value),
, .
,
, "" . . F a i l S o f t A r r a y ,
"" , . .

, " ", " ". F a i l S o f t A r r a y , ([ ]).
//
// .
using System;

class FailSoftArray {
int[]

a;

// .

public int Length; // Length - .


public bool errflag; //
// .
// ,
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}
// - FailSoftArray.
public int this[int index] {
// - get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;

// - set-.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;

//

258

true,

I. #

// - ,
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;

// ,
class FSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
int x;
// " " .
Console.WriteLine(" . ") ;
for(int i=0; i < (fs.Length * 2) ;
fs[i] = i*10;
for(int i=0; i < (fs.Length * 2 ) ;
x = fs[i];
if(x != -1) Console.Write(x + " ") ;
}
Console.WriteLine();
// .
Console.WriteLine(
" .");
for(int i=0; i < (fs.Length * 2 ) ; i++) {
fs[i] * i*10;
if(fs.errflag)
Console.WriteLine("fs[" + i + "] ");
for(int i=0; i < (fs.Length * 2 ) ;
x = fs[i] ;
if(!fs.errflag) Console.Write(x + " " ) ;
else
Console.WriteLine("fs[" + i + "] ");

:
" ".
10 20 30 40
.
fs[5]
fs[6]
fs[7]
fs[8]
fs[9]
0 10 20 30 40 fs[5]
fs[6]
fs[7]
fs[8]
fs[9]

10.

259

. . :
I public i n t t h i s [ i n t index] {
, i n t .
index. .
get.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;

get .
, get ,
. ,
, .
FailSoftArray e r r f l a g
. , ,
.
s e t ().
.
set

if(ok(index)) {
a[index] = value;
errflag = false;
else errflag = true;
, ,
value, .
e r r f l a g t r u e . ,
value , , . (
) .
get-, set. , , get-. ,
, set-.


.
FailSoftArray, double.
double- .
, ,

, .

260

I. #

// FailSoftArray.
using System;
class FailSoftArray {
int[] a;

// .

public int Length; // Length () - .


public bool errflag; //
// .
// ,
public FailSoftArray(int size) {
a = new int[size];
Length = size;
// int- FailSoftArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;

// set-.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;

/* FailSoftArray.
double-.

. */
public int this[double idx] {
// get-.
get {
int index;
// int-.
if( (idx - (int) idx) < 0.5) index = (int) idx;
else index = (int) idx + 1;
if(ok(index) ) {
errflag = false;
return a[index];
} else {

10.

'

261

errflag = truerreturn 0;

// set-.
set {
i n t index;
// int-.
if( (idx - (int) idx) < 0.5) index (int) idx;
else index = (int) idx + 1;
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;

// t r u e , ,
p r i v a t e bool o k ( i n t index) {
i f ( i n d e x >= 0 & index < Length) r e t u r n t r u e ;
return false;

// ,
c l a s s FSDemo {
p u b l i c s t a t i c void Main() {
FailSoftArray fs = new FailSoftArray(5);
// fs ,
f o r ( i n t i=0; i < fs.Length; i++)
fs[i] = i;
//
// i n t - double-.
Console.WriteLine("fs[l]: " + f s [ l ] ) ;
Console.WriteLine("fs[2]: " + f s [ 2 ] ) ;
Console.WriteLine("fs[l.1]:
Console.WriteLine("fs[1.6]:

" + fs[l.l]);
" + fs[1.6]);

:
fs[l]: 1
fs[2]: 2
fs[l.l]: 1
fs [1.6] : 2
, double- . , 1.1 1,
1. 6 2.

262

I. #

, ,
, . ,
,
.


. , , ,
, . , , , .
"" 2 0 15. . ( )
.
//
// .
using System;
c l a s s PwrOfTwo {
/*

,
2 0 15. */
public i n t t h i s [ i n t index] {
// 2.
get {
i f ( ( i n d e x >= 0) && (index < 16)) return pwr(index);
e l s e return - 1 ;
}

//

set-.

int pwr(int p) {
int result = 1;
for(int i=0; i<p; i
result *= 2;
return result;

class UsePwrOfTwo {
public static void Main() {
PwrOfTwo pwr = new PwrOfTwo();
Console.Write(" 8 2: " ) ;
for(int i=0; i < 8; i++)
Console.Write(pwr[i] + " " ) ;
Console.WriteLine() ;
Console.Write(" : " ) ;
Console.Write(pwr[-1] + " " + pwr[17]);
Console.WriteLine() ;

10.

263

:
8 2: 1 2 4 8 16 32 64 128
: -1 -1

, UsePwrOfTwo get, set-. ,


. , UsePwrOfTwo
, . , , :
I pwr[0] = 11; / /
, set-.
. -, ,
ref- out-. -,
, s t a t i c .


. ,
.
.
// .
using System;
class FailSoftArray2D {
int[,] a; // .
int rows, cols; //
public int Length; // Length - .
public bool errflag; //
// .
// ,
public FailSoftArray2D(int , int ) {
rows = ;
cols = ;
= new int[rows, cols];
Length = rows * cols;
}

// FailSoftArray2D.
public int this[int indexl, int index2] {
// -- get-.
get {
if(ok(indexl, index2)) {
errflag = false;
return a[indexl, index2];
} else {
errflag = true;
return 0;

264

I. #

// set-.
set {
if(ok(indexl, index2)) {
a[indexl, index2] = value;
errflag = false;
}
else errflag = true;

// true,
// ,
private bool ok(int indexl, int index2) {
if(indexl >= 0 & indexl < rows &
index2 >= 0 & index2 < cols)
return true;
return false;

// ,
class TwoDIndexerDemo {
public static void Main() {
FailSoftArray2D fs = new FailSoftArray2D(3, 5 ) ;
int x;
// " " .
Console.WriteLine(" .");
for(int i=0; i < 6; i
fs[i, i] = i*10;
for(int i=0; i < 6; i
x = fs[i, i] ;
if(x != -1) Console.Write(x + " ") ;
}
Console.WriteLine();
/ / .
Console.WriteLine(
" .");
for(int i=0; i < ; i++) {
fs [i,i] = i*10;
if(fs.errflag)
Console.WriteLine(
"fs[" + i + ", " + i + "] ");
for(int i=0; i < 6;
x = f s [i, i] ;
if(!fs.errflag) Console.Write(x + " " ) ;
else
Console.WriteLine(
"fs[" + i + ", " + i + "] ");

10.

265

, :
.
10 20
.
fs[3, 3]
fs[4, 4]
fs[5, 5]
0 10 20 fs[3, 3]
fs[4, 4]
fs[5, 5]

,
. .
, ,
,
. , , .
,
.
.
(get s e t ) . . ,

,
get- set-. .
:

get{

//
}
set{
//
}
(, i n t ) , . . s e t value,
, .
, . ,
, .
.
, myprop, prop. .

// ,
using System;

266

I. #

class SimpProp {
int prop; // myprop.
public SimpProp() { prop = 0 ; }
/*
prop.
. */
public int myprop {
get {
return prop;
}
set {
if(value >= 0) prop = value;

// ,
class PropertyDemo {
public static void Main() {
SimpProp ob = new SimpProp ();
Console.WriteLine(" ob.myprop: " +
ob.myprop);
ob.myprop = 100; // .
Console.WriteLine(" ob.myprop: " + ob.myprop);
// prop
// .
Console.WriteLine(
" -10 ob.myprop");
ob.myprop = -10;
Console.WriteLine(" ob.myprop: " + ob.myprop);

:
ob.myprop:
ob.myprop: 100
-10 ob.myprop
ob.myprop: 100
. SimpProp prop myprop, prop.
, ,
.
. , prop ,
myprop.
myprop public- ,
, .
, prop
: get- prop, a set- prop, . ,

10.

267

myprop , prop.
.
,
, .
, ( g e t ) ( set-).
,
. ,
Length. FailSof t A r r a y
Length.
, Length ,
. (, -
.) , Length , , FailSof tArray.
// FailSoftArray Length.
using System;
class FailSoftArray {
int[] a; // .
int len; // , Length.
public bool errflag;

//
// .

// ,
public FailSoftArray(int size) {
a = new i n t [ s i z e ] ;
len = size;
}

// Length ,
public int Length {
get {
return len;

// -- FailSoftArray.
public int this[int index] {
// -- get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;

// -- set-.
set {
if(ok(index)) {
a[index] = value;

268

'

I. #

errflag = false;
}
else errflag = true;

// true, ,
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;

// ,
class IinprovedFSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
int x;
// Length ,
for(int i=0; i < fs.Length; i++)
fs[i] = i*10;
for(int i=0; i < fs.Length; i++) {
x = fs[i];
if(x != -1) Console.Write(x + " " ) ;
}
Console.WriteLine();
// fs.Length = 1 0 ; // , !

Length , len. get-,


Length , . , :
I // f s . L e n g t h = 1 0 ; // , !
, , Length
.
F a i l S o f t A r r a y Length ,
. e r r f l a g ""
,
" ".
F a i l S o f t A r r a y , Error,
e r r f l a g .
// e r r f l a g .
using System;
class FailSoftArray {
int[] a; // ,
int len; // .

10.

269

bool errflag; // .
// ,
public FailSoftArray(int size) {
a = new int[size];
len = size;
// Length ,
public int Length {
get {
return len;

// Error ,
public bool Error {
get {
return errflag;

// - FailSoftArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = falserreturn a[index];
} else {
errflag = true;
return 0;

// set-.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;

// true, ,
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;

// ,
class FinalFSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// Error.

270

I. #

for(int i=0; i < fs.Length + 1;


fs[i] = i*10;
if(fs.Error)
Console.WriteLine(" " + i ) ;

E r r o r FailSoftArray . -, e r r f l a g ,
E r r o r . e r r f l a g . -,
E r r o r , . e r r f l a g , E r r o r . Main (),
, E r r o r .


. , ,
ref- out-. -, .
( , ,
.) ,
get-,
. , get- .



, . RangeArray, , .
, # .
,
,
- 5 5. RangeArray .
RangeArray :
RangeArray = new RangeArray(-5, 1 0 ) ; //
// -5 10.
for(int i = -5; i <= 10; i++) ra[i] = i ; / /
// -5 10.

, RangeArray (
), - 5 10 . , .

10.

271

RangeArray RangeArrayDemo,
. RangeArray int-, .
/*
. RangeArray
, .
RangeArray
.
. ,

-5 5, 1 10 50 56.
*/
using System;
class RangeArray {
// .
int[] ; // ,
int lowerBound; // ,
int upperBound; // .
// .
int len; // Length.
bool errflag; // Error.
// ,
public RangeArray(int low, int high) {
high++;
if(high <= low) {
Console.WriteLine(" .");
high = 1 ; //
// ,
low = 0;
}
= new int[high - low];
len = high - low;
lowerBound = low;
upperBound = high;
}
// Length, ,
public int Length {
get {
return len;

// Error, ,
public bool Error {
get {
return errflag;

// RangeArray.
public int this[int index] {

272

I. #

// get-.
get {
if(ok(index)) {
errflag = false;
return a[index - lowerBound];
} else {
errflag = true;
return 0;

// set-.
set {
if(ok(index) ) {
a[index - lowerBound] = value;
errflag = false;
else errflag = true;

// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return true;
return false;

//
// ,
class RangeArrayDeitio {
public static void Main() {
RangeArray ra = new RangeArray(-5, 5 ) ;
RangeArray ra2 = new RangeArray(1, 10);
RangeArray ra3 = new RangeArray(-20, -12);
// .
Console.WriteLine(" :

+ ra.Length);

for(int i = -5; i <= 5;


ra[i] = i;
Console.Write(" :
for(int i = -5; i <= 5; i++)
Console.Write(ra[i] + " " ) ;
Console.WriteLine("\n") ;
// 2.
Console.WriteLine(" 2:

+ ra2.Length)

for(int i = 1; i <= 10;


ra2[i] = i;
Console.Write(" 2: " ) ;
for(int i = 1; i <= 10;

10.

273

Console.Write(ra2[i] + " " ) ;


Console. WriteLine (lf \n") ;
//
Console.WriteLine(" : " + .Length);
for(int i = -20; i <= -12; i++)
ra3[i] = i;
Console.Write(" : ") ;
for(int i = -20; i <= -12; i++)
Console.Write([i] + " " ) ;
Console.WriteLine("\n") ;

:
: 11
; - 5 - 4 - 3 - 2 - 1 0 1 2 3 4 5
2: 10
2 : 1 2 3 4 5 6 7 8 9

10

: 9
: -20 -19 -18 -17 -16 -15 -14 - 1 3 -12
,
RangeArray . ,
RangeArray.
:
// .
int[] a; // ,
int lowerBound; // ,
int upperBound; // .
// .
int len; // Length.
bool errflag; // Error.
.
RangeArray. lowerBound,

upperBound. , Length Error.


RangeArray :
// ,
public RangeArray(int low, int high) {
high++;
if(high <= low) {
Console.WriteLine(" .");
high = 1; //
// ,
low = 0;

274

I. #

= new int[high - low];


len = high - low;
lowerBound = low;
upperBound = h i g h ;
RangeArray low high.
high , , low high . , . , . ( , ),
. l e n (
Length) . ,
lowerBound upperBound.
RangeArray Length Error. .
// Length, ,
p u b l i c i n t Length {
get {
return len;

// Error, ,
public bool Error {
get {
return errflag;

, FailSoftArray,
.
RangeArray . :
// RangeArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = false;
return a[index - lowerBound];
} else {
errflag = true;
return 0;

// set-.
set {
if(ok(index)) {
a[index - lowerBound] = value;
errflag = false;
else errflag = true;

10.

'

275

FailSoftArray,
. , .
I index - lowerBound
, index,
"", .. , ,
. . lowerBound: , .
ok ().
// t r u e ,
// ,
p r i v a t e bool o k ( i n t index) {
i f ( i n d e x >= lowerBound & index <= upperBound)
return true;
return false;
, FailSoftArray
, lowerBound upperBound.
RangeArray , " " . ( ),
. .

276

I. #

- , . ,
, , . ,
, .
# , , . , , . ,
. ,
, , , , , .


# ,
. . . TwoDShape, "" (,
^, , ..).
// ,
class TwoDShape {
public double width;
public double height;
public void showDimO {
Console.WriteLine(" " +
width + " " + height);

TwoDShape (..
) , . , TwoDShape
T r i a n g l e . , T r i a n g l e .
// .
using System;
// ,
class TwoDShape {
public double width;
public double height;
public void showDimO {
Console.WriteLine(" " +
width + " " + height);

// Triangle TwoDShape.
class Triangle : TwoDShape {
public string style; // .

278

I. #

// ,
public double area() {
return width * height / 2;
// ,
public void showStyleO {
Console.WriteLine(" " + style);

c l a s s Shapes {
p u b l i c s t a t i c void MainO {
T r i a n g l e t l = new T r i a n g l e ( ) ;
T r i a n g l e t 2 = new T r i a n g l e ( ) ;
t l . w i d t h = 4.0;
t l . h e i g h t - 4.0;
t l . s t y l e = "";
t 2 . w i d t h = 8.0;
t 2 . h e i g h t 12.0;
t 2 . s t y l e = "";
Console.WriteLine("
tl: ");
tl.showStyle();
tl.showDim();
Console.WriteLine (" " + tl.areaO);
Console.WriteLine();
Console.WriteLine(" t2: " ) ;
t2. showStyleO ;
t2.showDim();
Console.WriteLine(" " + t2.area());

.
tl:

4 4
8
t2:

8 12
4 8
T r i a n g l e TwoDShape,
. T r i a n g l e
TwoDShape , , s t y l e , area showStyleO. s t y l e , a r e a () , showstyle () .
, Triangle,
TwoDShape.

class Triangle : TwoDShape {

11.

279

. , , . #
.
T r i a n g l e , TwoDShape,
width h e i g h t ( ) . ,
MainO t l t 2 width
h e i g h t , T r i a n g l e .
TwoDShape T r i a n g l e . 11.1.

width
TwoDShape

height
showDim()
style

Triangle

area
showStyle()
. 11.1.
Triangle

TwoDShape T r i a n g l e ,
. , (),
. , :
TwoDShape shape = new TwoDShape();
shape.width = 10;
shape.height = 20;
shape.showDim ();
, TwoDShape " "
, TwoDShape.
, , :

class ___ : __ {
//
.
# ( C++) .
++- #. ,
.
, ( , ) .
, , , ,
. "" . , , TwoDShape
, :

280

I. #

// Rectangle,
/ / TwoDShape.
class Rectangle : TwoDShape {
// true,
// ,
public bool isSquareO {
if(width == height) return true;
return false;
// ,
public double area() {
return width * height;

Rectangle TwoDShape i s S q u a r e O , , , a r e a , .


8, ,
. , . , , ,
, . ,
, width h e i g h t p r i v a t e TwoDShape, T r i a n g l e .
// .
// .
using System;
// ,
class TwoDShape {
double width; // private-.
double height; // private-.
public void showDim() {
Console.WriteLine(" " +
width + " " + h e i g h t ) ;

// Triangle TwoDShape.
class Triangle : TwoDShape {
public string style; // .
// ,
public double area() {
return width * height / 2; // ,
//
// .

11.

'

281

// ,
public void showStyle() {
Console.WriteLine(" " + style);

T r i a n g l e , width h e i g h t
a r e a () . width
h e i g h t , .
.
.
, ,
.

, .
, # .
protected-, .
,
. , #
.
TwoDShape, width h e i g h t .
//
// .
using System;
// ,
class TwoDShape {
double pri_width; // private-.
double pri_height; // private-.
// width height,
public double width {
get { return pri_width; }
set { pri_width = value; }
public double height {
get { return pri__height; }
set { pri_height = value; }
}
public void showDimO {
Console.WriteLine(" " +
width + " " + height);

// - TwoDShape.
class Triangle : TwoDShape {
public string style; // .
// ,
public double area() {
return width * height / 2;

282

I. #

// ,
public void showStyleO {
Console.WriteLine(" " + style);

c l a s s Shapes2 {
p u b l i c s t a t i c void MainO {
T r i a n g l e t l = new T r i a n g l e ( ) ;
T r i a n g l e t 2 = new T r i a n g l e ( ) ;
t l . w i d t h = 4.0;
t l . h e i g h t = 4.0;
t l . s t y l e = "";
t 2 . w i d t h = 8.0;
t 2 . h e i g h t - 12.0;
t 2 . s t y l e = "";
Console.WriteLine(" t l : " ) ;
tl.showStyle();
tl.showDim();
Console.WriteLine (" " + tl.areaO);
Console.WriteLine();
Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
Console.WriteLine(" " + t2.area());

.
Java. Java #. Java #. , , #. C++ " / ".


, . , , ,
, .
, ,
. , , # . ,
, .
p r o t e c t e d .
protected- , . , .
, , . ,
p r o t e c t e d , ( " 11.

283

") ,
.
.
// .
using System;
class {
protected int i, j ; // ,
/ / D.
public void set(int a, int b) {
i = a;
j = b;
}
public void show() {
ConsoleWriteLine(i + " " + j) ;

class D : {
int k; // .
// D i j .
public void setk() {
k = i

* j ;

p u b l i c void showk() {
Console.WriteLine(k) ;

c l a s s ProtectedDemo {
p u b l i c s t a t i c void Main()
D ob = new D();
ob.set(2, 3);
ob.show();
ob.setk();
ob.showk();

/ / OK, D "" - i j .
/ / OK, D "" - i j .

/ / OK, D.
/ / OK, D.

D i j
(.. p r o t e c t e d ) ,
s e t k ( ) . i j
, D , .
p u b l i c p r i v a t e p r o t e c t e d
. ,
, , .
284

I. #


, . :
?
, ? : , , , .
, " "
. . , #, .
, ,
.
,
: . , ,
. , T r i a n g l e , . s t y l e private-, jcy .
// Triangle.
using System;
// ,
class TwoDShape {
double pri_width;
// .
double pri_height; // .

// width height,
public double width {
get { return pri_width; }
set { pri_width = value; }
}

public double height {


get { return pri_height; }
set { pri_height = value; }
}

public void showDim() {


Console.WriteLine(" " +
width + " " + height);

// - TwoDShape.
class Triangle : TwoDShape {
string s t y l e ; // .
// .
public Triangle(string s, double w, double h) {
width = w; // .
height = h; // .

11.

285

style - s;

// .

// ,
public double area() {
return width * height / 2;
// ,
public void showStyleO {
Console.WriteLine(" " + style);

class Shapes3 {
public static void Main() {
Triangle tl = new Triangle("",
4.0, 4.0);
Triangle t2 - new Triangle("",
8.0,
12.0);
Console.WriteLine(" tl: " ) ;
tl.showStyle();
tl.showDim();
Console.WriteLine (" " + tj..area());
Console.WriteLine();
Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
Console.WriteLine(" " + t2.area());

T r i a n g l e
TwoDShape, s t y l e .
, , , .
# base, : , "" . base.


,
,
base. :

__ (
_) : base (_) {
//
}

_ ,
.

286

I. #

, base,
TwoDShape. , width height.
// TwoDShape.
using System;
// ,
class TwoDShape {
double pri_width; // .
double pri_height; // .
// TwoDShape.
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// width height,
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri__height; }
set { pri_height = value; }
}

p u b l i c void showDimO {
Console.WriteLine(" " +
width + " " + h e i g h t ) ;

// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// ,
public Triangle(string s,
double w,
double h) : base(w, h) {
style = s;
// ,
public double area() {
return width * height / 2;
// ,
public void showStyleO {
Console.WriteLine(" " + style)

11.

287

class Shapes4 {
public static void Main() {
Triangle tl = new Triangle("", 4.0, 4.0);
Triangle t2 = new Triangle("", 8.0, 12.0);
Console.WriteLine(" tl: " ) ;
tl.showStyle();
tl.showDim();
Console .WriteLine (" " + tl.areaO);
Console.WriteLine();
Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
Console.WriteLine("

" + t2.area());

T r i a n g l e () "" base () w h,
TwoDShape (), width h e i g h t w h, . T r i a n g l e
.
, , s t y l e ( ). TwoDShape
. , TwoDShape
,
"", .
base , . , . ,
TwoDShape T r i a n g l e ,
, :
// TwoDShape .
using System;
class TwoDShape {
double pri_width; // .
double pri_height; // .

// ,
public TwoDShape() {
width = height = 0.0;
}
// TwoDShape ,
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// , ,
public TwoDShape(double x) {
width = height = x;

288

I. #

// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public void showDimO {
Console.WriteLine(" " +
'width + " " + height);

// , TwoDShape.
class Triangle : TwoDShape {
string style; // . Q
/* .
TwoDShape. */
public Triangle() {
style = "null";
// , ,
public Triangle(string s, double w, double h) : base(w, h) {
style = s;
// ,
public Triangle(double x) : base(x) {
style = "";
// ,
public double area() {
return width * height / 2;
// ,
public void showStyleO {
Console.WriteLine(" " + style);

class Shapes5 {
public static
Triangle tl
Triangle t2
Triangle t3

void Main() {
= new Triangle();
= new Triangle("", 8.0, 12.0);
= new Triangle(4.0);

tl = t2;
Console.WriteLine(" tl: " ) ;
tl.showStyleO ;

11.

289

tl.showDimO ;
Console.WriteLine (" " + tl.areaO);
Console.WriteLine() ;
Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
Console.WriteLine(" " + t2.area());
Console.WriteLine() ;
Console.WriteLine(" t3: " ) ;
t3.showStyle();
t3.showDim();
Console.WriteLine(" " + t3.area());
Console.WriteLine() ;

:
tl:

8 12
4 8
t2:

8 12
4 8

t3:

4 4
8
base-.
-"" .
, base ,
.
. ,
"" base (). base , .


,
. . #
, ""
. . , 290

I. #

new. ,
new
.
.
// .
using System;
class A {
p u b l i c i n t i = 0;
}

// ,
class : {
new i n t i ; // i i .
public (int b) {
i = b; // i .
public void show() {
Console.WriteLine(
" i : " + i ) ;

class NameHiding {
public s t a t i c void Main() {
ob = new (2);
ob.show();

-, new i . , , ,
i, i . new, .
:
/
I i : 2

i, i, . ,
show() , i, , .

base

base,
t h i s , , base , .
:
base.
11.

291

,
. base ,
. :
// base .
using System;
class A {
public i n t i = 0;
}

// ,
class : {
new int i ; // i i .
public (int a, int b) {
base.i = ; // i .
i = b; // i .
}

public void show() {


// i .
Console.WriteLine("i : " + base.i);
// i .
Console.WriteLine("i : " + i ) ;

class UncoverName {
public static void Main() {
ob = new (1 f 2 ) ;
ob.show();

:
i : 1
i : 2

i i
, base i .
base .
.
// .
using System;
class A {
public int i = 0;
// show() .
public void show() {
'
Console.WriteLine("i : " + i ) ;

292

I. #

// ,
class : {
new int i; // i
// .
public (int a, int b) {
base.i - ; //
// i .
i = b; // i .
}
// show ,
// .
// new.
new public void show() {
base.show(); // show() .
// i .
Console,WfiteLine ("i |& : " + i) '*

c l a s s UncoverNaine {
public static void Main()
ob = new (1, 2 ) ;
ob.show();

:
i : 1
i : 2

, base.show()
show (), .
, new , show (), show (), .


,
. , . , . , (, ) , ,
, .
. .
, , . Triangle
ColorTriangle.
11.

293

C o l o r T r i a n g l e T r i a n g l e TwoDShape c o l o r , .
// .
using System;
class TwoDShape {
double pri__width; // ,
double pri__height; // .
// ,
public TwoDShape() {
width = height =- 0.0;
}
// TwoDShape.
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// , ,
// ,
public TwoDShape(double x) {
width = height = x;
}
// width height,
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri__height; }
set { pri_height = value; }
}
public void showDimO {
Console.WriteLine(" " +
width + " " + height);

// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
/* .
TwoDShape. */
public Triangle () {
style = "null";
// .
public Triangle(string s, double w, double h) : base(w, h) {
style = s;

254

I. #

// ,
public Triangle(double x) : base(x) {
style = "";
// ,
public double area() {
return width * height / 2;
// ,
public void showStyleO {
Console.WriteLine(" " + style);

// ,
class ColorTriangle : Triangle {
string color;
public ColorTriangle(
string c, string s,
double w, double h) : base(s, w, h) {
color = c;
// ,
public void showColor() {
Console.WriteLine(" " + color);

class Shapes6 {
public static void Main() {
ColorTriangle tl =
new ColorTriangle("", "",
8.0, 12.0);
ColorTriangle t2 =
new ColorTriangle("", "",
2.0, 2.0);
Console.WriteLine(" tl: " ) ;
tl.showStyle() ;
tl.showDim();
tl.showColor();
Console .WriteLine (" " + tl.areaO);
Console.WriteLine ();
Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
t2.showColor();
Console.WriteLine(" " + t2.area());

11,

295

.
tl:

8 12

48
t2:

2 2

2
C o l o r T r i a n g l e T r i a n g l e TwoDShape, , () .
: .
: base
"" . , C o l o r T r i a n g l e base , T r i a n g l e . T r i a n g l e
base , TwoDShape. ,
, , .


:

? , ,
, ? .
, .. .
, , base.
base ,
(.. ) . ) :
// .
ifeing System;
// ,
class A {
public A() {
Console.WriteLine(" . " ) ;

// , .
class : {
public B() {
Console.WriteLine(" . " ) ;

296

I. #

// , .
class : {
public C() {
Console.WriteLine(" . " ) ;

class!OrderOfConstruction {
public static void Main()
= new ();

, :
.
.
.
, .
. " " ,
, ,
. , () () , . -
.



, # .
, , . ,
"" "" .
, , :

// .
class X {
int a;

public X(int i)

{ = i; }

class Y {
int a;
public Y(int i)

v
{ a = i; }

class IncompatibleRef {
public s t a t i c void Main() {
X x = new X(10);
X x2;
11.

297

Y = new Y{5) ;
x2 = x; // OK, .
2 = ; // , .

X Y
, Y ,
.
.
#-
.
^ , . .
//
// .
using System;
class X {
public int a;
public X(int i) {
a = i;

class Y : X {
public int b;
public Y(int i, int j) : base(j) {
b - i;

class BaseRef {
public static void Main() {
X x = new X(10);
X x2;
Y = new Y(5, 6) ;
x2 = x; // OK, .
Console.WriteLine("x2.a: " + 2.);
2 = ; // ok, Y
// X.
Console.WriteLine("2.: " + 2.);

//

// - "" X.
2. = 19; //
2. = 27; // , X .

Y X, 2
Y.

298

I. #

, ( , ) , . , , ,
. 2 b Y
, Y. , " " , . .
"",
. , .
, . , , . . , ,
. , ,
TwoDShape T r i a n g l e . ,
.
//
// .
u s i n g System;
c l a s s TwoDShape {
double p r i _ w i d t h ;
double p r i _ h e i g h t ;

// ,
// .

// ,
p u b l i c TwoDShape() {
width = h e i g h t = 0.0;
}

// TwoDShape.
p u b l i c TwoDShape(double w, double h) {
width = w;
h e i g h t = h;
}

// , ,
p u b l i c TwoDShape(double x) {
width = h e i g h t = x;
}

// ,
p u b l i c TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
}
// width height,
public double width {
get { return pri_width; }
set { pri__width = value; }

11.

299

public double height {


get { return pri_height; }
set { prijheight = value; }
public void showDimO {
Console.WriteLine(" " +
width + " " + height);

// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// ,
public Triangle() {
style = "null";
// Triangle,
public Triangle(string s,
double w,
double h) : base(w, h) {
style ~ s;
// ,
public Triangle(double x) : base(x) {
style = "";
// ,
public Triangle(Triangle ob) : base(ob) {
style ob.style;
// ,
public double area() {
return width * height / 2;
// ,
public void showStyle() {
Console.WriteLine(" " + style);

class Shapes7 {
public static void Main() {
Triangle tl = new Triangle("", 8.0, 12.0);
// tl.
Triangle t2 = new Triangle(tl);
Console.WriteLine(" tl: " ) ;
tl.showStyleO ;
tl.showDimO ;

500

I. #

Console. WriteLine( " " + tl. area O b Console .WriteLine();


Console.WriteLine(" t2: " ) ;
t2.showStyle();
t2.showDim();
Console.WriteLine(" " + t2.area());
t 2 t l .
JBOT :
tl:

8 12
48
t2:

8 12
4 8
T r i a n g l e :
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}

T r i a n g l e
jviexaHH3Ma) TwoDShape:
// .
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;

base-

, TwoDShape ()
TwoDShape. T r i a n g l e () T r i a n g l e . , " " ,
. , TwoDShape ()
, TwoDShape. TwoDShape () ,
TwoDShape, , ,
.


,
v i r t u a l
. , . : ,
. , #
11.

301

, , , . , , . , , ( ) , . ,
,
(
) .
,
v i r t u a l .
o v e r r i d e . , (method overriding).
- . , ( s t a t i c ) ( a b s t r a c t , ).
#: . , . # .
, .
// .
using System;

class Base {
// ,
public virtual void who () {
Console.WriteLine(" who() Base.");

class Derivedl : Base {


// who() ,
public override void who() {
Console.WriteLine(" who() Derivedl")

class Derived2 : Base {


// who()
// ,
public override void who() {
Console.WriteLine(" who() Derived2

class OverrideDemo {
public static void Main() {
Base baseOb = new Base();
Derivedl dObl = new Derivedl()
Derived2 dOb2 = new Derived2()

302

I. #

Base baseRef; // .
baseRef = baseOb;
baseRef.who();
baseRef = dObl;
baseRef.who() ;

baseRef = dOb2;
baseRef.who() ;


who()
who()
who()

:
Base.
Derivedl
Derived2

Base Derivedl
Derived2. Base who (),
. Main() Base, Derivedl
Derived2, baseRef Base. baseRef who (). ,
, ,
"" baseRef.
.
, , . :
/*
,
. /
using System;
class Base {
// ,
public virtual void who() {
Console.WriteLine(" who() Base");

class Derivedl : Base {


// who() ,
public override void who() {
Console.WriteLine(" who() Derivedl");

class Derived2 : Base {


// who().
}
class NoOverrideDemo {
public static void Main() {
Base baseOb = new Base();
Derivedl dObl = new Derivedl();
11.

303

Derived2 dOb2 = new Derived2();


Base baseRef; // .
baseRef = baseOb;
baseRef.who();

baseRef = dObl;
baseRef.who();
baseRef = dOb2;
baseRef.who(); // who() Base.


who()
who()
who()

:
Base
Derivedl
Base

Derived2 who ().


who () Derived2 who (), Base.
, ,
.
.
/*
,
,

. */
using System;
class Base {
// ,
public virtual void who() {
Console.WriteLine(" who() Base");

class Derivedl : Base {


// who() ,
public override void who() {
Console.WriteLine(" who() Derivedl");

class Derived2 : Derivedl {


// who().
}
class Derived3 : Derived2 {
// who().
}
class No0verrideDemo2 {

304

I. #

public static void Main{) {


Derived3 dOb = new Derived3();
Base baseRef; // .
baseRef = dOb;
baseRef.who(); // who()
// Derivedl.

:
I who() Derivedl
Derived3 Derived2,
Derivedl, Base. , who ()
Derived3, Derived2, Derivedl,
who () ( Derivedl) ,
.
. v i r t u a l , o v e r r i d e .


# . - ,
,
, $ .
# , " ".
(, "")
, , . "
", .. . , , . , -
. , () ,
, .


,
TwoDShape. ,
TwoDShape, a r e a (). ,
( )
TwoDShape,
, , . . TwoDShape name, .
11.

305

// ,
using System;
class TwoDShape {
double pri_width; // ,
double pri_height; // ,
string pri_name;
// .
// ,
public TwoDShape() {
width = height = 0.0;
name = "null";

// .
public TwoDShape(double w, double h, string n)
width = w;
height = h;
name = n;
// , ,
public TwoDShape(double x, string n) {
width = height = x;
name = n;
// ,
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
// width, height name.
public double width {
get { return pri_width; }
set { pri_width = value; }
}

public double height {


get { return pri_height; }
set { pri_height = value; }
}
public string name {
get { return pri__name; }
set { pri__name = value; }
}
public void showDim() {
\
Console.WriteLine(" " +
width + " " + height);
}
public virtual double area() {
Console.WriteLine(

306

I. #

return

" a r e a ( ) . " ) ;
0.0;

// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// ,
public Triangle() {
style = "null";
}
// .
public Triangle(string s, double w, double h) :
base(w, h, "") {
style = s;
}
// .
public Triangle(double x) : base(x, "") {'
style - "";
}
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}
// () Triangle,
public override double area() {
return width * height / 2 ;
}
// ,
public void showStyle() {
Console.WriteLine(" " + style);
}
}
// , TwoDShape.
class Rectangle : TwoDShape {
// .
public Rectangle(double w, double h) :
base(w, h, ""){ }
// ,
public Rectangle(double x) :
base(x, "") { }
// .
public Rectangle(Rectangle ob) : base(ob) { }
// true, - ,
public bool isSquare() {
if(width height) return true;
return false;

11.

307

// () Rectangle,
public override double area() {
return width * height;

c l a s s DynShapes {
p u b l i c s t a t i c void Main() {
TwoDShape[] shapes = new TwoDShape[5];
shapes[0]
shapes[1]
shapes[2]
shapes[3]
shapes[4]

=
=
=
=
=

new
new
new
new
new

Triangle("", 8.0, 12.0)


Rectangle(10);
Rectangle(10, 4 ) ;
Triangle(7.0);
TwoDShape(10, 20,
" ");

f o r ( i n t i = 0 ; i < shapes.Length; i++) {


Console.WriteLine(" " +
shapes[i].name);
Console.WriteLine(" " +
shapes[i].area() ) ;
Console.WriteLine();

% :

48

100

4 0

24.5

area() .
0
. -, ()
TwoDShape v i r t u a l
T r i a n g l e Rectangle. TwoDShape ()
"", ,
.
a r e a () , , . ,
, area () .
.
, ( ) shapes
308

I. #

TwoDShape.
T r i a n g l e , Rectangle TwoDShape. ,
.
shapes, . , , . , , ,
, .. ,
. TwoDShape, a r e a ().
, .


, "
", , "" . "" ,
,
. ,
.
TwoDShape ( ),
() "", , , .
, , , () ,
- . .
, , . (, ),
. .
,
. T r i a n g l e . ,
a r e a (). , .
# .
a b s t r a c t . , , . , , . , ,
v i r t u a l . , v i r t u a l a b s t r a c t .
.

abstract (_) ;
, . a b s t r a c t
, static-.
.
, ,
a b s t r a c t ,
c l a s s . 11.

309

, , . , new
.
, .
. , a b s t r a c t , .
,
TwoDShape.
,
a r e a () TwoDShape , , ,
TwoDShape. , , , TwoDShape,
a r e a ().
// .
using System;
abstract
double
double
string

class TwoDShape {
pri_width; // ,
pri_height; // ,
pri_name;
// .

// ,
public TwoDShape() {
width = height = 0.0;
name = "null";
}
// .
public TwoDShape(double w, double h, string n) {
width = w;
height = h;
name = n;
}
// , ,
public TwoDShape(double x, string n) {
width = height = x;
name = n;
// ,
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
// width, height name,
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
310

I. #

public string name {


get { return pri__name; }
set { pri_name = value; }
}
public void showDim() {
Console.WriteLine(" " +
width + " " + height);
}
// () ,
public abstract double area();
}
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// ,
public Triangle() {
style = "null";
}
// .
public Triangle(string s, double w, double h) :
base(w, h, "triangle") {
style = s;
}
// .
public Triangle(double x) : base(x, "") {
style = "";
}
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}

// () Triangle,
public override double area() {
return width * height / 2 ;
}
// ,
public void showStyle() {
Console.WriteLine(" " + style);
}
}
// , TwoDShape.
class Rectangle : TwoDShape {
// .
public Rectangle(double w f double h) :
base(w, h, ""){ }
// .

11.

311

public Rectangle (ckmfcrle x) :


base(xf "") { }
// .
public Rectangle(Rectangle ob) : base(ob) { }
// true,
// ,
public bool isSquareO {
if (width ===== height) return true;
return false;
// () Rectangle,
public override double area() {
return width * height;

class AbsShape {
public static void Main() {
TwoDShape [] shapes == new TwoDShape[4];
shapes[0]
shapes[1]
shapes[2]
shapes[3]

=
=
=
=

new
new
new
new

Triangle("", 8.0, 12.0);


Rectangle(10);
Rectangle(10, 4 ) ;
Triangle (7.0);

for(int i=0; i < shapes.Length; i++) {


Console.WriteLine(" " +
shapes[i].name);
Console.WriteLine(" " +
shapes[i 3.area());
Console.WriteLine();

,
a r e a ( ) , . , ,
a r e a (). (.. ) .
, TwoDShape,
. TwoDShape.
Main () shapes 4, "
" TwoDShape.
, TwoDShape - showDimO, a b s t r a c t . ( ) , " ".
, a b s t r a c t , .

312

I. #

sealed

, . , ,
, . ,
. # s e a l e d .
, s e a l e d . , a b s t r a c t s e a l e d ,
""
"", .. .
sealed-.
sealed class A {

// .
class : { // ! .

,
sealed-.

o b j e c t
# o b j e c t ,
( ). , object. , object . ,
#- , object
. , #- o b j e c t
System.Object, .NET Framework.
o b j e c t , . 11.1. .
11.1. object

public virtual
public

static

bool Equals (
object

ob)

bool Equals (
o b j e c t obi,
o b j e c t ob2)

11.

, , , ob
, , 2

313

. 11.1

p r o t e c t e d F i n a l i z e ()

. # F i n a l i z e ()

p u b l i c v i r t u a l i n t GetHashCode ()

-,

p u b l i c Type GetTypeO

p r o t e c t e d obj e c t
MemberwiseClone ()
public s t a t i c bool
ReferenceEquals (object obi,
object ob2)
public v i r t u a l s t r i n g T o S t r i n g o

" " , .. , ,
, 2


. E q u a l s ( o b j e c t ) , , , , ..
, .
t r u e , , f a l s e . . , . , E q u a l s ( o b j e c t ) ,
( ,
). E q u a l s ( o b j e c t , o b j e c t )
Equals(object).
GetHashCode () -, .
- , , .
9, "==" Equals ( o b j e c t ) GetHashCode (),
"==" Equals ( o b j e c t ) , , . Equals ( o b j e c t ) , GetHashCode ( ) , .
.
T o S t r i n g O , , . , T o S t r i n g O W r i t e L i n e ( ) . T o S t r i n g O , , . :
// T o S t r i n g O .
u s i n g System;
/
class MyClass {
static int count = 0 ;
int id;
public MyClass {
id = count;
count++;
}
public override string ToStringO {
return " MyClass #" + id;
314

I. #

class Test {
public static void Main() {
MyClass obi = new MyClassO;
MyClass ob2 = new MyClassO;
MyClass ob3 = new MyClassO;
Console.WriteLine(obi);
Console.WriteLine(ob2);
Console.WriteLine(ob3);

:
MyClass #0
MyClass #1
MyClass #2


, #-, , o b j e c t . , o b j e c t , . o b j e c t ,
(boxing).
, . ,
"" . ""
,
. o b j e c t . #.
" " (unboxing)
.
, .. o b j e c t .
, .
// "" "".
using System;
class BoxingDemo {
public s t a t i c void Main() {
int x;
object obj;
x = 10;
obj = x; // "" .
int

= (int)obj; // ""
// obj int-.
Console.WriteLine();

11.

315

10. ,

obj, o b j e c t . , o b j ,
i n t .
( )
. int- s q r ( ) , o b j e c t .
//
// .
using System;
class BoxingDemo {
public static void Main() {
int x;
x - 10;
Console.WriteLine(" : " + x ) ;
// ^^^
/ / sqr().
= BoxingDemo.sqr(x);
Console.WriteLine(" x : " + ) ;
}
static int sqr(object ) {
return (int) * (int);

:
: 10
: 100

s q r () .
#- . o b j e c t .
o b j e c t .

, . , o b j e c t , . ,
, , .
// ""
//

o b j e c t !

using System;
class MethOnValue {
public s t a t i c void Main() {
Console.WriteLine(lO.ToString());
}

316

I. #

10. , T o S t r i n g O , . 10 10!

object

, o b j e c t #-

, o b j e c t . , ,
jcnacca o b j e c t , .
// o b j e c t
// .
using System;
class GenericDemo {
public s t a t i c void Main() {
object[] ga = new object[10];

// int-.
f o r ( i n t i=0; l < 3; i++)
ga[ij = i ;
// double-.
f o r ( i n t i=3; i < 6; i++)
ga[i] = (double) i / 2;
// , bool- char-,
[] = " ";
[7] = t r u e ;
[8] = f X'; '
[9] = "";
f o r ( i n t i = 0; i < .Length;
Console.WriteLine("[" + i + " ] : " + ga[i] + " " ) ;

[0]:
1 1 1

L-L J
2
. .
[23: 1.5
[3]:
[4]: 2
[5] : 2 . 5
[]:
[7]: True
[8]: X
[9]:
,
o b j e c t . -

11.

317

, o b j e c t .
, object- .
, , o b j e c t . .
, object, , , o b j e c t
#- . ,
int- int-, s t r i n g string- .. o b j e c t
.

318

I. #

1 #: .
^ ^ , .
. , , , .
#: .
, ,
, . .
, #.

- ,
, .
. ,
. , , -. , , .
, . #

i n t e r f a c e .
.
, .. . , ,
, . , . .
( )
, . . , , . , , "" ,
, . , , # ,
" ".
i n t e r f a c e . :
i n t e r f a c e {
_ _1 {_) ;
_ _2 {_) ;
// . . .
_ _(_) ;
}

.
. , , . , . , , , .
(public-),
.
320

I. #

, .
public interface ISeries {
int getNext(); // ,
void reset (); // ,
void setStart(int x) ; //
// .
I S e r i e s . " I " ,
, .
I S e r i e s ,
.
, . 15, , . . , .
, .


, , . , , . , , :
c l a s s _ : __ {
//
, _.
, , .. .
. .
.
.
, , .
, ,
. ,
, .
I S e r i e s , . ByTwos, , .
// ISeries,
class ByTwos : ISeries {
int s t a r t ;
int val;
public ByTwos() {
start = 0;
val = 0;
public i n t getNext() {
12. ,

321

val += 2;
return val;
public void reset() {
val = start;
public void setStart(int x) {
start = x;
val = start;

, ByTwos ,
I S e r i e s . , .
, ByTwos. :
// ,
// ByTwos.
using System;
class SeriesDemo {
public static void Main() {
ByTwos ob = new ByTwos() ;
f o r ( i n t i=0; i < 5;
Console.WriteLine(" " +
ob.getNext());
Console.WriteLine(" .")
ob.reset ( ) ;
f o r ( i n t i=0; i < 5; i++)
Console.WriteLine(" " +
ob.getNext());
Console.WriteLine(" 100.");
o b . s e t S t a r t (100);
f o r ( i n t i=0; i < 5; i++)
Console.WriteLine(" " +"
ob.getNext());

SeriesDemo,
, I S e r i e s , ByTwos SeriesDemo.

. , , I S e r i e s , cs, ByTwos. cs
SeriesDemo.es, :
I >csc SeriesDemo.cs I S e r i e s . c s ByTwos.cs
(IDE) Visual Studio,
#-. .

322

I. #

:
2
4

8
10

.
2
4

8
10

100.




102
104
106
108
110

, ,
. , ByTwos
getPrevious (), .
// ISeries
// getPrevious().
class ByTwos : ISeries {
int start;
int val;
int prev;
public ByTwos() {
start = 0;
val = 0;
prev = -2;
}
public int getNextO {
prev = val;
val += 2;
return val;
}
public void reset() {
val = start;
prev = start - 2;
}
public void setStart(int x) {
start = x;
val = start;
prev = val - 2;
}
// , ISeries,
public int getPrevious() {
return prev;

12. ,

323

, g e t P r e v i o u s ()
, I S e r i e s .
, , . .
, .
, , Primes, . , I S e r i e s ByTwos.
// I S e r i e s
// .
class Primes : ISeries {
int start;
int val;
public Primes () {
start = 2;
val = 2;
}

public int getNext() {


int i, j;
bool isprime;
for(i = val; i < 1000000;
isprime = true;
for(j = 2; j < (i/j + 1)
if((i%j)==0) {
isprime = false;
break;
if(isprime) {
val = i;
break;
return val;
public void reset() {
val = start;
public void setStart(int x) {
start = x;
val = start;

, , Primes ByTwos
, I S e r i e s .
, , ""
.

324

I. #


, , ,
. , . ,
.
, .
(. 11).
.
-,
ByTwos, Primes.
// .
using System;
// ,
public interface ISeries {
int getNextO; // .
void reset(); // .
void setStart(int x ) ; //
// .
}
// ISeries
// ,
class ByTwos : ISeries {
int start;
int val;
public ByTwos() {
start = 0;
val = 0;
}
public int getNext() {
val += 2;
return val;
}
public void reset() {
val = start;
}
public void setStart(int x) {
start = x;
val = start;

-^

// ISeries
// ,
class Primes : ISeries {
int start;
int val;

12. ,

325

public Primes () {
start = 2;
val = 2;
public int getNext()
int i, j;
bool isprime;
for(i val; i < 1000000;
isprime = true;
for(j = 2; j < (i/j + 1 ) ;
if((i%j)==0) {
isprime = falserbreak;
if(isprime) {
val = i;
break;
return val;
public void reset() {
val = start;
public void setStart(int x) {
start = x;
val = start;

class SeriesDemo2 {
public static void Main() {
ByTwos twoOb = new ByTwos();
Primes primeOb = new Primes(
ISeries ob;
for(int i=0; i < 5;
ob = twoOb;
Console.WriteLine(
" " +
ob.getNext ());
ob = primeOb;
Console.WriteLine(
" " +
ob.getNext() ) ;

:
2
3
4
5

326

I. #


7
8
11
10
13

Main() ob I S e r i e s .
, , I S e r i e s . twoOb primeOb, ByTwos Primes,
, , I S e r i e s .
, ""
, " " i n t e r f a c e . , , , .


, . .
//
{
get;
set;
, ,
get- set-, .
ISeries ByTwos,
.
// .
using System;
public interface ISeries {
// ,
int next {
get; // .
s e t ; // .

// ISeries,
class ByTwos : ISeries {
m t val;
public ByTwos() {
val = 0;
}
// ,
public int next {
get {
12. ,

327

val += 2;
return val;
}
set {
val = value;

// ,
class SeriesDemo3 {
public s t a t i c void Main() {
ByTwos ob = new ByTwos();
// .
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);
Console.WriteLine(" 21");
ob.next = 2 1 ;
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);
:
2
4

8
10
21




23
25
27
29
31

So
. :

//

_ t h i s [ i n t ]{
get;
set;
}

, , get- set-, .
ISeries, , .
328

I. #

// ,
using System;
public interface ISeries {
// ,
int next {
get; // .
set; // .
// ,
int this[int index] {
get; // .

// ISeries,
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
//
// ,
public int next {
get {
val += 2;
return val;
}
set {
val = value;

// ,
public int this[int index] {
get {
val = 0;
for(int i=0; i<index;
val += 2;
return val;

// ,
class SeriesDemo4 {
public static void Main() {
ByTwos ob = new ByTwos();
// ,
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);

12. ,

329

Console.WriteLine(" 21");
ob.next = 2 1 ;
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);
Console.WriteLine(" .");
ob.next = 0;
// .
for(int i=0; i < 5; i++)
Console.WriteLine(" " +

, :
2
4

8
10
21





23
25
27
29
31

.
0
2
4

8


"" . , .
, , , . :
// .
using System;
public interface A {
void methl () ;
void meth2();
}

// methl()
/ / m e t h 3 ( ) .
330

meth2(),

I. #

public interface : A {
void meth3();
//
// .
class MyClass : {
public void methl() {
Console. WriteLine (" methl(). ff );
public void meth2() {
Console.WriteLine(" meth2().");
public void xneth3() {
Console.WriteLine(" meth3().");

class IFExtend {
public static void Main() { y
MyClass ob = new MyClass();
ob.methl();
ob.meth2();
ob.meth3();

methl (), MyClass,


. , , ,
, , ,
.

, , . .
, new.


. , , . ,

12. ,

331

interface IMyiF {
int myMeth(int x ) ;
IMyiF :
c l a s s MyClass : IMyIF{
i n t IMyIF.myMeth(int x) {
r e t u r n x / 3;

, myMethO IMyiF , .
. , ,
, "" , . -, ,
.
. .


lEven,
isEven () i s Odd (), ,
. MyClass lEven, isOdd()
.
// .
using System;
interface IEven {
bool isOdd(int x ) ;
bool isEven(int x) ;
}
class MyClass : IEven {
// ,
bool IEven.isOdd(int x) {
if((x%2) != 0) return true;
else return false;
}
// ,
public bool isEven(int x) {
IEven = this; // .
return !o.isOdd(x);

c l a s s Demo {
p u b l i c s t a t i c void Main() {
MyClass ob = new MyClass();
bool r e s u l t ;
result = ob.isEven(4);
i f ( r e s u l t ) Console.WriteLine("4
332

- . " ) ;
I. #

else Console.WriteLine("3
//

- .");

r e s u l t = ob.isOdd(); // , .

isOddO ,
MyClass. .
MyClass isOddO .
isEven ( ) .


, , meth (). ,
.
// ,
// .
using System;
interface IMyIF_A {
int meth(int x);
}

interface IMyIF_B {
int meth(int x ) ;
)
// MyClass ,
class MyClass : IMyIF_A, IMyIF_B {
// meth().
int IMyIF_A.meth(int x) {
return x + x;
}
int IMyIF_B.meth(int x) {
return x * x;
}
// meth() ,
public int methA(int x){
IMyIF_A a_ob;
a_ob = this;
return a_ob.meth(x); //
// IMyIF_A.
}
public int methB(int x){
IMyIF_B b_ob;
i
b_ob = t h i s ;
return b_ob.meth(x); //
// IMyIF_B

12. ,

333

c l a s s FQIFNames {
p u b l i c s t a t i c void Main() {
MyClass ob = new MyClass();
Console.Write(" IMyIF_A.meth(): " ) ;
Console.WriteLine(ob.methA(3));
Console.Write (" IMyIF_B.meth(): " ) ;
Console.WriteLine(ob.methB(3));

:
IMyIF__A.meth () :
IMylFjB.meth(): 9

, meth () lMylF_A lMylF_B. , MyClass , ,


( ).
, m e t h ( ) , iMyIF__A, iMylF_A, meth(), iMylFjB,
lMyiF_B.
, .

# ,
, , , . .
, , . ,
( ) .

.NET
Framework
.NET Framework , . , System. IComparable
CompareTo (), . ,
(, ). , ,
S y s t e m . C o l l e c t i o n s . I C o l l e c t i o n ,
. System. C o l l e c t i o n s . IEnumerator
. II.

334

I. #

:
#,
. i c i p h e r , .
, "" , , "".

I Cipher :
// ,
public interface ICipher {
s t r i n g encode(string s t r ) ;
s t r i n g decode(string s t r ) ;
}

ICipher : encode () decode ( ) ,


, .
. , ,
, . ,
, . . , ( ). ,
.
, .
I C i p h e r :

SimpleCipher BitCipher. SimpleCipher

"" . , , ..
B i t C i p h e r -: , 16 , .

/* ICipher,

1 . ,
.. */
class SimpleCipher : ICipher {
// ,
// ,
public s t r i n g encode(string s t r ) {
string ciphertext = " " ;
for(int i=0; i < str.Length;
ciphertext = ciphertext + (char) (str[i] + 1 ) ;
return ciphertext;
}
// ,
// .
\
public string decode(string str) {
'
string plaintext = "";

12. ,

335

for(int i=0; i < str.Length; ^.. ,


plaintext = plaintext + (char) (str[i] - 1) ;
return plaintext;

/* ICipher
. */
class BitCipher : ICipher {
ushort key;
//
// BitCipher.
public BitCipher(ushort k) {
key = k;
// ,
// ,
public string encode(string str) {
string ciphertext = "";
for(int i=0; i < str.Length;
ciphertext = ciphertext + (char) (str[i]

key);

return ciphertext;
// ,
// ,
public string decode(string str) {
string plaintext = "";
for(int i=0; i < str.Length;
plaintext = plaintext + (char) (str[i]

key);

return plaintext;

, SimpleCipher BitCipher ICipher, .


SimpleCipher
BitCipher.
// ICipher.
using System;
class ICipherDemo {
public static void Main() {
ICipher ciphRef;
BitCipher bit = new BitCipher(27);
SimpleCipher sc = new SimpleCipher();
string plain;
string coded;

336

I. #

// ciphRef
// SimpleCipher ( ).
ciphRef = sc;
Console.WriteLine(" .");
plain = "testing";
coded = ciphRef.encode(plain);
Console.WriteLine(" : " + coded);
plain = ciphRef.decode(coded);
Console.WriteLine(" : " + plain);
// ciphRef refer
// BitCipher ( ).
ciphRef = bit;
Console.WriteLine(
" .11);
plain = "testing";
coded = ciphRef.encode(plain);
Console.WriteLine(" : " + coded);
plain = ciphRef.decode(coded);
Console.WriteLine(" : " + plain);

:
.
: uftujoh
: testing
.
: o~horu|
: testing
,
, , , , . , , UnlistedPhone .
.
// ICipher.
using System;
// ,
class UnlistedPhone {
string pri_name;
// Name.
string pri_number; // Number.
ICipher crypt; // .
public UnlistedPhone(string name, string number,
ICipher c)

12. ,

337

crypt = ; // .
pri__name = crypt. encode (name) ;
pri_number = crypt.encode(number);
public string Name {
get {
return crypt.decode(pri_name);
}
set {
pri__name = crypt.encode(value);

public string Number {


get {
return crypt.decode(pri_number);
}
set {
pri_number = crypt. encode (value) ;

// UnlistedPhone.
class UnlistedDemo {
public static void Main() {
UnlistedPhone phonel =
new UnlistedPhone("TOM", "555-3456",
new BitCipher(27));
UnlistedPhone phone2 =
new UnlistedPhone("", "555-8891",
new BitCipher(9));
Console.WriteLine(" "
+ phonel.Name + " : "
+ phonel.Number);
Console.WriteLine(" "
+ phone2.Name + " : "
+ phone2.Number);

:
: 555-3456
: 555-8891

, UnlistedPhone. ,
.
.
I Cipher. UnlistedPhone
. , , , . crypt.
, , , -

338

I. #

i c i p h e r . BitCipher. ,
UnlistedPhone e n c o d e d decode ()
B i t C i p h e r crypt.
Name Number.
set-
encode () , c r y p t .
get- decode (). Name, Number
.
.

i c i p h e r , ,
UnlistedPhone. ,
UnlistedPhone SimpleCipher-, BitCipher-.
, UnlistedPhone.
// SimpleCipher.
using System;
class UnlistedDemo {
public static void Main() {
// BitCipher
// SimpleCipher.
UnlistedPhone phonel =
new UnlistedPhone("Tom", "555-3456",
new SimpleCipher());
UnlistedPhone phone2 =
new UnlistedPhone("Mary", "555-8891",
new SimpleCipher());
Console.WriteLine(
" " +
phonel.Name + " : " +
phonel.Number);
Console.WriteLine(
" " +
phone2.Name + " : " +
phone2.Number);

, i c i p h e r SimpleCipher BitCipher, UnlistedPhone


.
. UnlistedPhone , , .
i c i p h e r , ,
i c i p h e r .
,
UnlistedPhone. UnlistedPhone c r y p t
12. ,

339

(, BitCipher), UnlistedPhone
.

, . ,
. , # .
, .
. ,
, . . # . , , .
s t r u c t . :
struct : {
//
.
.
. (,
#-, o b j e c t ) .
. . , , , , , . , . ( ). ,
, .
, a b s t r a c t , v i r t u a l p r o t e c t e d .
new, , . new, , , ,
. ,
.
// .
using System;
// ,
struct Book {
public string author;
public string title;
public int copyright;
public Book(string a, string t, int c) {
author = a;
title = t;
copyright = c;
340

I. #

// Book,
class StructDemo {
public static void Main() {
Book bookl = new Book("Herb Schildt",
"C# A Beginner's Guide",
2001); //
// .
Book book2 = new Book(); //
// .
Book ; //
// .
Console.WriteLine(bookl.title + ", " +
bookl.author +
11
, () " + bookl. copyright );
Console.WriteLine();
if(book2.title == null)
Console.WriteLine(" book2.title null.");
// book2 .
book2.title = "Brave New World";
book2.author = "Aldous Huxley";
book2.copyright = 1932;
Console.Write(" book2 :\n
" ) ;
Console.WriteLine(book2.title + ", " +
book2.author +
", (c) " + book2.copyright);
Console.WriteLine();
// Console.WriteLine(.title); // :
//
// .
.title = "Red Storm Rising";
Console.WriteLine(.title); // Ok!

:
# A Beginner's Guide, Herb Schildt, () 2001
book2.title null.
book2 :
Brave New World, Aldous Huxley, () 1932
Red Storm Rising
, new, , . new
, ( ), , . new ,

12. ,

341

, ,
.
.
struct- lass-. ,
, ,
, . struct- , ,
. , ,
:
// .
using System;
// ,
struct MyStruct {
public int x;
}
// ,
class StructAssignment {
public static void Main() {
MyStruct a;
MyStruct b;
a.x = 10;
b.x = 20;
Console .WriteLine ("a.x {0}, b.x {I}11, a.x, b.x);
a - b;
b.x = 30;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);

.
.
a.x

1 0 , b . x 20
2 0 , b . x 30

,
= ;
b - . , , , . b ,
-. class- .
// .
u s i n g System;
// ,
class MyClass {
public int x;
}

//

342

I. #

class ClassAssignment {
public static void Main() {
MyClass a = new MyClassO;
MyClass b = new MyClassO;
a.x = 10;
b.x = 20;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);

:
a.x
a.x

1 0 , b . x 20
3 0 , b . x 30

, b , .. , .


, # s t r u c t , ,
, "" c l a s s .
. ,
, . , s t r u c t
. ,
. ,
, ,
. ,
. . . ,
, ,
s t r u c t .
, ,
. . .
.
, .
.
// .
using System;
// ,
struct PacketHeader {
public uint packNum;
// .
public ushort packLen; // .
}

12. ,

343

// PacketHeader
// ,
class Transaction {
static uint transacNum = 0;
PacketHeader ph;

//
// PacketHeader.

string accountNum;
double amount;
public Transaction(string ace, double val) {
// .
ph.packNum = transacNum++;
ph.packLen = 512; // arbitrary length
accountNum = ace;
amount = val;
// .
public void sendTransaction() {
Console.WriteLine(" #: " + ph.packNum +
", : " + ph.packLen +
",\n
#: " + accountNum +
", : {0:C}\n", amount);

,
// ,
class PacketDemo {
public static void Main() {
Transaction t = new Transaction("31243", -100.12);
Transaction t2 = new Transaction("AB4655", 345.25);
Transaction t3 = new Transaction("8475-09", 9800.00)
t.sendTransaction();
t2.sendTransaction() ;
t3.sendTransaction() ;

.
#: 0, : 512,
#: 31243, : ($100.12)
#: 1, : 512,
#: 4655, : $345.25
#: 2, : 512,
#: 8475-09, : $9,800.00
PacketHeader ,
, . PacketHeader , . ,
PacketHeader
.

344

I. #

, C++ s t r u c t . #- ++-
. C++ s t r u c t , s t r u c t c l a s s (
: , ). #
s t r u c t , a c l a s s
.

-J
(enumeration) . enum . :

enum

{_);

. _
, .
.
apple, .

enum apple

{ Jonathan, GoldenDel, RedDel,


Cortland, Mclntosh } ;

Winsap,

,
, ( ) .
, , Jonathan 0, GoldenDel 1 ..
,
. enum
,
. .
"". ,
I Console.WriteLine(apple.RedDel + " " +
I
(int)apple.RedDel);
.
1 RedDel 2
, .
i n t . ( #, , .)
, apple.
// .
using System;
class EnumDemo {
12. ,

345

enum apple { Jonathan, GoldenDel, RedDel, Winsap,


Cortland, Mclntosh };
public static void Main() {
string[] color = {
"",
"",
"",
"",
"",
"-"
apple i; // .
// i
// .
for(i = apple.Jonathan; i <= apple.Mclntosh; i++)
Console.WriteLine(i + " " + (int)i);
Console.WriteLine() ;
// .
for(i = apple.Jonathan; i <= apple.Mclntosh; i++)
Console.WriteLine(" " + i + " - " +
color[(int)i]);

:
Jonathan
GoldenDel 1
RedDel 2
Winsap 3
Cortland 4
Mclntosh 5

Jonathan -
GoldenDel -
RedDel -
Winsap -
Cortland -
Mclntosh - -

, for- apple.
,
, . , c o l o r ( ). : . , .
.
. , switch- (
).

346

I. #


. ""
. , , , . ,
10 RedDel.
enum apple { Jonathan, GoldenDel, RedDel = 10, Winsap,
Cortland, Mclntosh };
:
Jonathan
0
GoldenDel
I
RedDel
10
Winsap
11
Cortland
12
Mclntosh
13


i n t , , char. , i n t ,
. , apple
byte.
enum apple : byte { Jonathan, GoldenDel> RedDel, Winsap,
Cortland, Mclntosh };

apple.Winsap, , byte-.


, , , #-.
. ,
. , ,
. conveyor (), : , , . conveyor ()
(1 "", 2 "" ..), ,
, .
jaKoro :
// .
using System;
c l a s s ConveyorControl {
// , ,
p u b l i c enum a c t i o n { , , ,
p u b l i c void conveyor ( a c t i o n corn) {
switch(com) {
case a c t i o n . :
Console.WriteLine(" . ") ;
12. ,

<
};

347

break;
case action.:
Console.WriteLine(" .");
break;
case action.:
Console.WriteLine(" .");
break;
case action.:
Console.WriteLine(" .");
break;

class ConveyorDemo {
public s t a t i c void Main() {
ConveyorControl = new ConveyorControl()
c.conveyor(ConveyorControl.action.);
.conveyor(ConveyorControl.action.)
.conveyor(ConveyorControl.action.);
.conveyor(ConveyorControl.action.);

:
.
.
.
.
conveyor () a c t i o n ,
, a c t i o n . , ,
conveyor () 22.
I .conveyor(22);
// !
, i n t a c t i o n .
conveyor () . , "" , ,
.
, , , , conveyor () .
. switch-. , , switch.

348

I. #

( ) ,
. #- , . #
, C++ Java.
C++- Java-.
# .
,
"". , ,
. , ,
. "
", , , . . , .
#

, .
,
.
#- # .

System.Exception
# .
Exception,
System. ,
Exception.
Exception SystemException ApplicationException.
, #: ,
#- ,
(Common Language Runtime CLR), , . SystemException, ApplicationException
Exception.
.
#
,
SystemException. ,
DivideByZeroException. ,
,
ApplicationException.


#- : t r y , catch, throw f i n a l l y . -

350

I. #

, .
.
, . , .
, , try-. ,
. catch- .
#- . ,
throw. ,
try-, f i n a l l y .

t r y - catch-
t r y catch.
" "; t r y catch catch
t r y . try/catch- :
try {
// , .
}
catch {ExcepTypel exOb) {
// ExcepTypel.
}
catch (ExcepType2 exOb) {
// 2.
. "" catch, . ^ try/catch-, try-
, catch-. , . , catch, ( ).
.
.
( ),
. .
. , try- , catch- . ,
catch. , catch- ( try-) , .


, ,
. ,
. #-
indexOutOfRangeException, , #.
, .

13.

351

// ,
using System;
c l a s s ExcDemol {
p u b l i c s t a t i c void Main() {
i n t [ ] nums = new i n t [ 4 ] ;
try {
Console.WriteLine(
" .");
// ,
// ,
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" !");
}
Console.WriteLine(" catch-.");

:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
!
catch-.
, nums int- . for 0 9,
, IndexOutOfRangeException.
, . -, try-. -, ( - for- nums )
try- , catch-. , catch-,
, try- . ,
c a t c h , .
1 Console.WriteLine(" c a t c h - . " ) ;
. catch- . , , , .
352

I. #

, c a t c h . , ,
.
,
, . , catch- , , .
, try- ,
catch- , , catch-. , f -
1 f o r ( i n t i = 0 ; i < 10; i++) {
:
I f o r ( i n t i = 0 ; i < nums.Length; i++) {
for nums.
, catch- .


, try-,
. , , t r y . , ,
try-, try-, , ,
. .
/* ,
. */
using System;
class ExcTest {
// ,
public s t a t i c void genException()
i n t [ ] nums = new i n t [ 4 ] ;
Console.WriteLine("

.");

// ,
// .
f o r ( i n t i=0; i < 10; i++) {
nums[i] = i ;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");

class ExcDemo2 {
public static void Main() {
try {
ExcTest.genException();
}
catch (IndexOutOfRangeException)
13.

{
353

// .
Console.WriteLine(" !");
}
Console.WriteLine(" catch-.");

, :
.
,
nums [ 0 3 :
nums [ 1 ] : 1
nums [ 2 ] : 2
nums[3]: 3
!
catch-.
genExceptionO t r y , ,
( ), c a t c h
Main (). genExceptionO ,
Main ().



#-, , : .
.
, #- . , . , , , .
//
// #- .
using System;
class NotHandled {
public static void Main() {
int[] nums = new int[4];
Console.WriteLine(" .");
// ,
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine ("nums [ {0-} ] : {1}", i , nums[i]);

,
:

354

I. #

Unhandled Exception: System.IndexOutOfRangeException:


Index was outside the bounds of the array,
at NotHandled.MainO

NotHandled.Main () System. IndexOutOfRangeException,


.

, , ! ,
.
, ,
catch-. . ,
catch-
DivideByZeroException ( #-). , , IndexOutOfRangeException,
catch-. .
// !
using System;
class ExcTypeMismatch {
public static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine(" .");
// ,
// ,
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");
}
/* catch-
DivideByZeroException,
. */
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");
}
Console.WriteLine(" catch-. ") ;
:
,
nums[ 0 ] : 0
nums[1]: 1
nums[2]: 2
nums[3 3: 3

13.

355

Unhandled Exception: System.IndexOutOfRangeException:


Index was outside the bounds of the array,
at ExcTypeMismatch.Main()

, catch-,
DivideByZeroException, IndexOutOfRangeException.

, . ,
, , . , DivideByZeroException.
, . , ,
. .
//
// !
using System;
c l a s s ExcDemo3 {
p u b l i c s t a t i c void Main() {
i n t [ ] numer = { 4, 8, 16, 32, 64, 128 };
i n t [ ] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length;
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");

:
4 / 2 2
!
16/4
4
32/4
8
!
128 / 8 16
.
. ,
356

I. #

try-,
"" . .

catch-
try- , catch-.
. c a t c h . , ,
.
// catch-.
u s i n g System;
c l a s s ExcDemo4 {
p u b l i c s t a t i c void Main() {
// numer denom.
i n t [ ] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
i n t [ ] denom = { 2 , 0 , 4 , 4 ,
0,8};
for(int i=0; i < numer.Length;
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" .")

:
4/2
2
!
16/4
4
32/4
8
!
128 / 8 16
.
.
, catch .
catch- ,
. ,
. catch- .
13.

357


, .
catch- .
" ", ,
.
,
IndexOutOfRangeException DivideByZeroException.
// catch-
// " ".
using System;
class ExcDemo5 {
public static void Main() {
// numer denoiti.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2 , 0, 4, 4, 0, 8 } ;
for(int i=0; i < numer.Length;
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch {
Console.WriteLine(
" .");

:
4 / 2 2
.
1 6 / 4 4
3 2 / 4 8
.
128 / 8 16
.
.
catch-, " ",
:
catch-.

try-
try- . , try- catch-,
try-, try-. ,
IndexOutOfRangeException t r y , .

358

I. #

// try-,
using System;
class NestTrys {
public static void Main() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
try { // try-.
for(int i=0; i < numer.Length; i++) {
try { // try-.
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");

catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" .");
Console.WriteLine(
" .");

:
4 / 2 2
!
1 6 / 4 4
3 2 / 4 8
!
128 / 8 16
.
.
, try- (
), . try-
.
.
try- . .
, . try- , try- . try- " " ,
.

13.

359


, #. , throw. :

throw exceptOb;
exceptOb ,
Exception.

, throw
^ DivideByZeroException .
// .
using System;
class ThrowDemo {
public static void Main() {
try {
Console.WriteLine(" .");
throw new DivideByZeroException();
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" .");
}
Console.WriteLine(" try/catch-.");

:
.
.
try/catch-.

, DivideByZeroException, : new throw. , throw , "


". DivideByZeroException , .
, . , , .


, catch-, ,
() catch-.
. , ,
, . , -

360

I. #

throw, . , throw,
throw ;
,
catch-, c a t c h .
.
B IndexOutOfRangeException.
// .
using

System;

c l a s s Rethrow {
p u b l i c s t a t i c void genException() {
// numer denom.
i n t [ ] numer = { 4, 8, 16, 32, 64, 128, 256, 512
i n t [ ] denom = { 2 , 0 , 4, 4,
0,8};

};

for(int i=0; i<numer.Length;


try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[l]/denom[i]);
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !")
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(
" .")
throw; // .

class RethrowDemo {
public static void Main() {
try {
Rethrow.genException();
}
catch(IndexOutOfRangeException) {
//
// .
Console.WriteLine("
" .");

( ),
.. genException (), . IndexOutOfRangeException Main ().
13.

361

f i n a l l y
,
try/catch-. ,
, , ,
.
, . , # :
finally.
, try/catch, try/catch- f i n a l l y .
try/catch-, f i n a l l y ,
.
try {
// , .
}

catch {ExcepTypel
II
)
catch {2
II

exOb) {

ExcepTypel.

) {
2.

finally {
// .
}
f i n a l l y try/catch-,
. , try-
finally- . finally ,
try- catch- .
finally:
// finally.
using System;
class UseFmally {
public s t a t i c void genException(int what) {
int t ;
i n t [ ] nums = new i n t [ 2 ] ;
Console.WriteLine(" " + what);
try {
switch(what) {
case 0:
t = 10 / what; //
// ,
break;
case 1:
nums[4] = 4 ; //
// .
362

I. #

break;
case 2:
return; // try-.
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");
return; // catch-.
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" .");
}
finally {
Console.WriteLine(" try-.");

class FinallyDemo {
public static void MainO {
for(int i=0; i < 3;
UseFinally.genException(i);
Console.WriteLine();

:

!
try-.
1
.
try-.
2
t r y - .
,
try-, f i n a l l y .

" "
,
. , catch- . . Exception,
, . Exception catch-.
Exception . : Message,
StackTrace T a r g e t S i t e . .
13.

363

Message , ,
StackTrace , .
T a r g e t S i t e , , .
Exception .
ToStringO, .
ToStringO , ,
, WriteLine ( ) .
Exception .
// Exception.
using System;
class ExcTest {
public static void genException() {
int[] nums = new int[4];
Console.WriteLine(" .");
// ,
// ,
for(int i=0; i < 10; i++) {
nums[i] i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");

class UseExcept {
public static void Main() {
try {
ExcTest.genException();
}

c a t c h (IndexOutOfRangeException exc) {
// .
Console.WriteLine(" : " ) ;
C o n s o l e . W r i t e L i n e ( e x c ) ; // T o S t r i n g O .
Console.WriteLine(" StackTrace: " +
exc.StackTrace);
Console.WriteLine(" Message: " +
exc.Message);
Console.WriteLine(" T a r g e t S i t e : " +
exc.TargetSite);
}

Console.WriteLine(" catch-.");

:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3

364

/
J

I. #

:
System.IndexOutOfRangeException: Index was outside
the bounds of the array.
at ExcTest.genException()
at UseExcept.Main()
StackTrace:
at ExcTest.genException()
at UseExcept.Main()
Message: Index was outside the bounds of the array.
TargetSite: Void genException()
catch-.
Exception . :

Exception()
Exception(string str)
.
Message, .
.


System . SystemException,
(Common Language Runtime)
. , #, . 13.1.
13.1. ,
System

ArrayTypeMismatchException

DivideByZeroException

IndexOutOfRangeException

invalidCastException

Outof MemoryException

new -

overf lowException

NuilRef erenceException

, .. ,

stackoverf lowException

, . 13.1, , NuilRef erenceException. , ,


, . . null-,
n u l l . , , ,
. ,
NullReferenceException.

13.

365

// NullReferenceException.
using System;
class X {
int x;
public X(int a) {
x = a;
public int add(X o) {
return x + o.x;

// NullReferenceException.
class NREDemo {
public static void Main() {
X p new X(10);
X q = null; // q
// null,
int val;
try {
val = p.add(q); //
// .
} catch (NullReferenceException) {
Console.WriteLine("NullReferenceException!");
Console.WriteLine(" ...\n");
// ,
q = new X(9);
val = p.add(q);
Console.WriteLine(" val {}", val);

:
NullReferenceException!
...
val 19
X, add (),
, ,
, , .
Main () . , , , , q,
( n u l l ) .
p.iueth (), q . q
, q. x
NullReferenceException.
StackOverf lowException, . . , ,
366

I. #

, ,
. . , ,
, .


#- , #-
. # , .
"" . .
Exception. ,
,
ApplicationException, "" , , .
,
.
, ,
, Exception . ,
.
, "" .
10
RangeArray. , RangeArray i n t , . , , -5 27,
RangeArray. 10 ,
, ,
RangeArray. , , RangeArray. ,
"". ,
RangeArray
"" .
^ RangeArray.
//
//
// RangeArray.
using System;
// RangeArray.
c l a s s RangeArrayException : ApplicationException {
// ,
public RangeArrayException() : base() { }
p u b l i c RangeArrayException(string s t r ) : b a s e ( s t r )

{ }

// ToStringO
// RangeArrayException.
public override s t r i n g ToStringO {
r e t u r n Message;

13.

367

// RangeArray.
class RangeArray {
// .
int[] ; // .
int lowerBound; // .
int upperBound; // .
int len; // Length.
// ,
public RangeArray(int low, int high) {
high++;
if(high <= low) {
throw new RangeArrayException(
" ."),
}
= new int[high - low];
len = high - low;
lowerBound = low;
upperBound = --high;
// Length, ,
public int Length {
get {
return len;

// RangeArray.
public int this[int index] {
// ,
get {
if(ok(index)) {
return a[index - lowerBound];
} else {
throw new RangeArrayException(
" .");

// .set {
if(ok(index)) {
a[index - lowerBound] = value;
}
else throw new RangeArrayException(
" .");

// true,
// ,
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return true;
return false;

368

I. #

//
// ,
class RangeArrayDemo {
public static void Main() {
try {
RangeArray ra = new RangeArray(-5, 5 ) ;
RangeArray ra2 = new RangeArray(1, 10);
// - .
Console.WriteLine(" : " + ra.Length);
for(int i = -5; i <= 5; i++)
ra[i] = i;
Console.Write(" : " ) ;
for(int i = -5; i <= 5; i++)
Console.Write(ra[i] + " " ) ;
Console.WriteLine("\n");
// - 2.
Console.WriteLine(" 2: " + ra2.Length);
for(int i = 1; i <= 10; i++)
ra2[i] = i;
Console.Write(" ra2: ") ;
for(int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " " ) ;
Console.WriteLine("\n");
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// " ".
Console.WriteLine(
" .");
// ,
try {
RangeArray = new RangeArray(100, -10); // !
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// ,
try {
RangeArray = new RangeArray(-2, 2 ) ;
for(int i = - 2 ; i <= 2; i++)
[i] = i;
Console.Write(" : " ) ;
for(int i = -2; i <= 10; i++) //
// .
Console.Write([i] + " " ) ;

13.

369

} catch (RangeArrayException exc)


Console.WriteLine(exc);

:
: 11
: - 5 - 4 - 3 - 2 - 1 0 1 2 3 4 5
2: 10
2 : 1 2 3 4 5 6 7 8 9

10

.
.
: - 2 - 1 0 1 2 .
RangeArray- RangeArrayException. -
A p p l i c a t i o n E x c e p t i o n . , ,
, A p p l i c a t i o n E x c e p t i o n . ,
RangeArray-.
,
Range Array t r y , .
RangeArray
#-
.
, "" .
, T o S t r i n g O . ,
, , #.


, , catch-, c a t c h catch-
. ,
Exception, Exception
. , , c a t c h .
, .
, , catch- . catch- . , catch- c a t c h , . #
catch- .
ExceptA
ExceptB. ExceptA A p p l i c a t i o n E x c e p t i o n ,
ExceptB ExceptA. .
370

I. #

//
//
// .
using System;
// .
class ExceptA : ApplicationException {
public ExceptA() : base() { }
public ExceptA(string str) : base(str) { }
public override string ToStringO {
return Message;

//
// ExceptA.
class ExceptB : ExceptA {
public ExceptB() : base() { }
public ExceptB(string str) : base(str) { }
public override string ToStringO {
return Message;

class OrderMatters {
public static void Main() {
for(int x = 0; x < 3; x++) {
try {
if(x==0) throw new ExceptA(
" ExceptA.");
else if(x==l) throw new ExceptB(
" ExceptB.");
else throw new ExceptionO;
}
catch (ExceptB exc) {
// .
Console.WriteLine(exc);
}
catch (ExceptA exc) {
// .
Console.WriteLine(exc);
}
catch (Exception exc) {
Console.WriteLine(exc);

ExceptA.
ExceptB.
System.Exception: Exception of type System.Exception was thrown,
at OrderMatters.Main()
catch-.
. ExceptB ExceptA, catch ExceptB , 13.

371

ExceptA. catch-
Exception ( )
. , catch . .
catch-, , . , .
, ,
, ,
, .

checked
unchecked
# , , . , , ,
. , . , , :
byte a, b, result;
= 127;
b = 127;
result = (byte)(a * b ) ;
b
byte. , r e s u l t .
# checked unchecked. , , checked. ,
unchecked. ,
- .
checked .
checked-. .
checked {expr)

checked {
// , .
}
expr , .
,
OverflowException.

unchecked . ,
. , .
unchecked
372

(expr)
I. #

unchecked {
// , .
, .
.
, checked,
unchecked.
// checked unchecked.
using System;
class CheckedDemo {
public s t a t i c void Main() {
byte a, b;
byte result;
a = 127;
b = 127;
try {
result = unchecked((byte)(a * b ) ) ;
Console.WriteLine("Unchecked-: " + result);
result = checked((byte)(a * b)); //
// .
Console.WriteLine("Checked-: " +
result); //
// .
catch (OverflowException exc) {
// .
Console.WriteLine(exc);

:
Unchecked-: 1
System.OverflowException: Arithmetic operation resulted in an
overflow.
at CheckedDemo.Main()
, .
.

checked unchecked . , .
// checked unchecked
// .
using System;
class CheckedBlocks {
public s t a t i c void Main() {
byte a, b;
byte result;

13.

373

= 127;
b = 127;
/
try {
unchecked {
a = 127;
b 127;
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked-: " + result);
a 125;
b = 5;
result = unchecked((byte)(a * b ) ) ;
Console.WriteLine("Unchecked-: " + result);
checked {
a = 2;
b = 7;
result = checked((byte)(a * b)); // .
Console.WriteLine("Checked-: " + result);
a = 127;
b = 127;
result = checked((byte)(a * b)); //
//
// .
Console.WriteLine("Checked-: " +
result); //
// .
catch (OverflowException exc) {
// .
Console .WriteLine (exc).;

:
Unchecked-: 1
Unchecked-: 113
Checked-: 14
System.OverflowException: Arithmetic operation resulted in an overflow,
at CheckedBlocks.Main()
, unchecked-
. checked .
checked
unchecked , checked/unchecked- . ,
.

374

I. #

#- -
Console.WriteLine (), .
#- - ,
, , . #- -. # - ,
.NET Framework, .NET-.
, . , #- - , .

#- -
- .
(stream) , ,
. #- . , , . , - . , , ,
.


#- - .
, - . .
, # char 16- , a byte 8-.
ASCII, char byte : char-.
Unicode-, . ,
( ) -. # , ,
byte-char- char-byte- .


,
Console. In, Console.Out Console.Error, , System. Console.Out . . , Console.WriteLine (}
Console.Out. Console. In , . C o n s o l e . E r r o r ,
. -. . , .
376

I. #


# , . ,
,
. ,
, , .
System. 10.
,
:
1 using System.10;
System. 10,
Console System.

Stream
#- System. 10. Stream.
stream
. , .. . Stream .
, Stream, . 14.1.
14.1. stream

v o i d c l o s e ()
v o i d F l u s h ()
i n t ReadByte ()
mt

Read (byte [ ] buf,


mt offset,
m t numBytes)
l o n g Seek (long offset,
S e e k o n g m origin)
v o i d WriteByte (byte )
Void w r i t e (byte [ ] buf,
int offset,
m t numBytes)



-1
numBytes buf, buf [offset],



numBytes buf, buf[offset]

- , . 14 1, IOException.
, , , , NotSupportedException.
, stream , . ,
,
. ,
Seek (). , Stream. . 14.2.
Length P o s i t i o n ,
, .
14. -

377

14.2. , stream

b o o l canRead

t r u e , .

b o o l canSeek

t r u e ,
.

b o o l Canwrite

t r u e , .

l o n g Length

long Position

. ,


s t r e a m .

Buf f eredstream

Filestream

, -

Memorystream

.
.


, #-. TextReader TextWriter. TextReader
, TextWriter
. , , . , -, .
. 14.3 , TextReader.
lOException.
( .)
ReadLine (), ,
string-. , .
14.3. , TextReader

v o i d c l o s e ()
int

Peek

int

Read

378


, . - 1 ,
- .
-1

I. #

. 14.3

int Read (char [] buf,


int offset,
int numChars)

numChars buf,
b u f [ o f f s e t ] ,

int ReadBlock(char[] buf,


numChars buf,
int offset,
buf[ offset],
int numChars)
string ReadLineO

s t r i n g .
null-

string ReadToEndO

, ,
string-

TextWriter Write () W r i t e L i n e O , . , , .

void Write(int val)

i n t

void Write(double val)

double

void Write(bool val)

b o o l

void WriteLine(string val)

s t r i n g

void WriteLine(uint val)

u i n t

void WriteLine(char val)

Write () WriteLine (), TextWriter


Close () Flush ():
v i r t u a l void Close()
v i r t u a l void Flush()
Flush () , , . Close () .
TextReader TextWriter -
, , . , ,
TextReader TextWriter.

streamReader

streamwriter

stringReader

stringwriter

14. -

379


, # ,
. , BinaryReader BinaryWriter, -.
, #- -, , , ,
-.

-
-
Console. In, Console.Out C o n s o l e . E r r o r . - , 2, .
, .
, , #- , , , , . , #- -,
- , . , .


Console. In TextReader,
, TextReader.
, Console,
Console. In. Console
: Read () ReadLme ().
Read () .
s t a t i c i n t Read()
Read () , . ,
- , .
i n t , char. ReadO 1, lOException. ( ), ,
, <Enter>.
, Read ().
// .
using System;
class Kbln {
public static void Main() {
char ch;
380

I. #

Console.Write{
" , <ENTER>: " ) ;
ch = (char) Console.Read(); //
// char-.
Console.WriteLine("

: " + c h ) ;

:
, <ENTER>:
:
, Read () , . <Enter>
, . , , . , ( ).
, ReadLine ().
static string ReadLine()
ReadLine () ,
<Enter>, s t r i n g . IOException.
,
Console. In ReadLine ().
// ReadLine().

using System;
c l a s s ReadString {
p u b l i c s t a t i c void Main() {
string str;
Console.WriteLine(" .");
s t r = Console.ReadLine();
Console.WriteLine(" : " + s t r ) ;
.
I .
I .
I : .
Console
Console. In, TextReader. ,
, TextReader.
//
// Console.In.
using System;
class ReadChars2 {
public s t a t i c void Main() {
string s t r ;
14. -

381

Console.WriteLine(" .")/
s t r = Console.In.ReadLine();
Console. WriteLine (" : " + str 4 );
, ReadLine ()
Console. In. , , TextReader, Console. In,
, .


Console.Out C o n s o l e . E r r o r TextWriter.
Write
WriteLineO, . . Console
Write () WriteLine ( ) , Console, . ( ) TextWriter,
Console.Out C o n s o l e . E r r o r .
,
Console.Out C o n s o l e . E r r o r .
// Console.Out C o n s o l e . E r r o r .
using System;
class ErrOut {
public s t a t i c void Main() {
int a=10, b=0;
int r e s u l t ;
Console.Out.WriteLine(
" .");
try {
r e s u l t = / b; // .
} catch(DivideByZeroException exc) {
Console.Error.WriteLine(exc.Message);

:
.
Attempted to divide by zero.
, , C o n s o l e . E r r o r . Console.Out, C o n s o l e . E r r o r
, ?
: . ,
C o n s o l e . E r r o r ,
. , , , (log file), . ,
, , -

382

I. #

, .
, -.

F i l e s t r e a m -

# ,
. , .
. , # , . ,
. # . , .
, . . - .
,
FileStream. FileStream Stream . , , FileStream, System. 10. ,
:
1 u s i n g System.10;


, ,
FileStream. FileStream .
:
F i l e S t r e a m ( s t r i n g filename,
FileMode mode)
filename , , . mode ,
, . mode
, FileMode ( . 14.4).
.
14.4. F i l e M o d e

F i l e M o d e . Append

FileMode. Create

F i l e M o d e . CreateNew

F i l e M o d e . Open

FileMode. openOrCreate

, .

FileMode. Truncate

14. -

383

, .
,
FileNotFoundException. - -,
lOException.
: ArgumentNullException ( null-),
ArgumentException ( mode), SecurityException (
) DirectoryNotFoundException (
).

t e s t . dat .
FileStream f i n ;
try {
fin = new FileStream("test.dat", FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message) ;
return;
}
catch {
Console.WriteLine("He .");
return;
}
catch- ,
. , " ",
, . , , .
FileNotFoundException lOException,
( ) , ,
.
, FileStream
.
, :
FileStream(string filename, FileMode mode,
FileAccess how)
, filename , a mode
. , how,
. , FileAccess, :
FileAccess.Read
FileAccess.Write
FileAccess.ReadWrite
, t e s t . d a t
:
FileStream f i n = new F i l e S t r e a m ( " t e s t . d a t " , FileMode.Open,
FileAccess.Read);
.
Close (). :
void Close()
,
, .
Close () lOException.
384

I. #

Files tream
FileStream , :
ReadByteO Read (). ,
ReadByte ( ) , :
int ReadByte()
, . 1. NotSupportedExeption
( ) ObjectDisposedException ( ).
, Read (), :
i n t Read(byte[] buf, i n t offset,
i n t numBytes)
Read () numBytes buf, buf [off set]. . - lOException.
, NotSupportedException,
.
ReadByte ()
. . try/catch-,
, : "
" " ".
.
/* .
,
, .
, TEST.CS,
:
ShowFile TEST.CS
*/
using System;
using System.10;
class ShowFile {
public s t a t i c void Main(string[] args) {
int

i;

FileStream

fin;

try {
fin = new FileStream(args[0], FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message) ;
return;
} catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message +
": ShowFile ");
return;

14. -

385

// , EOF.
do {
try {
i = fin.ReadByte();
} catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1) Console.Write((char) i ) ;
} while(i != - 1 ) ;
fin.Close();


, WriteByte ().
:
void WriteByte(byte val)
, val. lOException. ,
NotSupportedException.
Write .
:
void Write(byte[] buf, int offset, int numBytes)
Write () numBytes buf,
buf [ o f f s e t ] .
lOException.
, NotSupportedException. .
, ,
,
, , .
. , ,
128 . , , ,
, .

, , Flush ():
void Flush()

lOException.
,
Close (). , , ,
.
Flush ().
.

386

I. #

// .
using System;
using System.10;
class WriteToFile {
public static void Main(string[] args) {
FileStream fout;
// ,
try {
fout = new FileStreamC'test.txt", FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(
exc.Message +
" .")
return;
// ,
try {
for(char = '1; <= ''; ++)
fout.WriteByte((byte) ) ;
} catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
fout.Close();

t e s t . t x t .
, .
,
t r y / c a t c h . t e s t . t x t :
1 ABCDEFGHIJKLMNOPQRSTUVWXYZ

Filestream
- FileStream
, ,
. , ,
.
.
/* .

.
, FIRST.DAT
SECOND.DAT,
:
CopyFile FIRST.DAT SECOND.DAT
*/
14. -

387

using System;
using System.10;
class CopyFile {
public static void Main(string[] args) {
int i ;
FileStream fin;
FileStream fout;
try {
// ,
try {
fin = new FileStream(args[0], FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
" .")
return;
// ,
try {
fout = new FileStream(args[1], FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(
exc.Message +
" .");
return;
}
} catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message +
": CopyFile ");
return;
// ,
try {
do {
i = fin.ReadByte();
if(i != -1) fout.WriteByte((byte)i) ;
} while(i != -1) ;
} catch(IOException exc) {
Console.WriteLine(exc.Message +
" . " ) ;
fin.Close() ;
fout.Close() ;

388

I. #

-

, # . Unicode- ( ). , Unicode-, .
, , F i l e S t r e a m StreamReader
StreamWriter. .
,
. StreamReader StreamWriter
.
StreamWriter TextWriter, a StreamReader
TextReader. , StreamWriter StreamReader
, .

StreamWriter
,
Stream (, FileStream) StreamWriter.

StreamWriter . :
StreamWriter(Stream stream)
stream . Argument Except ion, stream ,
ArgumentNullException, () null-.
StreamWriter
.
"-", ,
, t e s t . t x t .
, "".
FileStream, StreamWriter
>.
/* "-",
StreamWriter. */
using System;
using System.10;
class KtoD {
public static void Main() {
string str;
FileStream fout;
try {

fout = new FileStream("test.txt", FileMode.Create);

catch(IOException exc) {

14. -

389

Console.WriteLine(exc.Message +
"He .");
return ;
}
StreamWriter fstr_out - new StreamWriter(fout);
Console.WriteLine(
" ('' ).");
do {
Console.Write(": " ) ;
str = Console.ReadLine();
if(str != "") {
str = str + "\r\n"; //
// ,
try {
fstr_out.Write(str);
} catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
return ;
} while(str != "");
fstr_out.Close() ;

StreamWriter. :
StreamWriter(string filename)
StreamWriter(string filename, bool appendFlag)
filename ,
. appendFlag
bool: appendFlag t r u e ,
. .
, , , - IOException (
).
"-",
StreamWriter.
// StreamWriter.
using System;
using System.10;
class KtoD {
public static void Main() {
string str;
StreamWriter fstr_out;

// ,
// StreamWriter.
try {
fstr_out = new StreamWriter("test.txt");
390

I. #

catch(IOException exc) {
Console.WriteLine(exc.Message +
"He .");
return ;
Console.WriteLine(
" ('1 ).");
do {
Console.Write(": " ) ;
str = Console.ReadLine();
if(str != "") {
str = str + "\r\n"; //
// ,
try {
fstr_out.Write(str);
v
} catch(IOException exc) {
Console.WriteLine(
exc.Message +
" . " ) ;
return ;
} while(str != "");
fstr_out.Close() ;

StreamReader
,
- StreamReader. StreamReader
. :
StreamReader(Stream stream)
stream . ArgumentNullException, stream n u l l , ArgumentException, stream
. StreamReader
.
"-", t e s t . t x t . , ,
^ .
/* "-",
FileReader. */
using System;
using System.10;
class DtoS {
public static void Main() {
FileStream fin;
14. -

391

string s;
try {
fin = new FileStream("test.txt", FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"He .");
return ;
StreamReader fstr_in = new StreamReader(fin);
// ,
while ((s = fstr__in.ReadLine () ) != null) {
Console.WriteLine(s);
f strain. Close () ;

, . , ReadLine ( ) , n u l l , , .
StreamWriter, , StreamReader. :
StreamReader(string filename)
filename ,
. . FileNotFoundException. filename
n u l l , ArgumentNullException,
, ArgumentException.


, , Console. In, . , - .
/ . , ,
.
, .
. -, " < " " > " ,
Console. In / Console.Out, . , , :
u s i n g System;
class Test {
public static void Main() {
Console.WriteLine(" .");

392

I. #


Test > log
" ." log. . , , . .
" < " " > " #, . ,
- ( Windows),
, .
,
. S e t l n ( ) , SetOut ()
S e t E r r o r (), Console:
static void Setln(TextReader input)
static void SetOut(TextWriter output)
static void SetError(TextWriter output)
, , S e t i n O ,
.
, TextReader.
, Filestream-,
StreamWriter-. :
// Console.Out.
using System;
using System.10;
class Redirect {
public s t a t i c void Main() {
StreamWriter log_out;

try {
log_out = new StreamWriter("logfile.txt");
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"He .");
return ;
//
// .
Console.SetOut(log_out);
Console.WriteLine(" .");
for(int i=0; i<10; i++) Console.WriteLine(i);
Console.WriteLine(" .");
log_out.Close() ;

14. -

393

,
logf i l e . t x t :
.

1
2
3
4
5

7
8
9
.
,
-.


, - . ,
, i n t - , double- short-. #- BinaryReader
BinaryWriter. , , , .

BinaryWriter
BinaryWriter ,
.
:
BinaryWriter(Stream outputStream)
outputStream
, . , , FileStream. outputStream

null-, ArgumentNullException, outputStream , ArgumentException.


BinaryWriter ,
#- ( . 14.5). : s t r i n g , . BinaryWriter
p l o s e () Flush (), .
14.5. , BinaryWriter

void w r i t e (sbyte val)


void w r i t e (byte val)

394

byte- ( )
byte- ( )

I. #

. 14.5

v o i d w r i t e ( b y t e [ ] buf)

byte-

v o i d w r i t e ( s h o r t vai)

s h o r t ( )

v o i d w r i t e ( u s h o r t vai)

u s h o r t - ( )

v o i d w r i t e ( i n t vai)

i n t

v o i d w r i t e ( u i n t vai)

uint- ( )

void w r i t e (long vai)

l o n g ( )

v o i d w r i t e ( u i o n g vai)

uiong- ( )

v o i d w r i t e ( f l o a t vai)

float-

v o i d w r i t e (double v a i )

double-

v o i d w r i t e ( c h a r vai)

void w r i t e (char[] buf)

v o i d w r i t e ( s t r i n g vai)

string- ,

BinaryReader
BinaryReader ,
.
:
BinaryReader(Stream.inputStream)
inputStream
, .
, ,
FileStream. inputStream null-, ArgumentNullException, inputStream
, ArgumentException.
BinaryReader #. . 14.6. ,
ReadStringO , , . EndOfStreamException, IOException. BinaryReader Read ():

i n t Re a d ()

. -1

i n t Read ( b y t e [ ] buf,
i n t offset,
i n t num)

num buf,
buf[offset],

i n t Read (char [ ] buf,


i n t offset,
i n t )

buf,
buf[offset],


IOException.
14. -

395

BinaryReader Close ( ) .
14.6. , BinaryReadez

bool ReadBoolean()

booi-

byte ReadByte()

byte-

sbyte ReadSByteO

sbyte-

byte[] ReadBytes(int num)

char ReadChar()

char-

char[] ReadChars(int num)

double ReadDouble()

double-

float ReadSmgle ()

float-

short Readlntl6()

short-

i n t Readlnt32()

int-

long Readlnt64()

long-

ushort ReadUIntl6()

ushort-

uint ReadUInt32()

uint-

ulong ReadUInt64()

uiong-

s t r i n g ReadStringO

string-,
, . ,
B i n a r y W r i t e r

-
, BinaryReader
BinaryWriter. , .
//
//
.
using System;
using System.10;
class RWData {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataln;
int i = 10;
double d = 1023.56;
bool b = true;
try {
dataOut = new
BinaryWriter(new FileStream("testdata",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\nHe . 1 1 );
396

I. #

return;
try {
Console.WriteLine(" " + i ) ;
dataOut.Write(i) ;
Console.WriteLine(" " + d ) ;
dataOut.Write(d);
Console.WriteLine(" " + b ) ;
dataOut.Write(b);
Console.WriteLine(" " + 12.2 * 7.4);
dataOut.Write(12.2 * 7.4);
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
dataOut.Close();
Console.WriteLine();
// ,
try {
dataln = new
BinaryReader(new FileStream("testdata",
FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"\nHe .");
return;
try {
i = dataln.Readlnt32();
Console.WriteLine(" " + i ) ;
d = dataln.ReadDouble();
Console.WriteLine(" " + d ) ;
b = dataln.ReadBoolean();
Console.WriteLine(" " + b ) ;
d = dataln.ReadDouble();
Console.WriteLine(" " + d ) ;
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
dataln.Close ();

14. -

>

397

:
10
1023.56
True
90.28

10
1023.56
True
90.28

t e s t d a t a ,
, , ,
.
, #-
-.
. , .
,
. , .
/* BinaryReader BinaryWriter
. */
using System;
using System.10;
class Inventory {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataln;
string item; // .
int onhand; // , .
double cost; // .
try {
dataOut = new
BinaryWriter(new FileStream("inventory.dat",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\nHe .");
return;
}
//
//
,
try {
dataOut.Write("");
dataOut.Write(10) ;
dataOut.Write(3.95);
dataOut.Write("");
dataOut.Write(18);
dataOut.Write(1.50);

398

I. #

dataOut.Write("");
dataOut.Write(5) ;
dataOut.Write(4.95) ;
dataOut.Write("");
dataOut.Write(8) ;
dataOut.Write(8.95) ;
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\ .");
dataOut.Close() ;
Console.WriteLine() ;
//
// ,
try {
dataln = new
BinaryReader(new FileStream("inventory.dat",
FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"\nHe .");
return;
// , .
Console.Write(" : " ) ;
string what = Console.ReadLine();
Console.WriteLine() ;
try {
for(;;) {
// ,
item = dataln.ReadString();
onhand = dataln.Readlnt32();
cost = dataln.ReadDouble();
/*
, . */
if(item.CompareTo(what) = = 0 ) {
Console.WriteLine(item + ": " + onhand +
" . " +
": {0:} .",
cost);
Console.WriteLine(
" <{0}>: {1:}." ,
item, cost * onhand);
break;

catch(EndOfStreamException) {
Console.WriteLine(" .");

14. -

399

catch(IOException exc) {
Console.WriteLine(exc.Message + " .");
}
dataln.Close();
}
}
:
:
: 18 . : $1.50 .
<>: $27.00.
, , . , , , , , . ,
.
,
.
EndOfStreamException, , ,
. , .

LJ
, .. , , . # , . Seek(), FileStream. ( ) .
Seek () :
long Seek(long newPos, SeekOrigin
origin)
newPos , ,
, origin. origin , SeekOrigin.

SeekOrigin. Begin

SeekOrigin. Current

SeekOrigin.End

Seek () . - , IOException. , NotSupportedException.


400

I. #

, -
. , .
// .
using System;
using System.10;
class RandomAccessDemo {
public static void Main() {
FileStream f;
char ch;
try {
f = new FileStream("random.dat", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;
/ / .
f o r ( i n t i=0; i < 26; i++) {
try {
f.WriteByte((byte)('A'+i));
}

catch(IOException exc) {
Console.WriteLine(exc.Message);
return ;

try {
// .
f.Seek(O, SeekOrigin.Begin); // .
ch = (char) f.ReadByte();
Console.WriteLine(" " + ch) ;
f.Seekd, SeekOrigin.Begin) ; // .
ch = (char) f.ReadByte();
Console.WriteLine(" " + ch) ;
f.Seek(4, SeekOrigin.Begin); // . v
ch = (char) f.ReadByte();
Console.WriteLine(" " + ch);
Console.WriteLine ();
// .
Console.WriteLine(" : " ) ;
for(int i=0; i < 26; i += 2) {
f.Seekd,

SeekOrigin.Begin) ; / /
/ / i- .
ch = (char) f.ReadByte();
Console.Write(ch + " " ) ;

14. -

401

catch(IOException exc) {
Console.WriteLine(exc.Message);
Console.WriteLine();
f.Close ();

:



:
ACEGIKMOQSUWY

Memory Stream
-
.
. MemoryStream.
MemoryStream Stream, - . :
MemoryStream(byte[] buf)
buf ,
- / . , ,
. Seek (). buf,
.
,

jyiemoryStream:
// MemoryStream.
using System;
using System.10;
class MemStrDemo {
public static void Main() {
byte[] storage = new byte[255];
// .
MemoryStream memstrm = new MemoryStream(storage) ;
// memstrm StreamWriter
// StreamReader.
StreamWriter memwtr = new StreamWriter(memstrm) ;
StreamReader memrdr = new StreamReader(memstrm);
//
// memwtr.
for(int i=0; i < 10;
402

I. #

memwtr'.WriteLine("byte

[" + i + "] : " + i) ;

// ,
merawtr.Write (f . ') ;
memwtr.Flush();
Console.WriteLine(
" storage:
// .
foreach(char ch in storage) {
if (ch == '.') break;
Console.Write(ch);
Console.WriteLine(
" memrdr: " ) ;
// memstrm,
// .
menistrm.Seek(O, SeekOrigin.Begin) ; //
// .
string str = memrdr.ReadLine();
while(str != null) {
str = memrdr.ReadLine();
if (str.CompareToC1.11) == 0) break;
Console.WriteLine(str) ;

:
storage:
byte [0]: 0
byte [1]: 1
byte [2]: 2
byte [3]: 3
byte [4]: 4
byte [5]: 5
byte [6]: 6
byte [7]: 7
byte [8]: 8
byte [9]: 9
memrdr:
byte [1]: 1
byte [2] : 2
byte [3]: 3
byte [4]: 4
byte [5]: 5
byte [6]: 6
byte [7]: 7
byte [8]: 8
byte [9]: 9

14. -

403

storage. memstrcn Memory Stream.


memstrm StreamReader memrdr
StreamWritex memwtr. memwtr , . , memwtr flush (). , , memwtr, .
"", .. foreach.
Seek () ,
memrdr.
, , . ,
, .
GUI-, Windows.
. , ,
.

StringReader
StringWriter
-, ,
(byte-) , (string-). StringReader StringWriter. StringReader TextReader, StringWriter TextWriter. ,
, . ,
ReadLineO StringReader
WriteLine () StringWriter.
StringReader :
S t r i n g R e a d e r ( s t r i n g str)
s t r ,
.
StringWriter . :
StringWriter()
"" , .
StringWriter. , T o S t r i n g O .
StringReader StringWriter.
// StringReader
// StringWriter.
using System;
using System.10;
class StrRdrDemo {
public static void Main() {
// StringWriter.
404

I. #

StringWriter strwtr = new StringWriter();


// StringWriter-.
for(int i=0; i < 10; i++)
strwtr.WriteLine(" i : " + i ) ;
// StringReader.
StringReader strrdr = new StringReader(
strwtr.ToStringO ) ;
// StringReader-.
string str = strrdr.ReadLine();
while(str != null) {
str = strrdr.ReadLine();
Console.WriteLine(str) ;

:
i : 1
i : 2
i : 3
i : 4
i : 5
i :
i : 7
i : 8
i : 9
S t r i n g W r i t e r s t r w t r
WriteLine ().
StringReader , s t r w t r ,
T o S t r i n g O . ,
ReadLine ().

-, , . , #-
WriteLine ()
( , i n t double) . , WriteLine () . # , .. ,
. , , ,
"100", , int-. , , Parse ().

14. -

405

, .
#- (, i n t double)
(.. ) , .NET
Framework. Microsoft , #- .NET-
. . #- , , .
.NET- #- (
) .

.NET'

Decimal

decimal

Double

double

Single

float

Intl6

short

Int32

int

Int64

long

UIntl6

ushort

UInt32

uint

UInt64

ulong

Byte

byte

Sbyte

sbyte

System. ,
Int32 "" System. I n t 3 2 .
, #- . "" , .
. ,
.

Decimal

static decimal Parse(string str)

Double

static double Parse(string str)

Single

static float Parse(string str)

Int64

static long Parse(string str)

Int32

static int Parse(string str)

Intl6

static short Parse(string str)

UInt64

static ulong Parse(string str)

UInt32

static uint Parse(string str)

UIntl6

static ushort Parse(string str)

Byte

static byte Parse(string str)

SByte

static sbyte Parse(string str)

Parse () FormatException,
str , .
str null-, ArgumentNullException, a

406

I. #

str , , Overf lowException.


, , . , , .
,
ReadLineO I n t 3 2 . Parse () . ,
Double. Parse () double-.
// ,
// .
using
using

System;
System.10;

c l a s s AvgNums {
p u b l i c s t a t i c void Main() {
string str;
i n t n;
double sum = 0 . 0 ;
double avg, t ;

Console.Write(" : " ) ;
s t r = Console.ReadLine();
try {
n = Int32.Parse(str) ;
}

catch(FormatException exc) {
Console.WriteLine(exc.Message);
n = 0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
n = 0;

Console.WriteLine(" " + n + " .");


for(int i=0; i < n ; i++) {
Console.Write(": ") ;
str = Console.ReadLine();
try {
t = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
t - 0.0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
t = 0;
}
sum += t;
}
avg = sum / n;
Console.WriteLine(" " + avg);

14. -

407

:
: 5
5 .
: 1.1
: 2.2
: 3.3
: 4.4
: 5.5
3.3
. ,
. ,
I n t 3 2 . Parse () , ,
.

408

I. #

#-: . ,
, .
, .
, #.

(delegate). ,
. , , , . ,
. , ,
.
,
, , . ,
. , . ,
, , . .
, .
11 la

C/C++, ,
C/C++

,
, , . , , ,
, . .
d e l e g a t e . :
d e l e g a t e _
{_);
_ , , .
. , , ,
_.
, (..
) .
, ,
, .
, :
// .
using System;
// .
delegate string strMod(string stx);
class DelegateTest {
// .

410

I. #

static string replaceSpaces(string a) {


Console.WriteLine(" .");
return a.Replace(' ', ' - ' ) ;
// .
static string removeSpaces(string a) {
string temp = "";
int i;
Console.WriteLine(" .");
for(i=0; i < a.Length; i++)
if (a[i] != ' f ) temp += a[i] ;
return temp;
// ,
static string reverse(string a) {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i=a.Length-l; i >= 0; i ,
temp += a[i];
return temp;
public static void Main() {
// .
strMod strOp = new strMod(replaceSpaces);
string str;
// .
str = str0p("3TO .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new strMod(removeSpaces);
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new strMod(reverse);
str = strOp(" .");
Console.WriteLine(" : " + str);

:
.
: --.
.
: .
.
: .

15.

411

, strMod,
s t r i n g string-. DelegateTest
, , .
. , replaceSpaces ()
Replace () s t r i n g .
Main () strMod strOp, replaceSpaces (). :
1 strMod strOp = new s t r M o d ( r e p l a c e S p a c e s ) ;
, replaceSpaces () . ( ).
: , . ,
.
.
replaceSpaces ()
strOp, :
I s t r = strOp(" . " ) ;
strOp replaceSpaces ( ) ,
replaceSpaces (). strOp
removeSpaces (), strOp .
removeSpaces ().
, strOp r e v e r s e (),
strOp . , ,
reverse().
, s t r o p , strOp . ,
,
.
, .
. , ,
StringOps:
//
// .
using System;
// .
delegate string strMod(string str);
class StringOps {
// ,
public string replaceSpaces(string a) {
Console.WriteLine(" .");
f
return a.Replace( ', ' - ' ) ;
}
// .
public string removeSpaces(string a) {
string temp = "";
int i;
412

I. #

Console.WriteLine(" . ") ;
for(i=0; i < a.Length; i++)
if(a[i] != f ') temp += a[i];
return temp;
// ,
public string reverse(string a) {
string temp = "";
int i f j;
Console.WriteLine(" .")
for(j=0, i=a.Length-l; i >= 0; i ,
temp += a[i];
return temp;

class DelegateTest {
public static void Main() {
StringOps so = new StringOps(); //
// StringOps.
// .
strMod strOp = new strMod(so.replaceSpaces);
string str;
// ,
str = str0p("3TO .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new strMod(so.removeSpaces);
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new strMod(so.reverse);
str = strOp(" .");
Console.WriteLine(" : " + str);

, StringOps.



(multicasting). ,
( ) , . .
,
"+=".
" - = " . (
" + " , " - " " = " , "+=" "-=".)
15.

413

:
void.
. , s t r i n g , , void, ref-.
// .
using System;
// .
delegate void strMod(ref string str);
class StringOps {
// ,
static void replaceSpaces(ref string a) {
Console.WriteLine(" .");
a = a.Replace(' , f - f ) ;
}
// .
static void removeSpaces(ref string a) {
string temp = "";
int i;
Console.WriteLine(" .");
for(i=0; i < a.Length; i++)
if(a[i] != f f ) temp += a[i];
a = temp;
}
// ,
static void reverse(ref string a) {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i=a.Length-l; i >= 0; i , j++)
temp += a[i];
a = temp;
}
public static void Main() {
// .
strMod strOp;
strMod replaceSp = new strMod(replaceSpaces);
strMod removeSp = new strMod(removeSpaces);
strMod reverseStr = new strMod(reverse);
string str = " .";
// .
strOp = replaceSp;
strOp += reverseStr;
// .
strOp(ref str) ;

414

I. #

Console.WriteLine(" : " + str);


Console.WriteLine();
//
// .
strOp -= replaceSp;
strOp += removeSp;
str = " ."; //
// .
// .
strOp(ref str);
Console.WriteLine(" : " + str);
Console.WriteLine();
:
.
.
: .--
.
.
: .
Main() . , strOp,
null-. . , removeSpaces ()
r e v e r s e ( ) . :
strOp = repiaceSp;
strOp += reverseStr;

strOp replaceSp. , "+=", r e v e r s e S t r .


s t r o p ,
.

I strOp -== replaceSp;
replaceSp,
1 strOp += removeSp;
removeSp.
StrOp .
, .
, , , , " ". , .

System.Delegate
,
System. Delegate. ,
System. Delegate. .
15.

415


, ""
, " ?". ,
. -,
, .
-, ,
. , ,
. , (
Windows Paint). ,
. , ""
. .

#: (event). .
. ,
, .
, .
: .
,
event. :
event _ ;
_ ,
, .
.
// .
using System;
// ,
delegate void MyEventHandler();
// ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();

class EventDemo {
// ,
static void handler() {
416

I. #

Console.WriteLine(" .");
public static void Main() {
MyEvent evt = new MyEvent();
// handler() ,
evt.SomeEvent += new MyEventHandler(handler);
// ,
evt.OnSomeEvent();

:
1 .
, , . .
:
I d e l e g a t e void MyEventHandler();
. ,
. ,
. , void.
MyEvent. ,
, SomeEvent:
I p u b l i c event MyEventHandler SomeEvent;
. .
, MyEvent OnSomeEvent (),
, . ( ,
, .) , SomeEvent.
if(SomeEvent != null)
SomeEvent();

, , SomeEvent null-. , , ,
, OnSomeEvent () . null-, , 11-.
EventDemo h a n d l e r (). , , .
, Main() MyEvent,
h a n d l e r () .
MyEvent evt = new MyEvent();
// h a n d l e r ( ) ,
evt.SomeEvent += new MyEventHandler(handler);
,
"+=". , "+=" " - = " . h a n d l e r () ,
15.

417

. , "" ,
.
I/ .
evt.OnSomeEvent();

OnSomeEvent () . , ,
, .


.
,
.
// ,
// .
using System;
// ,
delegate void MyEventHandler();
// ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();

class X {
public void XhandlerO {
Console.WriteLine(",

X.");

class Y {
public void YhandlerO {
Console.WriteLine(", Y . ) ;

class EventDemo {
static void handler() {
Console.WriteLine(
", EventDemo.");
public static
MyEvent evt
X xOb = new
Y yOb = new

418

void Main() {
= new MyEvent();
X();
Y () ;

I. #

// ,
evt.SomeEvent += new MyEventHandler(handler);
evt.SomeEvent += new MyEventHandler(xOb.Xhandler);
evt.SomeEvent += new MyEventHandler(yOb.Yhandler);
// ,
evt.OnSomeEvent();
Console.WriteLine();
// .
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
}
}
:
, EventDemo.
, X.
, Y.
, EventDemo.
, Y.
X Y, , MyEventHandler.
, .
, Y .
, ,
,
.
.


,
,
, . , ( ). , . ,
, , . "" "" , , , . .
, . , X . X.
/*

. */
u s i n g System;
15.

419

// ,
delegate void MyEventHandler();
// ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();

class X {
int id;

public X(int x) { id = x; }
// ,
// ,
public void Xhandler() {
Console.WriteLine(" " + id);

class EventDemo {
public static void Main() {
MyEvent evt = new MyEvent();
X ol = new X(l) ;
X o2 = new X(2) ;
X o3 = new X(3);
evt.SomeEvent += new MyEventHandler(ol.Xhandler);
evt.SomeEvent += new MyEventHandler(o2.Xhandler);
evt.SomeEvent += new MyEventHandler(o3.Xhandler);
// ,
evt.OnSomeEvent() ;

:
I 1
I 2
1 3
, .
, ,
, .

/*

. */
using System;
// .
420

I. #

delegate void MyEventHandler();


// ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();
}
class X {
/* ,
. */
public static void XhandlerO {
Console.WriteLine(" .");

class EventDemo {
public static void Main() {
MyEvent evt = new MyEvent();
evt.SomeEvent += new MyEventHandler(X.Xhandler);
// ,
evt.OnSomeEvent();

:
I .
, .
h a n d l e r () X, SomeEvent OnSomeEvent ().


, . ,
, , , ,
. ,
.
, , .
, , , .
,
event-, .
. :
event _ __ {
add

15.

421

// .
remove {
// .
}
: add remove.
add , "+="
, remove , " - = " .
add remove , , . , , value. add remove .
, , .
. . , .
// .
using System;
// ,
delegate void MyEventHandler();
//
// ,
class MyEvent {
MyEventHandler[] evnt = new MyEventHandler[3];
public event MyEventHandler SomeEvent {
// ,
add {
int i ;
for(i=0; i < 3;
i f ( e v n t [ i ] == null) {
evnt[i] - value;
break;
if

(i == 3)
Console.WriteLine(
" .");

// ,
remove {
int i ;
for(i=0; i < 3;
if(evnt[i] == value)
evnt[i] = null;
break;

422

I. C#

if (i ~ 3)
Console.WriteLine(" .");

// ,
public void OnSomeEvent() {
for(int i=0; i < 3; i++)
if(evnt[i] !== null) evnt[i]();

// ,
// MyEventHandler.
class W {
public void WhandlerO {
Console.WriteLine(" W.")

class X {
public void XhandlerO {
Console.WriteLine("

X.");

class Y {
public void YhandlerO {
Console.WriteLine(" Y . " ) ;

class Z {
public void ZhandlerO {
Console.WriteLine(" Z.")

class EventDemo {
public static void MainO {
MyEvent evt = new MyEvent();
W wOb = new W();
X xOb = new X();
Y yOb = new Y () ;
Z zOb = new Z () ;
// .
Console.WriteLine(" .");
evt.SomeEvent += new MyEventHandler(wOb.Whandler);
evt.SomeEvent += new MyEventHandler(xOb.Xhandler);
evt.SomeEvent += new MyEventHandler(yOb.Yhandler);
// ,
evt.SomeEvent += new MyEventHandler(zOb.Zhandler);
Console.WriteLine();
// .

15.

423

evt.OnSomeEvent() ;
Console.WriteLine() ;
// .
Console.WriteLine(" xOb.Xhandler.");
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
Console.WriteLine() ;
// .
Console.WriteLine(
" xOb.Xhandler.");
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
Console.WriteLine();
// Zhandler.
Console.WriteLine(" zOb.Zhandler.")
evt. SomeEvent += new MyEventHandler (zOb. Z*handler) ;
evt.OnSomeEvent();

:
.
.
W.
X.
Y.
xOb.Xhandler.
W.
Y.
xOb.Xhandler.
.
W.
Y.
zOb.Zhandler.
W.
Z.
Y.
. MyEventHandler. MyEvent,
, evnt.
I MyEventHandler[] evnt = new MyEventHandler[3];
, . evnt null-
.
event-, .
424

I. #

public event MyEventHandler SomeEvent {


// ,
add {
int i ;
for(i=0; i < 3;
if(evnt[i] == null) {
evnt[ij = value;
break;
if

(i == 3)
^
Console.WriteLine(
" .");

// ,
remove {
int i;
for(i=0; i < 3; i
if(evnt[i] == value) {
evnt[i] = null;
break;
}
if (i == 3)
Console.WriteLine(" .");

add-,
( value) evnt. ,
. evnt
, .
remove-, evnt , value.
, n u l l , .
OnSomeEvent (). evnt, .
,
. , . event-, , . ,
, ,
.


. "" . . . , 15.

425

add remove,
. sealed. , .. .


.NET Framework
# . .NET Framework , Microsoft .
,
. , . EventArgs ,
. , .NET-
:
void handler(object source, EventArgs arg) {
source .
EventArgs ,
.
EventArgs , ; , , .
, EventArgs
Empty, , .
, .NET- .
// .NET- .
using System;
// , EventArgs.
c l a s s MyEventArgs : EventArgs {
p u b l i c i n t eventnum;
}

// .
delegate void MyEventHandler(object source,
MyEventArgs arg);
// ,
class MyEvent {
s t a t i c i n t count = 0;
public event MyEventHandler SomeEvent;
// SomeEvent-.
public void OnSomeEvent() {
MyEventArgs arg = new MyEventArgs();
if(SomeEvent

426

!= null) {

I. #

arg.eventnum = count++;
SomeEvent(this, arg);

class X {
public void handler(object source, MyEventArgs arg) {
Console.WriteLine(" " + arg.eventnum +
11
X . " ) ;
Console.WriteLine(" " +
source + " . " ) ;
Console.WriteLine();

class Y {
public void handler(object source, MyEventArgs arg) {
Console.WriteLine(" " + arg.eventnum +
" Y.");
Console.WriteLine(" " +
source + " . " ) ;
Console.WriteLine();

class EventDerno
public static
X obi - new
Y ob2 = new
MyEvent evt

{
void Main() {
X() ;
();
new MyEventO;

// handler() ,
evt. SomeEvert +-- new MyEventHandler (obi .handler) ;
evt.SomeEvent +~ new MyEventHandler(ob2.handler);
// ,
evt.OnSomeEvent();
evt.OnSomeEvent();

:
0 X.
MyEvent.
0 Y.
MyEvent.
1 X.
MyEvent.
I Y.
MyEvent.
MyEventArgs EventArgs.
MyEventArgs "" eventnum.

15.

427

.NET Framework MyEventHandler


. , ,
EventArgs EventArgs. MyEventArgs.

EventHandler
EventArgs .
.NET Framework , EventHandler. , . EventHandler.
// EventHandler.
using System;
// ,
class MyEvent {
public event EventHandler SomeEvent; //
// EventHandler.
//
// SomeEvent-.
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent(this, EventArgs.Empty);

class EventDemo {
static void handler(object source, EventArgs arg) {
Console.WriteLine(" .");
Console.WriteLine(" " +
source + " . " ) ;
public static void Main() {
MyEvent evt = new MyEvent();
// handler() ,
evt.SomeEvent +- new EventHandler(handler);
// ,
evt.OnSomeEvent();

EventArgs - EventArgs.Empty.
:
I .
I MyEvent.

428

I. #

:
, Windows. ,
, .
#, . ,
, .
.
Windows-, , ,
.
. KeyPress, OnKeyPress ().
// ,
// .
using System;
// EventArgs,
// ,
class KeyEventArgs : EventArgs {
public char ch;
}

// .
delegate void KeyHandler(object source, KeyEventArgs arg);
// ,
// ,
class KeyEvent {
public event KeyHandler KeyPress;
//
// - ,
public void OnKeyPress(char key) {
KeyEventArgs k = new KeyEventArgs();
if(KeyPress != null) {
k.ch = key;
KeyPress(this, k ) ;

// , ,
class ProcessKey {
public void keyhandler(object source, KeyEventArgs arg) {
Console.WriteLine(
" : " + arg.cn);

15.

429

// ,
//
,
class CountKeys {
public int count = 0 ;
public void keyhandler(object source, KeyEventArgs arg) {
count++;

// KeyEvent.
c l a s s KeyEventDemo {
p u b l i c s t a t i c void MainO {
KeyEvent kevt = new KeyEvent();
ProcessKey pk = new ProcessKey();
CountKeys ck = new CountKeys();
char ch;
kevt.KeyPress += new KeyHandler(pk.keyhandler);
kevt.KeyPress +~ new KeyHandler(ck.keyhandler);
Console.WriteLine(" . " +
"
.");
do {
ch = (char) Console.Read();
kevt.OnKeyPress(ch);
} while(ch !- ' . ' ) ;
Console.WriteLine(" " +
k.count + " .");

:
. .
.
:
:
:
:
: .
5 .
KeyEventArgs, .
KeyHandler ,
. KeyEvent.
: ProcessKey
CountKeys. ProcessKey keyhandler (), . CountKeys
. MainO
KeyEvent. ProcessKey CountKeys, a
keyhandler () ,
kevt.KeyPress. , kevt .OnKeyPress ( ) , .

430

I. #

#-,
. ,
.


2, #: . , # . ,
, ,
.
. .
,
. , ,
, , . .NET Framework ( #-)
System. :
using System;
^
14, - , System, System. 10.
, System, #.
, , , , , , .
" " ,
. ,
Finder, ,
Finder , .
, , , , .


namespace.
:
namespace {
//
}
. ,
, . , .
, , , , .
432

I. #

namespace,
Counter. , , Count Down.
// .
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n) {
val = n;
}
public void reset(int n) {
val = n;
public int count() {
if(val > 0) return val--;
else return 0;
)

CountDown , Counter.
, Counter.
// .
using System;
// ,
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) { val = n; }
public void reset(int n) {
val = n;
}
public int count() {
if(val > 0) return v a l ;
else return 0;

c l a s s NSDemo {
p u b l i c s t a t i c void Main() {
Counter.CountDown cdl = new Counter.CountDown(10);
int i;
do {
16. ,

433

i = cdl.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();
Counter.CountDown cd2 = new Counter.CountDown(20);
do {
i = cd2.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();

Cd2.reset (4);
do {
i = cd2.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();

:
1 10 9 8 7 6 5 4 3 2 1 0
1 20 19 18 17 16 15 14 13 12 11 10 9 8 7 5 4 3 2 1 0
1 4 3 2 1 0
. -,
CountDown Counter,
CountDown, , Counter.
1 Counter.CountDown c d l = new Counter.CountDown(10);
Counter , (
) ( "-") . ,
c d l . count () ,
:
I i = cdl.count();


, , , , . ,
jCountDown, Counter2.
// ,
// .
using System;
// ,
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
434

I. #

public void reset(int n) {


val = n;
public int count() {
if(val > 0) return v a l ;
else return 0;

// ,
namespace Counter2 {
/* CountDown
Counter2
, Counter. */
class CountDown {
public void count() {
Console.WriteLine(" count() " +
" Counter2.");

class NSDemo {
public static void Main() {
// CountDown
// Counter.
Counter.CountDown cdl = new Counter.CountDown(10);
// CountDown
// Counter2.
Counter2.CountDown cd2 = new Counter2.CountDown();
int i;
do {
i = cdl.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();
cd2.count();

:
10 9 8 7 6 5 4 3 2 1 0
count() Counter2.

, CountDown
Counter CountDown,
Counter2, .
, ,
, ,
.

16. ,

435

u s i n g
" 2,
,
, . using. using, #- System,
. , u s i n g , .
using. :
u s i n g ;
, . u s i n g . , , () ,
. u s i n g ,
.. .
, , u s i n g .
// .
using System;
// Counter,
using Counter;
// ,
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
public void reset(int n) {
val = n;
public int count() {
if(val > 0) return v a l ;
else return 0;

class NSDemo {
public static void Main() {
// CountDown
// .
CountDown cdl = new CountDown(10);
436

I. #

int

i;

do {
i = cdl.count();
Console.Write (i + " " ) ;
} while(i > 0);
Console.WriteLine();
CountDown cd2 = new CountDown(20);
do {
i = cd2.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();
cd2.reset(4);
do {
i = cd2.count();
Console.Write (i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();

:
.
,
. ,
System Counter.

using
using :
using = ;
,
.
, , Count
Counter.CountDown.
// .
using System;
// Counter.CountDown.
using Count = Counter.CountDown;
// .
namespace Counter {
// .
class CountDown {
int val;

public CountDown(int n) {
val = n;
}
p u b l i c v o i d r e s e t ( i n t n) {

16. ,

437

val

= n;

public int count() {


if(val > 0) return v a l ;
else return 0;

class NSDemo {
public static void Main() {
// Count
// Counter.CountDown.
Count cdl = new Count(10);
int i;
do {
i = cdl.count();
Console.Write(i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();
Count cd2 = new Count(20);
do {
i = cd2.count() ;
Console.Write(i + " " ) ;
} while(i > 0) ;
Console.WriteLine();
cd2.reset (4);
do {
i = cd2.count();
Console.Write (i + " " ) ;
} while(i > 0 ) ;
Console.WriteLine();

Count Counter.CountDown, CountDown . ,



I Count cdl = new Count(10);
CountDown.


.
. , Counter. CountDown, Countup.
Counter .

ll ,
using System;

438

I. #

// "" Counter,
using Counter;
//
// Counter,
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
public void reset(int n) {
val - n;
public int count() {
if(val > 0) return v a l ;
else return 0;

//
// Counter,
namespace Counter {
// ,
class CountUp {
int val;
int target;
public int Target {
get{
return target;

public CountUp(int n) {
target = n;
val = 0;
public void^ reset (int n) {
target = n;
val = 0;
public int count() {
if(val < target) return val++;
else return target;

class NSDemo {
public static void Main() {

16. ,

439

CountDown cd = new CountDown(10)


CountUp cu = new CountUp(8);
int i;
do {
i = cd.count();
Console.Write (i + " " ) ;
} while (i > 0 ) ;
Console.WriteLine();
do {
i = cu.count();
Console.Write(i + " " ) ;
} while(i < cu.Target);

:
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8

.
I using Counter;
"" .
CountDown CountUp ,
. , Counter
, .


. :
// .
using System;
namespace NS1 {
class ClassA {
public ClassA() {
Console.WriteLine(" ClassA.");
}
}
namespace NS2 { // ,
class ClassB {
public ClassB() {
Console.WriteLine(" ClassB.");

c l a s s NestedNSDemo {
p u b l i c s t a t i c v o i d Main() {
N S 1 . C l a s s A a= new N S 1 . C l a s s A ( ) ;
// N S 2 . C l a s s B b = new N S 2 . C l a s s B ( ) ; // ! ! !

440

I. #

// NS2 .
NS1.NS2.ClassB b = new NS1.NS2.ClassB(); //
// .

:
ClassA.
ClassB.

NS2 NS1. , ClassB ,


: NS1, NS2. NS2 .
, .
,
. ,
namespace OuterNS {
namespace InnerNS {

:
namespace OuterNS.InnerNS {


,
, .
, . ( , )
( ), .
.
, ,
.

# , .
, , . "" C++,
# , C++. ,
, , (preprocessor). ,
.
16. ,

441

# :
#define

#elif

#else

#endif

#endregion,

terror

#if

#line

#region

#undef

#warning

" # " . , .
, # , ,
. ,
. .
# define
#def i n e , . # i f # e l i f ,
. #def i n e :
#define
, .
#def i n e , .
, EXPERIMENTAL,
:
1 #define EXPERIMENTAL
^SB^SSiil

C/C++ #define
, ,
, .
#define C# . # #define .

#if #endif
# i f #endif , , . , . .
, #def ine, .
# i f :
#if _
_
#endif
, # i f (_), , , #endif
( _), . .
#endif tif-.

442

I. #

.
: !, ==, !=, && | |.
.
#if, #endif #def ine.
// #if, #endif
// tdefine.
#define EXPERIMENTAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#endif
Console.WriteLine(
" .");

:
.
.

#define
EXPERIMENTAL. # i f
EXPERIMENTAL , ( )
WriteLine ()-. EXPERIMENTAL
, WriteLine ()- , # i f .
WriteLine () - ,
# if-. , # i f . :
// .
#define EXPERIMENTAL
#define TRIAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#endif
#if EXPERIMENTAL && TRIAL
Console.Error.WriteLine(
" .");
#endif

16. ,

443

Console.WriteLine(
" .")

:
.
.
.

, EXPERIMENTAL TRIAL. WriteLine () - ,


.

#else #elif
# e l s e else- #, .. , # i f . .
// #else.
#define EXPERIMENTAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#else
Console.WriteLine(" -.");
#endif
#if EXPERIMENTAL && TRIAL
Console.Error.WriteLine(
" .");
#else
Console.Error.WriteLine(
" .");
#endif
Console.WriteLine(
" .");

:
.
.
.

TRIAL , #1-
.
, # e l s e
#if-, telse-, #if
#endif.
444

I. #

# e l i f " " i f - e l s e- i f - . # e l i f .
, (_) , #elif- . telif-. #el i f - :
#if _
_
# e l i f _
_
# e l i f 1_
_
# e l i f _
_
# e l i f _

#endif
:
// #elif.
#define RELEASE
using Systemsclass Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#elif RELEASE
Console.WriteLine(" -.");
#else
Console.WriteLine(
" .");
#endif
#if TRIAL && !RELEASE
Console.WriteLine(" .");
#endif
Console.WriteLine(
" .");

:
-.
.

#undef
#undef , . #undef :
#undef
16. ,

445

:
#define SMALL
#if SMALL
// ...
#undef SMALL
// SMALL .
#undef SMALL
.
#undef , .
# error
# e r r o r . .
t e r r o r :
terror ___
t e r r o r __
. ,
I t e r r o r !
, " !".
#warning
twarning t e r r o r , ,
. .
twarning :
twarning _
#line
t l i n e , t l i n e .
.
t l i n e :

t l i n e "_"

, , ___
, .
t l i n e .
, d e f a u l t :
| t l i n e default

446

I. #

# region # end region


#region #endregion ,
(IDE) Visual Studio. :

#region _
// _

#endregion
, __ .


internal
#-
(assembly), .
.NET-. Microsoft, "
.NET Framework." , .
.
.
(manifest). .
, , ,
" ".
, , .
, .
, Microsoft Intermediate
Language (MSIL). , , .
, # , ( ) . , , #, ,
. , .
.
( .NET-,
#.) # : i n t e r n a l . - .

i n t e r n a l
p u b l i c , p r i v a t e p r o t e c t e d ,
, # i n t e r n a l . , ,
, . , , i n t e r n a l , , - .
i n t e r n a l .
16. ,

447

i n t e r n a l ,
. i n t e r n a l
.
i n t e r n a l
p r o t e c t e d . p r o t e c t e d i n t e r n a l , . , p r o t e c t e d i n t e r n a l ,
. .
i n t e r n a l .
// internal.
using System;
class InternalTest {
internal int x;
class InternalDemo {
public static void Main() {
InternalTest ob = new InternalTest();
ob.x = 10; // :

Console.WriteLine(" ob.x: " + ob.x);

I n t e r n a l T e s t
i n t e r n a l . , ,
InternalDemo, .

448

I. #

#: , . , . ,
. , , .
,
, .
. , , .

. , .


(runtime type identification RTTI)
,
. , , . RTTI , ,
, . ( ).
# ,
: i s , as typeof.
.

i s
i s ,
. :
i s
.
( ) , .
. , , ,
.
i s .
// i s .
using System;
c l a s s A {}
c l a s s : A {}

class Usels {
public static void Main() {
A a = new A () ;
b = new ();

450

I. #

if(a is A) Console.WriteLine(" A . " ) ;


if(b is A)
Console.WriteLine(" b , " +
" . " ) ;
if(a is )
Console.WriteLine(" , " +
" .")
if(b is ) Console.WriteLine(" b . " ) ;
if(a is object) Console.WriteLine(" .");

:
.
b , .
b .
-- .

, bie . :
i f ( b i s A)
Console.WriteLine(" b , " +
" . " ) ;

i f- , b
, . , b . .

i f ( a i s )
Console.WriteLine(" , " +
" . " ) ;

if- , ,
. , .

as

, , .
as, :
as
, , . .
.
a s i s .
, , , i s :
// i s
// .
using System;
c l a s s A {}
c l a s s : {}

17. ,

451

class CheckCast {
public static void Main() {
A a = new A ( ) ;
b = new ();
// , .
if(a is ) //
// ,
b = () ;
else //
// ,
b = null;
if(b==null)
Console.WriteLine(
" b = () .");
else
Console.WriteLine(
" b = () .")

:
b = () .
,
, , if. ,
.
, . as
, .
// a s .
using System;
class A {}
class : A {}
class CheckCast {
public static void Main() {
A a = new A();
b = new () ;
b = a as ; // ,
// .
if(b==null)
Console.WriteLine(" " +
"b = () .");
else
Console.WriteLine(
" b = () .");

:
b = () .

452

I. #

as ,
, , , .

typeof
as i s , ( -) .
. # typeof.
System.Type . , .
typeof :
typeof()
, . , typeof, , .
-, , , , . , , . , , ,
: FullName, I s C l a s s I s A b s t r a c t .
FullName . I s C l a s s t r u e , . I s A b s t r a c t t r u e , .
// typeof.
using System;
using System.10;
class UseTypeof {
public s t a t i c void Main() {
Type t = typeof(StreamReader);
Console.WriteLine(t.FullName);
if (t. IsClass) Console. WriteLine (" ") ;
if(t.IsAbstract)
Console.WriteLine(
" .");
else Console.WriteLine(" .");

:
System.10.StreamReader
.
.

StreamReader.
, , .

17. ,

453


, (reflection) #,
.
: , , ,
. "
" , () , . , , , .
, , .NET Reflection API,
System.Reflection. , , , :
I using S y s t e m . R e f l e c t i o n ;

: system. Type
System. , "" , . ,
. System.Reflection.Memberlnf.
Member Info ,
:
D e c i a n n g T y p e

MemberTypes MemberType

s t r i n g Name

Type ReflectedType

, MemberType MemberTypes.
MemberTypes , , . :
MemberTypes.Constructor
v
MemberTypes.Method
MemberTypes.Field
MemberTypes.Event
MemberTypes.Property
, , MemberType. , MemberType MemberTypes .Method, ,
.
Memberlnf : GetCustomAttributes ()
I sDefined (). .
, Memberlnf ,
"". , .

454

I. #

C o n s t r u c t o r i n f [ ] G e t C o n s t r u c t o r s ()

E v e n t l n f [ ] G e t E v e n t s ()

F i e i d i n f [ ] G e t F i e i d s ()

M e m b e r i n f [ ] GetMembers ()

M e t h o d i n f [ ] G e t M e t h o d s ()

P r o p e r t y i n f [ ] G e t P r o p e r t i e s ()

,
.

Assembly Assembly

TypeAttributes

Attributes

BaseType

s t r i n g FuliName

bool isAbstract

bool i sArray

bool isClass

b o o l isEnum

s t r i n g Namespace


, . , , , ,
. , , .
Reflection API , . ( Reflection API !) Reflection API , , ,
, .
: , , .


Type- , . GetMethods ().
:
Methodinf[] GetMethods()

17. ,

455

GetMethods () Methodlnf , , . Methodlnf


System. Reflection.
Methodlnfo MethodBase, ,
, Memberlnfo. , , . , , Name.
Methodlnfo: ReturnType GetParameters ().
ReturnType, , ,
.
GetParameters () , .
:
Parameterlnfo[] GetParameters()
Parameterlnfo.
Parameterlnfo ,
. :
Name, , ,
ParameterType, .
.
,
, MyClass. , ,
.
// .
using System;
using System.Reflection;
class MyClass {
int x;
int y;
public MyClass(int i, int j) {
x = i;
= j;
}
public int sum() {
return x+y;
}
public bool isBetween(int i) {
if(x < i && i < y) return true;
else return false;
public void s e t ( i n t a, i n t b) {
x = a;
= b;
}

public void set(double a, double b) {


x = (int) a;
= (int) b;
456

I. #

public void show() {


Console.WriteLine(" x: {0}, y: {1}", x, y ) ;

class ReflectDemo {
public static void Main() {
Type t = typeof(MyClass); // Type-,
// MyClass.
Console.WriteLine(
" , " + t.Name);
Console.WriteLine();
Console.WriteLine("

" ) ;

Methodlnfo[] mi = t.GetMethods();
// , MyClass.
foreach(Methodinf m in mi) {
// , ,
/ / .
Console.Write("
" + m.ReturnType.Name +
11
" + m.Name + " (") ;
// .
'~
Parameterlnfo[] pi = m.GetParameters();
for(int i=0; i < pi.Length; i
Console.Write(pi[i].ParameterType.Name +
11
" + pi[i] .Name) ;
if(i+l < pi.Length) Console.Write(", " ) ;

Console.WriteLine(")");
Console.WriteLine();

:
, MyClass
:
Int32 G e t H a s h C o d e O
Boolean Equals(Object
String

obj)

ToStringO

Int32 sum()
Boolean isBetween(Int32 i)
Void set(Int32 a, Int32 b)

17. ,

457

Void set(Double a, Double b)


Void show()
Type GetType()
, , MyClass,
, o b j e c t . ,
# o b j e c t . ,
.NET-. ,
s e t () . : s e t ( ) .
i n t , double.
. , ,
MyClass public- public-, s e t (). Main () , MyClass:
Type t = typeof(MyClass); // Type-,
// MyClass.

t Reflection API, , MyClass. :


I MethodlnfoU mi = t . G e t M e t h o d s ( ) ;
f oreach, , :
// , ,
/ / .
Console.Write(
" + m.ReturnType.Name +
" " + m.Name + "(") ;
// .
Parameterlnf [ ] pi = m.GetParameters () ;
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name +
" " + pi[i].Name);
if(i+l < pi.Length) Console.Write(", " ) ;
}
GetParameters () p i .
for p i
. ,
, .. MyClass.

GetMethods ()
GetMethods () ,
. :
Methodlnfo[] GetMethods(BindingFlags flags)
, . BindingFlags .
:

458

I. #


DeciaredOnly
instance
NonPublic
Public
static

, .


--
public-
static-

.
P u b l i c NonPublic I n s t a n c e
S t a t i c . GetMethods () .
BindingFlags-, GetMethods ( ) , ,
. ,
, . , , GetMethods () :
// ,
// MyClass.
Methodlnfo[] mi = t.GetMethods(BindingFlags.DeciaredOnly |
BindingFlags.Instance |
BindingFlags.Public) ;
:
, MyClass
:
Int32 sum()
Boolean isBetween(Int32 i)
Void set(Int32 a, Int32 b)
Void set(Double a, Double b)
Void show()
, ,
MyClass.


, , .
Invoke , Methodlnfo.
:
object Inyoke(object ob, o b j e c t [ ] args)
ob , . static- ob n u l l . , ,
args. , args n u l l . args ,
. , , args , , , .
17. ,

459

invoke ()
Methodlnfo, GetMethods (). :
// .
using System;
using System.Reflection;
class MyClass {
int x;
int y;
public MyClass(int i, int j) {
x = i;
= j;
}
public int sum() {
return x+y;
}
public bool isBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
}
public void set (int a, int b) {
Console.Write(" set(int, int). " ) ; .
x = a;
= b;
show();
}
// set.
public void set(double a, double b) {
Console.Write(" set(double, double). " ) ;
x = (int) a;
= (int) b;
show();
p u b l i c v o i d show() {
Console.WriteLine(
" x:

{0},

{1}",

x,

);

class InvokeMethDemo {
public static void Main() {
Type t = typeof(MyClass);
MyClass reflectOb = new MyClass(10, 20);
int val;
Console.WriteLine(" ,
t.Name);
Console.WriteLine() ;
M e t h o d l n f o [ ] mi = t . G e t M e t h o d s ( ) ;

460

I. #

// ,
foreach(Methodlnfo m in mi) {
// .
Parameterlnf[] pi = m.GetParameters();
if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType == typeof(int)) {
object [] args = new object[2];
args[0j = 9;
args[l] = 18;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType typeof(double)) {
object[] args = new object[2];
args[0] = 1.12;
args[l] = 23.4;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("sum")==0) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(
" sum " + val)
}
else if(m.Name.CompareTo("isBetween")==0) {
object[] args = new object[1];
args[0J = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine("14 . " ) ;
}
else if(m.Name.CompareTo("show")==0) {
m.Invoke(reflectOb, null);

"
, MyClass
sum 30
14 .
s e t ( i n t , i n t ) . : 9, : 18
set(double, double). : 1, : 23
: 1, : 23
, . . foreach
. , i f /else-,
. s e t ():
if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType == typeof(int)) {
object[] args = new object[2];
args[0] = 9;
args[l] = 18;
m.Invoke(reflectOb, args);

17. ,

461

e l s e if(m.Name.CompareTo("set")==0 &&
p i [ 0 ] . P a r a m e t e r T y p e typeof(double))
o b j e c t [ ] a r g s = new o b j e c t [ 2 ] ;
args[0] = 1.12;
a r g s [ l ] = 23.4;
m.Invoke(reflectOb,
args);

s e t , ,
s e t ( ) . ,
s e t ( i n t , i n t ) , a r g s int-
s e t ( ) . s e t ( )
double.


,
( MyClass),
MyClass . ,
. , . . , .
, .
, G e t C o n s t r u c t o r s () . :
Constructorlnf[] GetConstructors()
C o n s t r u c t o r l n f o ,
.
C o n s t r u c t o r l n f o MethodBase,
Member Info. C o n s t r u c t o r l n f o
.
GetParameters ( ) , , . GetParameters ( ) ,
Methodlnf .
, , Invoke ( ) , C o n s t r u c t o r l n f o . Invoke () :
object Invoke(object[]
args)
, , args. , args null-. args . invoke ()
.

MyClass:
// .
using System;
using System.Reflection;

462

I. #

class MyClass {
int x;
int y;
public MyClass(int i) {
Console.WriteLine(
" MyClass(int). " ) ;
x = = i;
public MyClass(int i, int j) {
Console.WriteLine(
" MyClass(int, int). " ) ;
x = i;
= j;
show();
public int sum() {
return x+y;
public bool isBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
public void set(int a, int b) {
Console.Write(" set(int, int). " ) ;
x = a;
= b;
show () ;
// set().
public void set(double a, double b) {
Console.Write(" set(double, double). ") ;
x = (int) a;
= (int) b;
show();
public void show() {
Console.WriteLine(
" : {0}, : {1}", x, )

c l a s s InvokeConsDemo {
p u b l i c s t a t i c void Main() {
Type t = typeof(MyClass);
int val;
// .
Constructorinf[] ci = t.GetConstructors();
Console.WriteLine(" : " ) ;

17. ,

463

foreach(Constructorinf in ci) {
// .
Console.Write("
" + t.Name + " ( " ) ;
// .
Parameterlnf[] pi = .GetParameters();
for(int i=0; i < pi.Length;
Console.Write(pi[i].ParameterType.Name +
" " + pi[i].Name);
if(i+l < pi.Length) Console.Write(", " ) ;
Console.WriteLine(")");
}
Console.WriteLine();
// ,
int x;
for(x=0; x < ci.Length; x++) {
Parameterlnf[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;
if(x == ci.Length) {
Console.WriteLine(
" .");
return;
}
else
Console.WriteLine(
" .\");
// .
object[] consargs = new object[2];
consargs[0] = 10;
consargs [1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Console.WriteLine(
" reflectOb.");
Console.WriteLine();
Methodlnfo[] mi = t.GetMethods();
// .
foreach(Methodinf m in mi) {
// .
Parameterlnf[] pi = m.GetParameters();
if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType == typeof(int)) {
// set(int, int).
object[] args = new object[2];
args[0] = 9;
args [1] = 18;
m.Invoke(reflectOb, args);

464

I. #

else if (m.Name.CompareTo ("set")0 &&


pi[0].ParameterType == typeof(double)) {
// set(double, double).
object[] args = new object[2];
args[0] = 1.12;
args[l] = 23.4;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("sum")==0) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(
" sum() " + val);
}
else if(m.Name.CompareTo("isBetween")==0) {
object[] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine("14 . " ) ;
}
else if(m.Name.CompareTo("show")==0) {
m.Invoke(reflectOb, null);

:
:
MyClass(Int32 i)
MyClass(Int32 i , Int32 j)
.
MyClass(int,
: 10, : 20

int).

reflectOb.

sum() 30
14 .
s e t ( i n t , i n t ) . : 9, : 18
set(double, double). : 1, : 23
: 1, : 23
,
MyClass. :
I Constructorlnf[] ci = t.GetConstructors();
, . , , :
for(x=0; < ci.Length; x++) {
Parameterlnfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;

( ), , :
17. ,

465

// .
object[] consargs = new o b j e c t [ 2 ] ;
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);

Invoke () r e f l e c t O b
MyClass.
, ,
int-, , MyClass.
.



MyClass, : MyClass.

MyClass, , MyClass,
typeof ,
( ).
,
,
.
16, , ., . Reflection API , . , ,
" " . . , , , .
, , , , . , .

Assembly. Assembly p u b l i c . Assembly , .
, LoadFromO . :
s t a t i c Assembly LoadFrom(string _)
_ .
Assembly, GetTypes (). :
[] GetTypes()
, .

, . .
MyClasses.cs :
I // .
| // MyClasses.cs.
466

I. #

using System;
class MyClass {
int x;
int y;
public MyClass(int i) {
Console.WriteLine(
" MyClass(int).
x = = i;
show();
public MyClass(int i, int j) {
Console.WriteLine(
" MyClass(int, int). ")
x = i;
= j;
show();
public int sum() {
return x+y;
public bool isBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
public void set(int a, int b) {
Console.Write(" set(int, int). " ) ;
x = a;
= b;
show () ;
// set.
public void set(double a, double b) {
Console.Write(" set(double, double). " ) ;
x = (int) a;
= (int) b;
show();
public void show() {
Console.WriteLine(
" : {0}, : {1}", x, ) ;

class AnotherClass {
string remark;
public AnotherClass(string str) {
remark = str;

17. ,

467

public void show() {


Console.WriteLine(remark);

class Demo {
public static void Main() {
Console.WriteLine(" .");

MyClass,
. , AnotherClass Demo.
, , ,
. , MyClasses.exe.
, .
,
^lyClasses.exe.
/* ,
, . */
using System;
using System.Reflection;
class ReflectAssemblyDemo {
public static void Main() {
int val;
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
// , MyClasses.exe.
[] alltypes = asm.GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(": " + temp.Name);
Console.WriteLine();
// ,
// MyClass.
Type t = alltypes[0]; //
// .
Console.WriteLine(": " + t.Name);
// .
Constructorlnfo[] ci = t.GetConstructors();
Console.WriteLine(" : " ) ;
foreach(Constructorlnfo in ci) {
// .
Console.Write("
" + t.Name + " ( " ) ;
// .
Parameterlnfo[] pi = c.GetParameters();
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name +
468

I. #

" " + pi[i].Name);


if(i + l < pi.Length) Console.Write(", ") ;
}
Console.WriteLine(")");
}
Console.WriteLine() ;
// ,
int x;
for(x=0; x < ci.Length; x++) {
Parameterlnfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;
}
if(x == ci.Length) {
Console.WriteLine(
" .");
return;
}
else
Console.WriteLine(
" .\n") ;
// .
object[] consargs = new object[2];
consargs[0] = 1 0 ;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Console.WriteLine(
" reflectOb.");
Console.WriteLine();
Methodlnfo[] mi = t.GetMethods();
// .
foreach(Methodlnf m in mi) {
// .
Parameterlnfo[] pi = m.GetParameters();
if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType == typeof(int)) {
// set(int, int).
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("set")==0 &&
pi[0].ParameterType == typeof(double)) {
// set(double, double).
object[] args = new object[2];
args[0] = 1.12;
args[l] = 23.4;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("sum")==0) {

17. ,

469

val = (int) m.Invoke(reflectOb, null);


Console.WriteLine(
" sum() " +
val) ;
}
else if(m.Name.CompareTo("isBetween")==0) {
object[] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine("14 . " ) ;
}
else if(m.Name.CompareTo("show")==0) {
m.Invoke(reflectOb, null);

:
: MyClass
: AnotherClass
: Demo
: MyClass
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)

'

.
MyClass(int, int).
: 10, : 20
reflectOb.
sum() 30
14 .
set(int, int). : 9, : 18
set(double, double). : 1, : 23
: 1, : 23

, , MyClasses.exe. ,
MyClass, .
MyClasses. .
, MyClasses.exe, ,
Main ():
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
// , MyClasses.exe.
Type[] alltypes = asm.GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(": " + temp.Name);

470

I. #

,
.
, -. (dynamic link library DLL), d l l . ,
MyClasses. cs :
I esc / t : l i b r a r y MyClasses.es

MyClasses.dll. DLL-
Main(). - ,
Main (), . Demo Main ().
DLL- .
MyClass DLL-, LoadFromO :
I Assembly asm = Assembly.LoadFrom("MyClasses.dll");


, .
MyClass ,
MyClass. , ( s e t ( ) sum ).
, .
, , . , , , ,
.
, , , MyClasses.exe, MyClass,
.
// MyClass
// .
using System;
using System.Reflection;
class ReflectAssemblyDemo {
public s t a t i c void Main() {
int val;
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
Type[] alltypes = asm.GetTypes();
Type t = a l l t y p e s [ 0 ] ; //
// .
Console.WriteLine(": " + t.Name);
Constructorlnfo[] ci = t.GetConstructors();
// .
17. ,

471

Parameterlnfof] cpi = ci[0].GetParameters();


object reflectOb;
if(cpi.Length > 0) {
object[] consargs = new object[cpi.Length];
// .
for(int n=0; n < cpi.Length; n++)
consargs[n] = 10 + n * 20;
// .
reflectOb = ci[0].Invoke(consargs) ;
} else
reflectOb = ci[0].Invoke(null);
Console.WriteLine(
" reflectOb.");
Console.WriteLine();
// .
Methodlnfo[] mi = t.GetMethods(
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public) ;
// .
foreach(Methodinf m in mi) {
Console.WriteLine(" {0} ", m.Name);
// .
Parameterlnfo[] pi = m.GetParameters();
// ,
switch(pi.Length) {
case 0: //
if(m.ReturnType == typeof(int)) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(" " + val);
}
else if(m.ReturnType == typeof(void)) {
m.Invoke(reflectOb, null);
}
break;
case 1: //
if(pif0].ParameterType == typeof(int)) {
object [] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine(
"14 . " ) ;
else
Console.WriteLine(
"14 . " ) ;
}
break;
case 2: //
if((pi[0].ParameterType == typeof(int)) &&

472

I. #

(pi[1].ParameterType == t y p e o f ( i n t ) ) )
o b j e c t [ ] a r g s = new o b j e c t [ 2 ] ;
a r g s [ 0 ] = 9;
a r g s [ 1 ] = 18;
m.Invoke(reflectOb, a r g s ) ;

e l s e i f ( ( p i [ 0 ] . P a r a m e t e r T y p e == t y p e o f ( d o u b l e ) ) &&
(pi[1].ParameterType == t y p e o f ( d o u b l e ) ) ) {
o b j e c t [ ] a r g s = new o b j e c t [ 2 ] ;
a r g s [ 0 ] = 1.12;
args[1] = 23.4;
m.Invoke(reflectOb, a r g s ) ;
}

break;
}

Console.WriteLine();

: MyClass
M y C l a s s ( i n t ) .
: 10, : 10

'

reflectOb.

sum
20
isBetween
14 .
s e t
s e t ( i n t , i n t ) . : 9, : 18
s e t
s e t ( d o u b l e , d o u b l e ) . : 1, : 23
show
: 1, : 23
. -, ( ) , MyClass.
BindingFlags- GetMethods (). . -, , , . switch-. case-
() () .
.

17. ,

473


# .
, , .. , ,
, .
, , . ,
. .


, System. A t t r i b u t e . , A t t r i b u t e .
A t t r i b u t e , . A t t r i b u t e . , , , E r r o r A t t r i b u t e .
A t t r i b u t e U s a g e . ,
.


, .

. , ,
, . :
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // remark.
public RemarkAttribute(string comment) {
pri_remark = comment;
}
public string remark {
get {
return pri_remark;
}
.
RemarkAttribute.
A t t r i b u t e U s a g e , , RemarkAttribute
. A t t r i b u t e U s a g e , ;
.
RemarkAttribute,
A t t r i b u t e . RemarkAttribute pri_remark, remark, . , .
474

I. #

RemarkAttribute ,
p r i r e m a r k . , ,
RemarkAttribute,
.


, .
, , . ,
RemarkAttribute :
[RemarkAttribute(" .")]
class UseAttrib {
RemarkAttribute,
" .". UseAttrib.
A t t r i b u t e . , :
[Remark(" .")]
class UseAttrib {
Remark.
,
, .


,
. .
GetCustomAttributes ( ) , Memberlnfo
. , ,
:
object[] GetCustomAttributes(bool searchBases)
searchBases t r u e ,
.
, .
GetCustomAttribute , A t t r i b u t e .
:
s t a t i c Attribute GetCustomAttribute(Memberlnfo mi,
Type attrib type)
mi Memberlnfo, ,
.
attribtype.
, ,
. , RemarkAttribute,
:
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
17. ,

475

, . ,
, , , ,
. ,
remark:
I Console.WriteLine(ra.remark);
Rema r kAt t r i b u t e
.
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // remark.
public RemarkAttribute(string comment) {
pri_remark = comment;
}

public string remark {


get {
return pri_remark;
}

[RemarkAttribute(" .")]
class UseAttrib {

class AttribDemo {
public static void Main() {
Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": ") ;
object[] attribs = t.GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine(o);
Console.Write("Remark: " ) ;
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.remark);

:
UseAttrib: RemarkAttribute
Remark: .

476

I. #


Remark At t r i b u t e . , ..
, comment,
RemarkAttribute (), . ,
. # .
, .
, ,
.
.
, . , , :
[ a t trib (__,
___1 = value,
__2 = value, . . . ) ]
( ) . .
.
.
.
, , . RemarkAttribute,
supplement, .
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
s t r i n g pri_remark; // remark.
public s t r i n g supplement; // .
public RemarkAttribute(string comment) {
pri_remark = comment;
supplement = " ";
}

public string remark {


get {
return pri_remark;

, supplement " "


.
. , ,
supplement :
[RemarkAttribute(" .",
supplement = " .")]
class UseAttrib {

17. ,

477

,
RemarkAttribute. . , ,
supplement, . . ,
. . , ,
.
.
, supplement:
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri__remark; / / remark.
public s t r i n g supplement; / / .
public RemarkAttribute(string comment) {
pri_remark = comment;
supplement = " ";
public string remark {
get {
return pri_remark;

[RemarkAttribute(" .",
supplement = " .")]
class UseAttrib {

class NamedParamDemo {
public s t a t i c void Main() {
Type t = typeof(UseAttrib);
Console.Write("

" + t.Name + " : ") ;

object[] a t t r i b s = t.GetCustomAttributes(false);
foreach(object in a t t r i b s ) {
Console.WriteLine(o);
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write("Remark: ") ;
Console.WriteLine(ra.remark);

478

I. #

Console.Write("Supplement: " ) ;
Console.WriteLine(ra.supplement);

:
UseAttrib: RemarkAttribute
Remark: .
Supplement: .

, . ,
jlema r kAt tribute int- priority.
//
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri__remark; // remark.
int pri_priority; // priority,
public string supplement; // .
public RemarkAttribute(string comment) {
pri_remark = comment;
supplement = " ";
}
public string remark {
get {
return pri_remark;

// ,
public int priority {
get {
return prijpriority;
}
set {
prijpriority = value;
}

[RemarkAttribute(
" .",
supplement = " .",
priority = 10)]
class UseAttrib {

class NamedParamDemo {
17. ,

479

public static void Main() {


Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": " ) ;
object[] attribs = t.GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine(o);
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write("Remark: " ) ;
Console.WriteLine(ra.remark);
Console.Write("Supplement: " ) ;
Console.WriteLine(ra.supplement);
Console.WriteLine("Priority: " + ra.priority);

:
UseAttrib: RemarkAttribute
Remark: .
Supplement: .
Priority: 10
( UseAttrib):
[RemarkAttribute(
" .",
supplement = " .",
priority = 10)]

supplement p r i o r i t y . ,
.

-J
# : AttributeUsage, Conditional
Obsolete. .

AttributeUsage
, AttributeUsage ,
. AttributeUsage
System.AttributeUsageAttribute. AttributeUsage :
AttributeUsage(AttributeTargets item)

480

I. #

item , . A t t r i b u t e T a r g e t s ,
:
All
Assembly
Class
Constructor
Delegate
Enum
Event
Field
Interface
Method
Module
Parameter
Property
ReturnValue
Struct
.
, , , AttributeTargets:
1 AttributeTargets.Field | AttributeTargets.Property
AttributeUsage .
AllowMultiple, bool.
,
. I n h e r i t e d , bool.
, .
. AllowMultiple I n h e r i t e d
f a l s e .

Conditional
Conditional, , #. .
, #def ine. . , #if.
C o n d i t i o n a l System. Diagnostics . C o n d i t i o n a l A t t r i b u t e . Conditional, System. Diagnostics.
, .
// Conditional.
#define TRIAL
using System;
using System.Diagnostics;
class Test {
[Conditional("TRIAL") ]
void t r i a l ( ) {
Console.WriteLine(
" , .");
}

[Conditional("RELEASE")]
void release() {
Console.WriteLine(" .");
}

p u b l i c s t a t i c void Main() {
Test t = new T e s t ( ) ;
17. ,

481

t . t r i a l ( ) ; // ,
// TRIAL ,
t . r e l e a s e ( ) ; // ,
// RELEASE .

:
1 , .
, , . , TRIAL, t r i a l ()
r e l e a s e . C o n d i t i o n a l , :
[Conditional
"symbol"]
symbol , , . . , . .
MainO t r i a l (), r e l e a s e ().
TRIAL.
t r i a l (). r e l e a s e () .
RELEASE, r e l e a s e ().
TRIAL, t r i a l () .
. void. , .
o v e r r i d e .

Obsolete

Obsolete
System. O b s o l e t e A t t r i b u t e . -
. :
[Obsolete("message")]
message ,
. .
// Obsolete.
using System;
class Test {
[Obsolete(" myMeth2.")]
static int myMeth(int a, int b) {
return a / b;
}
// myMeth().
static int myMeth2(int a, int b) {
return b == 0 ? 0 : a /b;
}
public s t a t i c void MainO {

482

I. #

// ,
// .
Console.WriteLine("4 / 3 i s " + Test.myMeth(4, 3 ) ) ;
// .
Console.WriteLine("4 / 3 i s " + Test.myMeth2(4, 3 ) ) ;
Main ()
myMeth (), ,
myMeth () inyMeth2 ().
Obsolete :
[Obsolete{"message", error)]
error Boolean. t r u e ,
, . ,
,
.

17. ,

483

.
. , "",
# , C++, .. , .
, " " # , Java.
,
.


# , " " (unsafe
code). , , , Common Language Runtime (CLR).
1, # . "" ,
, .
"",
. , , . , CLR.
, , ,
? ,
. C++, ,
, . , #.
, ,
"" .
, . , , , . # .
, (,
) , , # ( )
.
"", .
# ,
C/C++ ( , C/C++,
#). : # .
. #-
. , , /unsafe.
, , .

18. ,

485


, . , , ,
"" . , . , , .


- ( )
. - :
* _;

,
. , .
"" (*). .
_ -.
. i p int-,
:
1 int* ip;
float- :
| f l o a t * fp;
"" (*)
.
, , . , i p
int-, fp float-. :
,
"--". - .
# C/C++, # C/C++.
C/C++ " * " ,
. C/C++
| i n t * p, q;
int- int- q. :
i n t * Print q;

# " * " ,

| i n t * p, q;
q int-. , # :
i n t * ;
i n t * q;

C/C++-
"" #.

486

I. #

"*" "&"
: " * " "&". "&" .
, . (:
.) ,
int* ip;
i n t num = 10;
i p = &num;
i p num. , num. num. ,
i p 10 ( num), , . "&" "" " ", . , : " i p
num".
(*) (&).
, ,
, . , , . (
) i p num,
I i n t val = *ip;

v a l 10,
num, i p . " * " " ".
: " v a l () i p " .
" * " . , . ,
| i p = 100;
100 , i p (
num). ,
: " i p 100".

unsafe
, , ""
unsafe. . , ', Main() , unsafe.
//
// unsafe.

using

System;

class UnsafeCode {
// Main() "",
unsafe public s t a t i c void Main() {
int count = 99;

18. ,

487

int* p; // int-.
= &count; // count
/ / .
Console.WriteLine(
" count " +
*);
* = 10; // 10 count
// .
Console.WriteLine(
" count " + * ) ;
:
count 99
count 10

f i x e d
fixed. .
, , , - . " " " ", .
fixed :
fixed (type* p = &var) {
/I .
, .
, . fixed . fixed
" ". , , .
fixed:
//

fixed.

using System;
c l a s s Test {
public i n t num;
public T e s t ( i n t i)

{ num = i ;

c l a s s FixedCode {
/ / Main() ,
unsafe public s t a t i c void Main() {
Test = new Test(19);
fixed

488

( i n t * p = So.num)

{ / /
/ / fixed,
/ / .num .

I. #

Console.WriteLine(
" o.num " + * ) ;
* = 10; // 10 count
// .
Console.WriteLine(
" o.num " + * ) ;

:
o.num 19
o.num 10

fixed .
. num,
.


, . "" (->), "" (.). , , :
struct MyStruct {
public int x;
public int y;
public int sum() { return x + y; }
}

, :
MyStruct = new MyStruct ( ) ;
MyStruct* p ; // .
= & ;
-> = 10;
-> = 20;
Console.WriteLine(" " + p->sum());


: ++,
, + -. , , . p i int- 2 000 (.. p i 2 000).

p i 2 004, 2 001! ,
p i int-. # int- , p i
4. , .. p i 4. ,
18. ,

489

p i 1 996, 2 000.
, , , , .
, .

.
, .
| p i = p i + 9;
p i p i
, p i .
,
( , ).
, .
( ) () ,
,
. , f l o a t -
double-.
,
, .
, int- (ip)
float- (fp). (
), .
//
// .
using System;
class PtrArithDemo {
unsafe public static void Main() {
int x;
int i;
double d;
int* ip = &i;
double* fp = &d;

Console.WriteLine("int
for(x=0; x < 10; x++) {
Console.WriteLine((uint)
(uint)

double\n");
(ip) + " " +
(fp));

fp++;

. ,
.

490

I. #

int

double

1243324
1243328
1243332
1243336
1243340
1243344
1243348
1243352
1243356
1243360

1243328
1243336
1243344
1243352
1243360
1243368
1243376
1243384
1243392
1243400

, . int- , double- , .


, ==, < >.
, - . , p i 2
, ,
p i 2 . p i 2 , (, , ), p i 2
.
,
.
//

u s i n g System;
class PtrCompDemo {
unsafe public s t a t i c void Main() {
int[] nums = new i n t [ 1 1 ] ;
int x;
// ,
fixed (int* s t a r t = &nums[0]) {
fixed(int* end = Snums[nums.Length-1]) {
for(x=0; start+x <= end-x; x++) ;
}
}

Console.WriteLine(
" " + ) ;
:
1
,
s t a r t , end . ,
, s t a r t , 18. ,

491

end ,
s t a r t end .
: s t a r t end fixed, ,
. , # .


# . , . :
/*
. */
using System;
class PtrArray {
unsafe public static void Main() {
int[] nums = new int[10];
fixed(int* p = &nums[0]f p2 = nums) {
if(p == p2)
Console.WriteLine(
" 2 .");

:
I 2 .
,
I &nums[0]

1 nums
,
, .


, , ,
.
, . .
// .
using System;
class PtrlndexDemo {
unsafe public static void Main() {
int[] nums = new int[10];
// .
Console.WriteLine(
" .");
492

I. #

fixed (int* p = nums) {


for(int i=0; i < 10;
p[i] = i; // .
for(int i=0; i < 10;
Console.WriteLine("p[{0}]: {1}
// .
Console.WriteLine(
" .")
fixed (int* p = nums) {
for(int i=0; i < 10; i++)
*(p+i) = i; //
// .
for(int i=0; i < 10;
)
Console.WriteLine("*(p+{0};

{1}

}
:
.
[0]

[2]
[3]
[4]
[5]
[]
[7]
[8]
[9]

.
+0)
*(+2)
+3)
*(+4)
*(+5)
*(+6)
*(+7)
+8)
*(+9)
, (
)
* ( p t r + i)
,
:
ptr[i]

. -,
. ,
"" , . -, Length. .
18. ,

493


^ # , .
char*- , fixed-:
f i x e d ( c h a r * p = s t r ) { II . . .
f ixed- , .
, .. .
. C/C++ , . , char*- , ,
C/C++.
, char*:
// fixed-
// .
using System;
class FixedString {
unsafe public static void Main() {
string str = " .";
// str.
fixed(char* p = str) {
// str
/ / .
for(int i=0; p[i] != 0;
Console.Write(p[i]);
}
Console.WriteLine();

:
I .


, ,
.
(multiple indirection), . . 18.1. ,
( )
, .
, , .
, , , , .
494

I. #

, , .
""(*) . , , q i n t :
| i n t * * q;
, q
, int-.
, , " * " , :
using System;
class Multiplelndirect {
unsafe public static void Main() {
int x;
// ,
int* p; //
// int-.
int** q; //
// int-.
= 10;
= &; // .
q = &; // q.
Console.WriteLine(**q); // .

, ..
10. int-,
q int-.
: , , .
.


. 18.1.


, , . , , i n t :
i n t * [] p t r s = new i n t * [ 3 ] ;
18. ,

495

int- v a r
, :
I p t r s [ 2 ] = &var;
var, :
*ptrs[2j


I # ,
.

sizeof
, ( ) #-
. s i z e o f .
:
sizeof{)

, .
s i z e o f (unsafe) . , ,
( ) .

lock
lock . #
.
. , , ,
, . :
,
? , , . lock. :
lock{obj)

// .
obj , .
,
, . . ( . 21.)

readonly
, ,
readonly, readonly- , . , readonly- (, ), -

496

I. #

. ,
.
readonly-:
//

readonly-.

using System;
class MyClass {
public static readonly int SIZE = 10;
}
class DemoReadOnly {
public static void Main() {
int[]nums = new int[MyClass.SIZE];
for (int i^=0; i<MyClass . SIZE; i++)
nums[i] = i;
foreach(int i in nums)
Console.Write(i + " ") ;
// MyClass.SIZE = 100; // !!! readonly-
// !
MyClass. SIZE 10.
, . ,
, , .
.

stackalloc
s t a c k a l l o c .
. :

* = stackalloc []
,
, . s t a c k a l l o c
(unsafe) .
, . . , , . , . .
s t a c k a l l o c , "" .
s t a c k a l l o c :
// s t a c k a l l o c .
u s i n g System;
class UseStackAlloc {
unsafe public s t a t i c void Main() {
i n t * p t r s = stackalloc i n t [ 3 ] ;

18. ,

497

ptrs[O] == 1;
ptrs[l] = 2;
ptrs[2] = 3;
for(int i=0; i < 3;
Console.WriteLine(ptrs[ij);

:
1
2
3

u s i n g
using, ,
, using.
:
using (obj) {
// obj.
using (type obj = ) {
// obj.
obj , using. us ing-, .
obj Dispose () (
System. IDisposable). u s i n g , System. IDisposable.
using:
// u s i n g .
using System;
using System.10;
class UsingDemo {
public s t a t i c void Main() {
StreamReader sr = new StreamReader("test.txt");
// using,
using(sr) {
Console.WriteLine(sr.ReadLine());
sr.Close();
// StreamReader- using,
using(StreamReader sr2 = new StreamReader("test.txt")) {
Console.WriteLine(sr2.ReadLine());
sr2.Close();
}
}

498

I. #

StreamReader IDispo sable (


TextReader). , us ing-.
( iDisposable . 24.)

const v o l a t i l e
const , . . , const-
. ,
I const i n t i = 10;
const- i, 10.
v o l a t i l e , . , ,
,
.
.
. , #- ,
, . , (, ), , . v o l a t i l e ,
.

18. ,

499

#
II #.
I, #
.NET Framework.
,
#, .NET Framework.
#
. -
using
. ,
, ..
, ( )
.

dystem

System,
#. , , ,
.NET Framework. ,
System #.
System
, , System.Net.
. System.

system
, System co :
Activator
Array
AttributeUsageAttribute
CharEnumerator
ContextBoundOb^ ect
DBNull
Environment
FlagsAttribute
LocalDataStoreSlot
MTAThreadAttribute
Object
ParamArrayAttribute
SerializableAttribute
ThreadStaticAttribute
UnhandledExceptionEventArgs
ValueType

AppDomain
AssemblyLoadEventArgs
BitConverter
CLSCompliantAttribute
ContextStaticAttribute
Delegate
EventArgs

GC
MarshalByRefObject
MulticastDelegate
ObsoleteAttribute
Random
STAThreadAttribute
TimeZone

Uri
Version

AppDomainSetup
Attribute
Buffer
Console
Convert
Enum
Exception
LoaderOptimizationAttribute
Math
NonSerializedAttribute
OperatingSystern
ResolveEventArgs
String
Type
UriBuilder
WeakReference

System :
Arglterator
Char
Double
Int32
RuntimeArgumentHandle
RuntimeTypeHandle
TimeSpan
UInt32

Boolean
DateTime
Guid
Int64
RuntimeFieldHandle
SByte
TypedReference
UInt64

Byte
Decimal
Intl6
IntPtr
RuntimeMethodHandle
Single
UIntl6
UlntPtr

Void

System :
IAppDomainSetup
IComparable
IDisposable
IServiceProvider

IAsyncResult
IConvertible
IFormatProvider

19. System

ICloneable
ICustomFormatter
IFormattable

503

System :
AssemblyLoadEventHandler

AsyncCallback

CrossAppDomainDelegate

EventHandler

ResolveEventHandler

UnhandledExceptionEventHandler

System :
AttributeTargets

DayOfWeek

Environment.SpecialFolder

LoaderOptimization

PlatformID

TypeCode

UriHostNameType

UriPartial

, System
, . , System .NET Framework, #- .
, System (,
Type, Exception A t t r i b u t e ) I . System. S t r i n g , #-
s t r i n g , ,
20 ( ).
System, #- .

Math
Math , , , . ,
Math, . 19.1. .
, , Math,
static-.
Math, , Math.
Math :
public const double E
public const double PI
E , , a PI pi.
Math sealed-, .. .
19.1. , Math

p u b l i c s t a t i c double

Abs(double v)
p u b l i c s t a t i c f l o a t Abs ( f l o a t v)

p u b l i c s t a t i c decimal

A b s ( d e c i m a l v)
p u b l i c s t a t i c i n t A b s ( i n t v)

p u b l i c s t a t i c s h o r t Abs ( s h o r t v)

p u b l i c s t a t i c l o n g Abs ( l o n g v)

p u b l i c s t a t i c s b y t e A b s ( s b y t e v)

504

II. #

. 19.1

public static double


Acos(double v)
public static double
Asin(double v)

v. v -1 1
v. v -1 1

public static double


Atan(double v)

public static double


Atan2(double y,
double x)

public static double


Ceiling(double v)

( ), v. , v, 1.02, c e i l i n g ()
2.0. v, -1.02, c e i l i n g () -1

public static double


Cos(double v)

public static double


Cosh(double v)

public static double


Exp(double v)

,
v

public static double


Floor(double v)

( ), v. , v, 1.02, F l o o r ()
1.0. v, - 1 . 0 2 , F l o o r () -2

public static double


IEEERemainder(double dividend,
double divisor)

dividend/

public static double


Log(double v)

public static double


Log(double v,
double base)

v base

public static double


LoglO(double v)

v 10

public static double


Max(double vl,
double v2)

vl v2

public static float


Max(float vl,
float v2)

v l v2

public static decimal


Max(decimal vl,
decimal v2)

v l v2

public static int Max(int vl,


int v2)

v l v2

public static short


Max(short vl,
short v2)

v l v2

public static long Max(long vl,


long v2)

v l v2

19. System

divisor

505

. 19.1

public static uint Max(uint vl,


uint v2)
public static ushort
Max(ushort vl,
ushort v2)

vl v2

public static ulong


Max(ulong vl,
ulong v2)

vl v2

public static byte Max(byte vl,


byte v2)

vl v2

public static sbyte


Max(sbyte vl,
sbyte v2)

vl v2

public static double


Min(double vl,
double v2)

vl v2

public static float


Min(float vl,
float v2)

vl v2

public static decimal


Min(decimal vl,
decimal v2)

vl v2

public static int Min(int vl,


int v2)

vl v2

public static short


Min(short vl,
short v2)

vl v2

public static long Min(long vl,


long v2)

vl v2

public static uint Min(uint vl,


uint v2)

vl v2

public static ushort


Min(ushort vl,
ushort v2)

vl v2

public static ulong


Min(ulong vl,
ulong v2)

vl v2

public static byte Min(byte vl,


byte v2)

vl v2

public static sbyte


Min(sbyte vl,
sbyte v2)

vl v2

public static double


Pow(double base,
double exp)

base,
(baseexp)

public static double


Round(doubleI

v,

V)

public static decimal


Round(decimal v)

506

vl v2

v,

II. #

. 19.1

public static double


Round(double v,
int frac)

v} ,
frac

public static decimal


Round(decimal v,
int frac)

v, ,
frac

public static int Sign(double v)

-1, v , 0, v
, 1, v

public static int Sign(float v)

-1, v , 0, v
, 1, v

public static int


Sign(decimal v)

-1, v , 0, v
, 1, v

public
static int Sign(int v)

-1, v , 0, v
, 1, v

static int Sign(short v)

-1, v , 0, v
, 1, v

static int Sign(long v)

-1, v , 0, v
, 1, v

static int Sign(sbyte v)

-1, v , 0, v
, 1, v

public
public
public
public
static double
Sin(double
static double
Sinh(double
public static double
Sqrt(double
public static double
Tan(double
public static double
Tanh(double
public

v
v)
v)

v)

v)

v)

, Sqrt (), .
() .
// .
using System;
class Pythagorean {
public static void Main() {
double si;
double s2;
double hypot;
string str;
Console.WriteLine(" : " ) ;
str = Console.ReadLine();
si = Double.Parse(str);

4
19. System

507

Console.WriteLine(" : " ) ;
str = Console.ReadLine();
s2 = Double.Parse(str);
hypot = Math.Sqrt(sl*sl + s2*s2);
Console.WriteLine(" " + hypot);

:
:
3
:
4
5
, Pow ()
,
.
:
I n i t i a l l n v e s t m e n t = FutureValue / (1 + I n t e r e s t R a t e ) Y e a r s
Pow() double,
double-. decimal.
/* ,


. */
using System;
class Intiallnvestment {
public static void Main() {
decimal Initlnvest; //
decimal FutVal;
//
double NumYears;
double IntRate;

//
//
//

string str;
Console.Write(" : " ) ;
str = Console.ReadLine();
try {
FutVal = Decimal.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
Console.Write(
" (, 0.085): " ) ;
str = Console.ReadLine();
try {
508

II. #

IntRate = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
Console.Write(" : " ) ;
str = Console.ReadLine();
try {
NumYears = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
InitInvest = FutVal / (decimal) Math.Pow(IntRate+1.0,
NumYears);
Console.WriteLine(
" : {0:}",
Initlnvest);

:
: 10000
(, 0.085): 0.07
: 10
: $5,083.49


14 , ,
, . .
#- . ,
, , . .NET-
#:
.NET-

.NET-

#-

Boolean

bool

Char

char

Decimal

decimal

Double

double

Single

float

Intl6

short

Int32

lilt

Int64

long

UIntl6

ushort

UInt32

uint

UInt64

ulong

Byte

byte

SByte

sbyte

19. System

509

, ,
iFormatProvider Number Styles. iFormatProvider
. Numberstyles , System.Globalization.
20.


:
Byte

SByte

Intl6

UIntl6

Int32

UInt32

Int64

UInt64

(. . 19.2), , Parse ( ) . Parse () , . ,


I n t 3 2 Parse () i n t ,
U l n t l 6 u s h o r t . ( Parse 14.)
, . 19.2,
const-:
MaxValue
MinValue
, , .
:
IComparable, IConvertible IFormattable.

19.2. ,

public int CompareTo(object v)

v. ,
. , , ,

public override bool Equals(

,
v

object v)
public override int GetHashCode()

public TypeCode GetTypeCode()

TypeCode . , i n t 3 2
TypeCode . Int32

public static _
Parse(string str)


, str.
,

public static _
Parse(string str,
IFormatProvider fmtpvdr)


, s t r ( , ), fmtpvdr.
,

510

II. #

. 19.2

public static _
Parse(string str,
NumberStyles styles)


, s t r , ,
styles.

,

public static _
Parse(string str,
NumberStyles styles,
IFormatProvider fmtpvdr)


, s t r , , styles, a
(
, ),
fmtpvdr.
,

public override string ToStringO

public string ToString(


string format)



, forma t

public string ToString(


IFormatProvider fmtpvdr)


( ,
),
fmtpvdr

public string ToString(


string format,
IFormatProvider fmtpvdr)


( , ), fmtpvdr,
, forma t


: Double
Single. Single f l o a t .
. 19.3, . 19.4. Double double. . 19.5, . 19.6. , Parse () ToStringO
( , ), .
:
IComparable, I C o n v e r t i b l e I F o r m a t t a b l e .
19.3. , s i n g l e

public int CompareTo(object v)

v. ,
. , , ,

public override bool Equals(


object v)

,
v

19. System

511

. 19.3

public override int GetHashCode()

public TypeCode GetTypeCode()

ode S i n g l e , .. TypeCode . S i n g l e

public static bool Islnfinity(


float v)

, v
( "" "").

public static bool IsNaN(float v)

, v .

public static bool


IsPositivelnfinity(float v)

, v
"".

public static bool


IsNegativelnfinity(float v)

, v
"".

public static float Parse (


string str)


, s t r .
f l o a t ,

public static float Parse(


string str,
IFormatProvider fmtpvdr)


, s t r
( ,
),
fmtpvdr. f l o a t ,

public static float Parse(


string str,
NumberStyles styles)


, s t r , ,
styles.

f l o a t ,

public static float Parse(


string str,
NumberStyles styles,
IFormatProvider fmtpvdr)


, s t r , ,
styles,
(
, ), fmtpvdr.

f l o a t ,

public override string ToStringO

public string ToString(


string format)



, forma t

public string ToString(


IFormatProvider fmtpvdr)


( ,
), fmtpvdr

public string ToString(


string format,
IFormatProvider fmtpvdr)


( , ), fmtpvdr,
, format

512

II. #

19.4. , single

public const float Epsilon

public const float MaxValue

,
f l o a t

public const float MinValue

,
f l o a t

public const float NaN

public const float

Negativelnfinity

public const float

Positivelnfinity

19.5. , Double

public i n t CompareTo(object v)

v. ,
. , , ,

public override bool Equals(


object v)

,
v

public override int GetHashCode()

public TypeCode GetTypeCode()

TypeCode D o u b l e , .., TypeCode . D o u b l e

public static bool Islnfinity(


double v)

, v
( "" "").

public static bool IsNaN(


double v)

, v .

public static bool


IsPositivelnfinity(double v)

, v
"".

public static bool


IsNegativelnfinity(double v)

, v
"".

public static double Parse(


string str)


, str.
d o u b l e ,

public static double Parse (


string str,
IFormatProvider fmtpvdr)


, s t r
( ,
),
fmtpvdr. d o u b l e ,

public static double Parse(


string str,
NumberStyles styles)


, strt ,
styles.

d o u b l e ,

19. System

513

. 19.5

public static double Parse(


string str,
NumberStyles styles,
IFormatProvider fmtpvdr)

public override string ToStringO


public string ToString(
string format)
public string ToString(
IFormatProvider fmtpvdr)


, s t r , ,
styles, (
, ), fmtpvdr.
d o u b l e ,



, forma t

( , ),
fmtpvdr

public string ToString(


string format,
IFormatProvider fmtpvdr)


( , ),
fmtpvdr, ,
forma t

19.6. , Double

public const double Epsilon


, d o u b l e
, d o u b l e
,
,
,

public const double MaxValue


public const double MinValue
public const double NaN
public const double Negativelnfinity
public const double

Positivelnfinity

D e c i m a l
Decimal , . , , , decimal #-. , decimal .
Decimal .
:
p u b l i c D e c i m a l ( i n t v)
p u b l i c Decimal(uint v)
p u b l i c Decimal(long v)

514

li. #

public Decimal(ulong v)
public Decimal(float v)
public Decimal(double v)
Decimal- .
Decimal- , :
p u b l i c Decimal(int low, i n t middle,
i n t high,

bool signFlag, byte

scaleFactor)

decimal . 96 , . 96- 32-


low, middle high. signFlag,
f a l s e
t r u e .
s c a l e F a c t o r , 0 28.
10 (.. i o s c < a i e F a c t o r ) ,
.
, Decimal- .
:
public Decimal(int[]
parts)
int- parts 96- .
31- p a r t s [3] (
1 ), 16-23 .
Decimal : iComparable,
IConvertible IFormattable.
decimal "".
// decimal- "".
using System;
class CreateDec {
public static void MainO {
decimal d = new decimal(12345, 0, 0, false, 2 ) ;
Console.WriteLine(d);

:
123.45
96- 12345.
.
, Decimal, . 19-7,
. 19.8. Decimal , decimal-
. decimal 3.

19. System

515

19.7. , Decimal

public static decimal Add(


decimal vl,
decimal v2)

vl + v2

Public static int CompareTo(


decimal vl,
decimal v2)

vl v2.
, . , vl v2, , vl
v2

public int CompareTo(object v)

v. ,
. , , ,

public static decimal Divide(


decimal vl,
decimal v2)

vl / v2

Public override bool Equals(


object v)

, v

public static bool Equals(


decimal vl,
decimal v2)

, vl v2

public static decimal Floor(


decimal v)

( d e c i m a l ) , v. , v, 1 . 0 2 , F l o o r () 1 . 0 .
v, - 1 . 0 2 , F l o o r () - 2

public static decimal


FromOACurrency(long v)

, OLE
Automation v, d e c i m a l

public static int[] GetBits(


decimal v)

v
int-.

public override int


GetHashCodeO

public TypeCode GetTypeCode()

TypeCode
D e c i m a l , .. TypeCode . D e c i m a l

public static decimal


Multiply(decimal vl,
decimal v2)

vi * v2

public static decimal Negate (


decimal v)

-v

public static decimal Parse(


string str)

, s t r .
d e c i m a l ,

public static decimal Parse('


string str,
IFormatProvider fmtpvdr)

, s t r ( ,
), fmtpvdr.

d e c i m a l ,

516

II. #

. 19.7

public static decimal Parse(


string str,
NumberStyles styles)

, s t r ,
, styles. decimal,

public static decimal Parse(


string str,
NumberStyles styles,
IFormatProvider fmtpvdr)

, str,
, styles,
( ,
), fmtpvdr. decimal,

public static decimal


Remainder(decimal vl,
decimal v2)

vl / v2

public static decimal


Round(decimal v,
int decPiaces)

v, ,
decPiaces,
0-28

public static decimal


Subtract(decimal vl,
decimal v2)

vl - v2

public static byte


ToByte(decimal v)

byte- v. . v
, b y t e ,
Overf l o w E x c e p t i o n

public static double


ToDouble(decimal v)

double- v. , double
, d e c i m a l

public static short


Tolnt16(decimal

short- v. . v
, s h o r t , Overf l o w E x c e p t i o n

v)

public static int


Tolnt32(decimal v)

int- v. . v
, i n t ,
Overf l o w E x c e p t i o n

public static long


Tolnt64(decimal

long- v. . v
, long,
Overf l o w E x c e p t i o n

v)

public static long


ToOACurrency(decimal

v)

v OLE
Automation

public static sbyte


ToSByte(decimal v)

sbyte- v. . v
, sbyte, Overf l o w E x c e p t i o n

public static float


ToSingle(decimal

float- v.
, f l o a t
, d e c i m a l

19. System

v)

517

. 19.7

public override string


ToStringO

public string
ToString(string


,
forma t

format)

public string ToString(


IFormatProvider fmtpvdr)


( , ), fmtpvdr

public string ToString(


string format,
IFormatProvider fmtpvdr)


( , ), fmtpvdr,
, forma t

public static ushort


ToUIntl6(decimal v)

ushort- v. . v
, u s h o r t , Overf l o w E x c e p t i o n

public static uint


ToUInt32(decimal v)

uint- v. . v
, u i n t ,
Overf l o w E x c e p t i o n

public static ulong


ToUInt64(decimal v)

ulong- v. . v
, ulong, Overf l o w E x c e p t i o n

public static decimal


Truncate(decimal v)

, v. ,

19.8. , Decimal

p u b l i c s t a t i c readonly decimal MaxValue

,
d e c i m a l

p u b l i c s t a t i c readonly decimal MinusOne

-1 decimal

p u b l i c s t a t i c readonly decimal MinValue

,
decimal

public static readonly decimal One

1 decimal

public static readonly decimal Zero

0 decimal.

char
, ( , "
") Char. , ,
. , ToUpperO, -

518

II. #

. isDigit () ,
.
, Char, . 19.9.
Char :
public const char MaxValue
public const char MinValue
,
char. Char IComparable
IConvertible.
19.9. , char

public int CompareTo(object v)


v. , . , , ,

public override bool Equals(


object v)

, v

public override int


GetHashCodeO

public static double


GetNumericValue(char ch)

ch, ch - .
-1

public static double


GetNumericValue(string str,
int idx)

str [idx], . -1

public TypeCode GetTypeCode()

TypeCode
Char, .. T y p e C o d e . C h a r

public static UnicodeCategory


GetUnicodeCategory(char ch)

UnicodeCategory
ch. UnicodeCategory , S y s t e m . G l o b a l i z a t i o n ,
Unicode

public static UnicodeCategory


GetUnicodeCategory(string str,
int idx)

UnicodeCategory
striidx].
UnicodeCategory- ,
system. G l o b a l i z a t i o n ,
Unicode

public static bool


IsControl(char ch)

, ch .

public static bool


IsControl(string str,
int idx)

, str [ idx]
.

public static bool IsDigit(


char ch)

' , ch .

public static bool


IsDigit(string str,
int idx)

, striidx]

. -

public static bool


IsLetter(char ch)

, ch .

19. System

519

. 19.9

public static bool


IsLetter(string str,
int idx)

, str [idx]
.

public static bool


IsLetterOrDigit(char ch)

, ch .

public static bool


IsLetterOrDigit(string str,
int idx)

, str [idx]
.

public static bool


IsLower(char ch)

, ch
.

public static bool


IsLower(string str,
int idx)

, s t r [ idx]
.

public static bool


IsNumber(char ch)

, ch (0-9 A-F).

public static bool


IsNumber(string str,
int idx)

, str [idx]
(0-9 A-F).

public static bool


IsPunctuation(char ch)

, ch .

public static bool


IsPunctuation(string str,
int idx)

, str [idx]
.

public static bool


IsSeparator(char ch)

, ch , .

public static bool


IsSeparator(string str,
int idx)

, str [idx]
, .

public static bool


IsSurrogate(char ch)

, ch Unicode.

public static bool


IsSurrogate(string str,
int idx)

, str [idx]
Unicode.

public static bool


IsSymbol(char ch)

, ch , .

public static bool


IsSymbol(string str,
int idx)

, str [idx]
, .

public static bool


IsUpper(char ch)

, ch .

public static bool


IsUpper(string str,
int idx)

, str [idx]
.

520

II. #

. 19.9

public static bool


IsWhiteSpace(char ch)

, ch , .

public static bool


IsWhiteSpace(string str,
int idx)

, striidx]

, .

public static char


Parse(string str)

char- s t r .
str , F o r m a t E x c e p t i o n

public static char


ToLower(char ch)

ch, ch . ch

public static char


ToLower(char ch,
Culturelnfo c)

ch, ch . ch .
, , . C u l t u r e l n f o , S y s t e m . G l o b a l i z a t i o n

public static char


ToUpper(char ch)

ch, ch
. ch

public static char


ToUpper(char ch,
Culturelnfo c)

ch, ch
. ch . , ,
. C u l t u r e l n f o ,
s y s t e m . G l o b a l i z a t i o n

public override string


ToString()


char-

public static string


ToString(char ch)

ch

public string ToString(


IFormatProvider fmtpvdr)


char-
fmtpvdr
, ,

, , Char:
//
//

,
Char.

using System;
c l a s s CharDemo {
public s t a t i c void Main() {
s t r i n g s t r = "
int
i;

19. System

$23";

521

for(i=0; i < str.Length;


Console.Write(str[i] + " ");
if(Char.IsDigit(str[i]))
Console.Write(" ");
if(Char.IsLetter(str{i]))
Console.Write(" ");
if(Char.IsLower(str[i]))
Console.Write(" ");
if(Char.IsUpper(str[i] ) )
Console.Write(" " ) ;
if(Char.IsSymbol(str[i] ) )
Console.Write(" ")
if(Char.IsSeparator(str[i] ) )
Console.Write(" ");
if(Char.IsWhiteSpace(str[i] ) )
Console.Write(" ");
if(Char.IsPunctuation(str[i] ) )
Console.Write(" ");
Console.WriteLine();
Console.WriteLine(" : " + str);
// ,
string newstr = "";
for(i=0; i < str.Length; i++)
newstr += Char.ToUpper(str[i]);
Console.WriteLine(" : " + newstr);

:









i







.

$
2
3
: . $23
: . $23

522

II. #

Boolean
Boolean bool. , Boolean, . 19.10.
:
public s t a t i c readonly string FalseString
public s t a t i c readonly string TrueString

true false. , FalseString
WriteLine (), "False".
Boolean IConiparable IConvertible.
19.10. , Boolean

public int CompareTo(object v)

v. , .
,
f a l s e , v t r u e . , t r u e , a
v f a l s e

public override bool Equals(


object v)

t r u e ,
v

public override int

GetHashCodeO
public TypeCode

GetTypeCode()

TypeCode
B o o l e a n , .. TypeCode . B o o l e a n

public static bool Parse (


string str)

booi- ,
str. "True",
"False", , ,
:

public override string


ToString i)

string ToString(
IFormatProvider fmtpvdr)


fmtpvdr , ,

! Array
System Array. Array
#. , , ,
. , Array, . 19.11,
. 19.12.
Array : icioneable, iCollection,
IEnumerable iList. ICollection, IEnumerable iList
System. Collections 22.
19. System

523

Array
IComparer.

S y s t e m . C o l l e c t i o n s , Compare (),
.
i n t Compare(object vl, o b j e c t v2)
, vl
v2, , vl v2, ,
.
.


, ,
. Array . Sort ( ) , ,
, "/".
BinarySearch (). ,
int- Sort () BinarySearch ():
// .
using System;
class SortDemo {
public static void Main() {
int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };
//
// .
Console.Write(" :
" ) ;
foreach(int i in nums)
Console.Write(i + " " ) ;
Console.WriteLine();
// .
Array.Sort(nums);
// .
Console.Write(" : " ) ;
foreach(int i in nums)
Console.Write(i + " ") ;
Console.WriteLine();
// 14.
int idx = Array.BinarySearch(nums, 14);
Console.WriteLine(" 14 " + idx);
:
:
5 4 3 14 9 8 17 1 24 -1
: -1 0 1 3 4 5 8 9 14 17 24
14 9
524

II. #

i n t , .. .
, Array, . . ,
IComparable.
,
. ,
IComparable , :
int CompareTo(object v)
v. , v, ,
, ,
v. ,
, , :
//

using System;
class MyClass : IComparable {
public i n t i ;
public MyClass(int

x)

{ i = x;

/ / IComparable.
public i n t CompareTo(object v) {
return i - ((MyClass)v).i;

c l a s s SortDemo {
p u b l i c s t a t i c v o i d Main() {
MyClass[] nums = new M y C l a s s [ 5 ] ;
nums[0]
nums[1]
nums[2]
nums[3]
nums[4]

=
=
=
=
=

new
new
new
new
new

MyClass(5);
MyClass(2);
MyClass(3);
MyClass ( 4 ) ;
MyClass ( 1 ) ;

/ /
/ / .
C o n s o l e . W r i t e ( " :
") ;
f o r e a c h ( M y C l a s s i n nums)
Console.Write(.i + " " ) ;
Console.WriteLine();
/ / .
Array.Sort(nums);
/ / .
C o n s o l e . W r i t e ( " : " ) ;
f o r e a c h ( M y C l a s s o i n nums)
Console.Write(.i + " " ) ;
Console.WriteLine();

19. System

,
/

525

// MyClass(2).
MyClass x = new MyClass(2);
int idx = Array.BinarySearch(nums, x ) ;
Console.WriteLine(" MyClass(2)
idx) ;


:
:
MyClass(2)

:
5 2 3 4 1
12 3 4 5
1


. , , , , . :
Reverse .
. :
// .
u s i n g System;^
class ReverseDemo {
public static void Main() {
int[] nums = { 1 , 2 , 3 , 4, 5 };
// .
Console.Write(" :
foreach(int i in nums)
Console.Write(i + " " ) ;
Console.WriteLine();

" ) ;

// .
Array.Reverse(nums);
// .
Console.Write(" :
foreach(int i in nums)
Console.Write(i + " " ) ;
Console.WriteLine();

" ) ;

// .
Array.Reverse(nums, 1, 3 ) ;
//
// .
Console.Write(" : " ) ;
foreach(int i in nums)
Console.Write(i + " " ) ;
Console.WriteLine();

526

II. #

:
:
12 3 4 5
:
5 4 3 2 1
: 5 2 3 4 1


. , (). - ,
, () . ()
:
// .
using System;
class CopyDemo {
public static void Main() {
int[] source = { 1 , 2, 3, 4, 5 } ;
int[] target = { 11, 12, 13, 14, 15 };
int[] source2 = { -1, -2, -3, -4, -5 };
// - .
Console.Write("-: " ) ;
foreach(int i in source)
Console.Write(i + " ") ;
Console.WriteLine() ;
// -.
Console.Write(
" -: " ) ;
foreach(int i in target)
Console.Write (i + " " ) ;
Console.WriteLine();
// .
Array.Copy(source, target, source.Length);
// .
Console.Write(" : " ) ;
foreach(int i in target)
Console.Write (i + " " ) ;
Console.WriteLine();
// target.
Array.Copy(source2, 2, target, 3, 2 ) ;
// .
Console.Write(
" : " ) ;
foreach(int i in target)
Console.Write(i + " " ) ;
Console.WriteLine();

19. System

527

:
-: 1 2 3 4 5
- : 11 12 13 14 15
:
1 2 3 45
:
1 2 3-3-4
19.11. , A r r a y

public virtual bool


IsFixedSize { get; }

. t r u e ,
, f a l s e ,

public virtual bool


IsReadOnly { get; }

. t r u e ,
A r r a y , f a l s e

public virtual bool


IsSynchronized { get; }

. t r u e ,
,
f a l s e

public int Length { get;

public int Rank { get; }

public virtual object


SyncRoot { g e t ; }

. ,

19.12. , A r r a y

public static int


BinarySearch(Array a,
object v)

, , , v.
. , .

public static int


BinarySearch(Array a,
object v,
IComparer comp)

, , , v, , . . , .

public static int


BinarySearch(Array a,
int start,
int count,
object v)

, ,
, v. ,
start,
count .
.
, .

public static int


BinarySearch(Array a,
int start,
int count,
object v,
IComparer comp)

, ,
, v,
, .
, start,
count
.
. , .

528

II. #

. 19.12

public s t a t i c void
Clear(Array a,
int start,
int count)

.
, , , s t a r t , count

public virtual object Clone()

. , , "". , ,
, ,

public static void


Copy(Array source,
Array dest,
int count)

count source
dest. .
, ( ) " ",

public static void


Copy(Array source,
int srcStart,
Array dest,
int destStart,
int count)

count source (
srcstart)
dest (
deststart).

, ()
" ",

public virtual void


CopyTo(Array dest,
int start)


d e s t [ s t a r t ]

public static Array


Createlnstance(Type t,
int size)

,
size t

public static Array


Createlnstance(Type t,
int sizel,
int size2)


sizel*size2.
t

public static Array


Createlnstance(Type t,
int sizel,
int size2,
int size3)


sizei*size2*size3.
t

public static Array


Createlnstance(Type t,
int[] sizes)

, sizes. t

public static Array


Createlnstance(
Type t,
int[] sizes,
int[] startlndexes)

, sizes. t . s t a r t l n d e x e s . ,
, ,

public override bool


Equals(object v)

t r u e ,
v

public virtual IEnumerator


GetEnumerator()

.
.
22, ""

19. System

dest,

529

. 19.12

public int GetLength(int dim)

. ; ,
,
1

public int
GetLowerBound(int dim)

, . dim ,
; ,
0, 1

public override int


GetHashCodeO

public TypeCode GetTypeCode()

TypeCode
A r r a y , .. TypeCode . A r r a y

public int
GetUpperBound(int dim)

,
. dim ,
; ,

0, 1

public object GetValue(int ldx)

idx.

public object GetValue(int idxl,


int idx2)

[ idxl,
idx2].

public object GetValue(int idxl,


int idx2,
int idx3)

[ idxl,
idx2,
idx3].

public object
GetValue(int[] idxs)

, idxs. ,
idxs

public static int


IndexOf(Array a, object v)


, , v. - 1 , . (
, 0,
,
1)

public static int


IndexOf(Array a,
object v,
int start)


, , v.
a [start].
- 1 , . ( , 0,
, 1)

public static int


IndexOf(Array a,
object v,
int start,
int count)


, , v.
[ s t a r t ] t . - 1 , . ( , 0,
,
1)

530

II. #

. 19.12

public void Initialize()

, .

public static int


LastlndexOf(Array a,
object v)

, , v. - 1 , . (
, 0,
,
1)

public static int


LastlndexOf(Array a,
object v,
int start)


, ,
v. , [ s t a r t ] [0].
- 1 , . ( , ,

, 1)

public static int


LastlndexOf(Array a,
object v,
int start,
int count)


, , v. ,
a [ s t a r t ] , oxeaTbieaeTcount .
- 1 , . ( , 0,
, 1)

public static void


Reverse(Array a)

public static void


Reverse(Array a,
int start,
int count)

.
[ start]
c o u n t

public void SetValue(object v,


int idx)


idx v.

public void SetValue(object v,


int idxl,
int idx2)


[ idxl,
idx2] v.

public void SetValue(object v,


int idxl,
int idx2,
int idx3)


[ idxl,
idx2,
idx3] v.

public void SetValue(object v,


int[] idxs)

,
idxs, v. , idxs

public static void Sort(Array a)

public static void


Sort(Array a,
IComparer comp)


, .

19. System

531

. 19.12

public static void


Sort(Array k,
Array v)


. , v
, . ,
/.

public static void


Sort(Array k,
Array v,
IComparer comp)


, . ,
V, . ,
/.

public static void


Sort(Array a,
int start,
int count)

.
a [start]

count .

public static void


Sort(Array a,
int start
int count,
IComparer comp)


,
.
a [ s t a r t ] count .

public static void


Sort(Array k,
Array v,
int start,
int count)


.
, start,
count . , v , .
,
/.

public static void


Sort(Array k,
Array v,
int start,
int count,
IComparer comp)


, . ,
start,
count .
, v ,
. ,
/.

LJ B i t C o n v e r t e r

. , , .
.
, . ,
, . # BitConverter.

532

II. #

B i t C o n v e r t e r , . 19.13.
:
public static readonly bool IsLittleEndian
t r u e , ( ), (
) . ( ) , .. , ("little-endian" format). I s L i t t l e E n d i a n
f a l s e ,
( ), ( )
. ("big-endian" format). , Pentium Intel,
.
BitConverter sealed-, ..
.
19.13. , BitConverter

public static long


DoubleToInt64Bits(double v)

v
l o n g

public s t a t i c byte[]
GetBytes(bool v)

public static byte[]


GetBytes(char v)

public s t a t i c byte[]
GetBytes(double v)

public static byte[]


GetBytes(float v)

public static byte[]


GetBytes(int v)

public static byte[]


GetBytes(long v)

public static byte[]


GetBytes(short v)

public static byte[]


GetBytes(uint v)

public static byte[]


GetBytes(ulong v)

public static byte[]


GetBytes(ushort v)

public static double


Int64BitsToDouble(long v)

v
double

public static bool


ToBoolean(byte[] a,
int idx)

a [idx]
bool- .
t r u e , f a l s e

public static char


ToChar(byte[] a,
int start)

, [ start], char-

19. System

533

. 19.13

public static double


ToDouble(byte[] a,
int start)
public static short
Tolntl6(byte[] a,
int start)

, [ start],
double-

public static int


Tolnt32(byte[] a,
int start)

, a [start],
int-

public static long


Tolnt64(byte[] a,
int start)

, [ start ],
long-

public static float


ToSingle(byte[] a,
,
int start)

, a [start],
float-

public static string


ToString(byte[] a)

. ( ),

public static string


ToString(byte[] a,
int start)

, a
[start],
.
( ),

public static string


ToString(byte[] a,
int start,
int count)

count ,
[ start], .
( ),

public static ushort


ToUIntl6(byte[] a,
int start)

, [ start], ushort-

public static uint


ToUInt32(byte[] a,
int start)

, [ start],
uint-

public static ulong


ToUInt64(byte[] a,
int start)

, [ start],
u long-

, [ start], short-


Random
,
Random. , .
, Random .
Random :
public Random()
public Random(int seed)

534

II. #

Random,

.
seed.
, Random, . 19.14.
19.14. , Random

p u b l i c v i r t u a l i n t Nexto
public virtual int
Next ( i n t upperBound)
public virtual int
Next ( i n t lowerBound,
i n t upperBound)
public v i r t u a l void
N e x t B y t e s ( b y t e [ ] bur")
p u b l i c v i r t u a l double
NextDoubie ()
p r o t e c t e d v i r t u a l double
sample ()

i n t .
0-int32 .MaxVaiue-1,
i n t ,
0- upperBounchi,
i n t ,
lowerBound-upperBound-^

buf . 0B y t e . MaxValue-1,

( ),
0,0 1,0

( ),
0,0 1,0. ,

, Random
:
// .
using System;
c l a s s RandDice {
public s t a t i c void Main() {
Random ran = new Random();
Console.Write(ran.Next(1, 7) + " " ) ;
Console.WriteLine(ran.Next(1, 7 ) ) ;

"" :
5 2
4 4
16

Random. , 16.

19. System

535

- J GC
GC #- . ,
, . 19.15. ,
public s t a t i c

int

MaxGeneration

{ get;

MaxGeneration . (.
new) , , , .
, MaxGeneration ,

.

GC. ,
C o l l e c t () .
, .
,
,
, ().
GC sealed-,
19.15. , GC

public s t a t i c void Collect()

public s t a t i c void
Collect (mt MaxGen)

MaxGen

public s t a t i c int
GetGeneration(object o)

public s t a t i c int
GetGeneration(WeakReference o)

,
"" , ""

public s t a t i c long
GetTotalMemory(bool

( )
collect

t r u e ,

collect)

public s t a t i c void
KeepAlive(object o)

public s t a t i c void
ReRegisterForFinalize(
object o)

S u p p r e s s F m a l i z e ^)

public static void


SuppressFinalize(object o)

public static void


WaitForPendmgFmalizers ()

536

II. #

- J O b j e c t
Object , #- object.
Object 11, # (
) . 19.16. Object :
Object ()
.
19.16. , Object

p u b l i c v i r t u a l b o o l Equals (
o b j e c t ob)

t r u e ,
, , ob.
f a l s e

p u b l i c s t a t i c bool Equals (
ob j ect obi,
o b j e c t ob2)

t r u e , obi
, 2.
false

p r o t e c t e d F i n a l i z e ()

. # F i n a l i z e ()

p u b l i c v i r t u a l i n t GetHashcode ()

-,

p u b l i c Type GetType ()

protected object
Memberwisecione ()
p u b l i c s t a t i c bool
Ref erenceEquals (object obi,
o b j e c t ob2)

" " , .. , ,
true, obi 2 .
f a l s e

public v i r t u a l s t r i n g TostringO

IComparable
IComparable,
, #-, .
IComparable ,
:
i n t CompareTo(object v)
v. , v, , , , v.

19. System

537

EJ I C o n v e r t i b l e
I C o n v e r t i b l e .
. , .

ICloneable
ICloneable, . ICloneable :
object Clone ()
. ,
Clone (), . :
. . , ,
. , ,
. ,
,
, , , , . Clone () , .

MemberwiseClone (), Object.


, ICloneable.
Test, X.
Test Clone ().
// I C l o n e a b l e .
using System;
class X {
public int a;

public X(int x) { a = x; }
}
class Test : ICloneable {
public X o;
public int b;
public Test (int x, int y) {
= new X(x);
b = y;
}
public void show(string name) {
Console.Write(" " + name + " : " ) ;
Console.WriteLine("o.a: {0}, b: {1}", o.a, b ) ;

538

II. #

// ,
public object Clone() {
Test temp = new Test(o.a, b ) ;
return temp;

class CloneDemo {
public static void MainO {
Test obi = new Test(10, 20);
obi.show("obi") ;
Console.WriteLine(
" 2 obi.");
Test ob2 * (Test) obi.Clone();
ob2.show("ob2") ;
Console.WriteLine(" obi.. 99,
+ " obl.b 88.");
obi.. = 99;
obl.b - 88;
obi.show("obi");
ob2.show("ob2");

:
obi : . : 10, : 20
2 o b i .
2 : . : 10, : 20
o b i . . 99, o b l . b
obi : . : 99, : 88
2 : . : 10, : 20

88.

, 2 obi,
obi 2 . .
, X, , .
Clone () MemberwiseClone (), Object.
, , Clone () :
// ,
p u b l i c o b j e c t Clone() {
Test temp = (Test) MemberwiseClone();
r e t u r n temp;

:
obi : .: 10, : 20
2 obi.
2 : .: 10, : 20
obi.. 99, obl.b 88.
19. System

539

i obi : . : 99, : 88
I 2 : . : 99, : 20
, obi 2 X.
. int- b - ,
.

I IFormatProvider
IFormattable
IFormatProvider GetFormatO, , , . Get Format () :
ob3ect GetFormat(Type fmt)
fmt . 20.
I F o r m a t t a b l e
. IFormattable
:
string ToString(string fmt, IFormatProvider fmtpvdr)
fmt , fmtpvdr () . 20.

540

II. #

l s t r i n g . ,
V ^ . s t r i n g , ,
, . , .
,
#, , .

#
# 7,
"" .
s t r i n g , #.
(string) ,
. C++ , # . #
s t r i n g . s t r i n g . , s t r i n g #- .NET- System. S t r i n g .
, #- , , , S t r i n g .
. # ( )
.
, . ,
" " , ,
, ,
, .
,
" " . , s t r i n g , , ,
. s t r i n g .
, , #
S t r i n g B u i l d e r , System.Text. s t r i n g , S t r i n g B u i l d e r .

L-J S t r i n g
String System.
IComparable, ICloneable, IConvertible IEnumerable. String sealed, .. . s t r i n g # . #- s t r i n g
.NET Framework. String.

542

II. #

S t r i n g
S t r i n g , . ,
:
public String(char[] chrs)
public String(char[] chrs, int start, int count)
,
, chrs. ,
, count , chrs, , start.
, , . :
p u b l i c S t r i n g ( c h a r ch, i n t count)
ch , count .
, ,
:
unsafe public String(char* chrs)
unsafe public String(char* chrs, int start, int count)
,
, chrs. , chrs ( ).
, ,
count , , chrs, ,
s t a r t .
, ,
:
unsafe p u b l i c S t r i n g ( s b y t e * chrs)
unsafe p u b l i c S t r i n g ( s b y t e * chrs, i n t start,
i n t count)
unsafe p u b l i c S t r i n g ( s b y t e * chrs, i n t start,
i n t count, Encoding ) *
,
, chrs. ,
chrs ( ). ,
, count , , chrs, , start. . ASCIIEncoding. Encoding
System. Text.
.
. :
I s t r i n g s t r = " ";

, s t r i n g
s t r i n g :
public static readonly string Empty
Empty , .. , .
() s t r i n g , .
20.

543

s t r i n g ,
:
public char this[int

idx]

{ get;

. , . s t r i n g , , S t r i n g , , .
s t r i n g ,
:
public int Length { get; }

Length , .

s t r i n g
S t r i n g : " = = " " ! = " . , , "==". "==" , ,
. "===" S t r i n g , . " ! = " : string- . (, " < " ">="),
, . , , ()
, Compare (), S t r i n g .

s t r i n g
s t r i n g .
. , .


, ,
. S t r i n g
, . 20.1.
Compare (). ,
( ) (..
). , .. ,
, , . ( ,
, ), .
Compare () :
1 // .

using System;

I class CompareDemo {
public static void Main() {
string strl = "";
%
string str2 = "";
544

II. #

string str3 = "";


string str4 = "";
string str5 = ", ";
if(String.Compare(strl, str2) == 0)
Console.WriteLine(strl + " " + str2 +
" .");
/
else
Console.WriteLine(strl + " " + str2 +
" .");
if(String.Compare(strl, str3) == 0)
Console.WriteLine(strl + " " + str3 +
" .");
else
Console.WriteLine(strl + " " + str3 +
" .");
if(String.Compare(strl, str3, true) == 0)
Console.WriteLine(strl + " " + str3 +
" .");
else
Console.WriteLine(strl + " " + str3 +
" .")
if(String.Compare(strl, str5) == 0)
Console.WriteLine(strl + " " + str5 +
" .");
else
Console.WriteLine(strl + " " + str5 +
" .");
if(String.Compare(strl, 0,*str5, 0, 3) == 0)
Console.WriteLine(" " + strl +
" " +
str5 + " .");
else
Console.WriteLine(" " + strl +
" " +
str5 + " .");
int result = String.Compare(strl, str4);
if(result < 0)
Console.WriteLine(strl + " " + str4);
else if(result > 0)
Console.WriteLine(strl + " " + str4);
else
Console.WriteLine(strl + " " + str4);

:
.
.
.
, .
, .

20.

545

20.1. , string

public static int


Compare(string strl,
string str2)

, s t r l , ,
str2. , strl str2, ,
strl s t r 2 , , s t r l str2

Public static int


Compare(string strl,
string str2,
bool ignoreCase)

, s t r l , ,
str2. , s t r l str2, ,
strl s t r 2 , , strl s t r 2 .
ignoreCase t r u e ,
.

public static int


Compare(string strl,
string str2,
bool ignoreCase,
Culturelnfo ci)

, s t r l , ,
str2,
( ,
),
ci. ,
s t r l str2, , strl
str2, , strl s t r 2 . ignoreCase t r u e ,
. .
c u l t u r e l n f o
System.Globalization

public static int


Compare(string strl,
int startl,
string str2,
int start2,
int count)

, s t r l str2.
strl [ startl}
s t r 2 [ start2]
count . , strl
s t r 2 , , strl -
str2-4ac, ,
s t r l s t r 2

public static int


Compare(string strl,
int startl,
string str2,
int start2,
int count,
bool ignoreCase)

, strl str2.
s t r l
[startl]
str2 [start2]
count . , s t r l
s t r 2 , , strl-
st2-, ,
s t r l s t r 2 . ignoreCase t r u e ,
.

public static int


Compare(string strl,
int startl,
string str2,
int start2,
int count,
bool ignoreCase,
Culturelnfo ci)

, s t r l str2%
( , ), ci.
stri[starti]

str2[start2]
count . , strl str2x , strl str2-4acTn, ,
strl s t r 2 . ignoreCase t r u e ,
.
. c u l t u r e l n f o S y s t e m . G l o b a l i z a t i o n

546

II. #

. 20.1

public static int


CompareOrdinal(string strl,
string str2)

, strl, ,
str2, ,
. , strl str2,
, s t r l str2, , strl
str 2

public static int


CompareOrdinal(string strl,
int startl,
string str2,
int start2,
int count)

, strl str 2,
, .
strl[startl]
str2[start2] count
. ,
strl str2, , stri- str2-4ac, , strl str2

Public int CompareTo(object str)

, str. , str, ,
str, ,
, str. , str, ,
str, ,

Public int CompareTo(string str)


() . , 7, "+". , ,
String. "+" , .
, , Concat (),
:
public s t a t i c string Concat(string s t r l , string str2)
, str2, strl.
Concat () :
public static string Concat(string strl,
string str2,
string str3)

, strl, str2 str3. ,


"+", Concat ().
Concat () ,
:
public s t a t i c string Concat(params s t r i n g [ ] strs)

20.

547

Concat () . Concat () :
// Concat().
using System;
class ConcatDemo {
public s t a t i c void Main() {
s t r i n g r e s u l t = String.Concat(
" " , " " ,
" " , " " , " " ,
" " , " " ,
"String.");
Console.WriteLine(":

" + result);

:
: String.
Concat string-, a object-.

, .
Concat () :
public static string Concat(object vl, object v2)
public static string Concat(object vl,
object v2,
object v3)
public static string Concat(params object[] v)
, v2, vl. , vl, v2 v3. , , "" v.
, :
// C o n c a t ( ) .
using System;
class ConcatDemo {
public static void Main() {
string result = String.Concat(" ", 10, " ",
20.0, " ",
false, " ",
23.45M);
Console.WriteLine(": " + r e s u l t ) ;

548

II. #

:
: 10 20 False 23.45
Concat () .
T o S t r i n g O , . ,
10 Int32 .ToString (). Concat ()
. Concat ()
, .


s t r i n g ,
( ).
.
, indexOf (),
:
public int IndexOf(char ch)
public int IndexOf(string str)
IndexOf (), ,
ch .
str. 1,
.
,
Last IndexOf (), :
public int LastlndexOf(char ch)
public int LastlndexOf(string str)
LastlndexOf (), , ch . s t r . 1,
.
s t r i n g : IndexOf Any ()
LastlndexOf Any (). ,
. :
public int IndexOfAny(char[] a)
public int LastlndexOfAny(char[] a)
IndexOf Any ()
, . LastlndexOf Any ()
, . 1,
.
,
.
StartsWith () EndsWith ():
public bool StartsWith(string str)
public bool EndsWith(string str)
StartsWith () t r u e , , str. EndsWith () t r u e , , str. f a l s e .
20.

549

:
// .
using System;
class StringSearchDemo {
public static void Main() {
string str =
"C# .";
int idx;
Console.WriteLine("str: " + str);
idx = str.IndexOf( f c f );
Console.WriteLine(
" ' 1 : " + idx) ;
idx = str.LastlndexOf('');
Console.WriteLine(
" f c f : " + idx);
idx = str.IndexOf("");
Console.WriteLine(
" \"\": "
+ idx);
idx = str.LastlndexOf("");
Console.WriteLine(
" \"\": "
+ idx);
char[] chrs = { f a f , ' 1 , '' };
idx = str.IndexOfAny(chrs) ;
Console.WriteLine(
" f a', '' ' 1 : " + idx);
if(str.StartsWith("C# "))
Console.WriteLine(
"str \"# \"");
if(str.EndsWith("."))
Console.WriteLine(
"str \".\"");

:
str:
C# .
'': 20
' 1 : 41
"": 17
"": 28
'a', f f f f : 4
str "# "
str "."
,
.

550

II. #

, S t r i n g ,
. 20.2.
20.2. , string

public bool
EndsWith(string

str)

t r u e ,
, str.
f a l s e

public int IndexOf(char ch)

ch
. - 1 ,

public int
IndexOf(string str)

s t r . - 1 ,

public int

ch
. , start. - 1 ,

IndexOf(char ch,
int start)
public int
IndexOf(string str,
int start)

s t r . , start. - 1 ,

public int IndexOf(char ch,


int start,
int count)

ch
. , start, count .
- 1 ,

public int
IndexOf(string str,
int start,
int count)

s t r . , start, count . - 1 ,

public int
IndexOfAny(char[] a)

, . - 1 ,

public int
IndexOfAny(char[] a,
int start)

, . ,
start. - 1 ,

public int
IndexOfAny(char[] a,
int start,
int count)

, . ,
s t a r t , count . - 1 ,

public int
LastlndexOf(char ch)

ch
. -1,

public int
LastlndexOf(string str)

s t r . - 1 ,

public int
LastlndexOf(char ch,
int start)

ch, .
, , start, .
- 1 ,

20.

551

. 20.2

public int
LastlndexOf(string str,
int start)

s t r , .
, , start, . - 1 ,

public int
LastlndexOf(char ch,
int start,
int count)

ch, .
, , start,
count .
- 1 ,

public int
LastlndexOf(string str,
int start,
int count)

s t r , . , ,
start,
count . - 1 ,

public int
LastlndexOfAny(char[] a)

, .
- 1 ,

public int
LastlndexOfAny(char[] a,
int start)

, .
, ,
s t a r t , . - 1 ,

public int
LastlndexOfAny(char[] a,
int start,
int count)

, .
, ,
s t a r t , count .
- 1 ,

public bool
StartsWith(string str)

t r u e ,
, s t r .
f a l s e


()
. .
"" . s t r i n g
Split (), Join ().
Split () :
public s t r i n g [ ] split(params char[] seps)
public s t r i n g [ ] split(params char[J seps, i n t count)
, . ,
, seps. seps
null-, . , count.
Join ():

552

II. #

public static string Join(string sep, string[] strs)


public static string Join(string sep, string[] strs,
int start, int count)
J o i n ( ) , , strs.
, count , strs, strs[start].
, , , sep.
S p l i t () J o i n ( ) :
// .
using System;
class SplitAndJoinDemo {
public static void Main() {
string str =
" , .";
char[] seps = { ', '. ', ', ',};
// ,
string[] parts = str.Split(seps);
Console.WriteLine(
" : " ) ;
for(int i=0; i < parts.Length; i++)
Console.WriteLine(parts[i]);
// ,
string whole = String.Join(" | ", parts);
Console.WriteLine(" : " ) ;
Console.WriteLine(whole);

:
:

:
| | | |
| | | | | |
,
, . , , S p l i t () , " , 100" (, "" "100").
20.

553

, "" ( ), " ". . , , 10 + 5, .


// .
using System;

class TokenizeDemo {
public s t a t i c void MainO {
s t r i n g [ ] input = {
"100 + 19",
"100 / 3.3",
"-3 * 9",
"100 - 87"
char[] seps = { '

};

for(int i=0; i < input.Length; i++) {


// ,
string[] parts = input[i].Split(seps);
Console.Write(": " ) ;
for(int j=0; j < parts.Length; j++)
Console.Write(parts[j] + " " ) ;
Console.Write(", : " ) ;
double n = Double.Parse(parts[0]);
double n2 = Double.Parse(parts[2]);
switch(parts[1]) {
case "+":
Console.WriteLine(n
break;
case lf-":
Console.WriteLine(n
break;
case "*":
Console.WriteLine(n
break;
case "/":
Console.WriteLine(n
break;

+ n2) ;
- n2);
* n2);
/ n2);

:
: 100 + 19 , : 119
: 100 / 3.3 , : 30.3030303030303
: - 3 * 9 , : -27
: 100 - 87 , : 13

554

II. #


. , , .
, "print".

. , , "" . ,
, , ""
. , ,
. , # , .
,
Trim ():
public string Trim()
public string Trim(params char[] chrs)

. , chrs. , .
#
. ""
:
p u b l i c s t r i n g PadLeft(int len)
p u b l i c s t r i n g PadLeft(int lenr char ch)

,
len. , , ch.
, .
"" :
p u b l i c s t r i n g PadRight(int len)
public s t r i n g PadRight(int lenf char ch)
,
len. ,
, ch. , .
:
1
//
//

using System;
c l a s s TrimPadDemo {
public s t a t i c void Main() {
s t r i n g s t r = "";
Console.-WriteLine(" :

20.

" +str);

555

// .
str = str.PadLeft(10);
Console.WriteLine("|" + s t r + " I " ) ;
// .
str = str.PadRight(20);
Console.WriteLine("I" + s t r + " I " ) ;
// .
str = str.TrimO ;
Console.WriteLine("|" + str + " I " ) ;
// "" "#".
str = str.PadLeft(10, # ) ;
Console.WriteLine("I" + str + " I " ) ;
// "" "#".
str = str.PadRight(20, ' # ' ) ;
Console.WriteLine("I" + str + " I " ) ;
// "#".
str = str.Trim('#');
C o n s o l e . W r i t e L i n e ( " | " + s t r+ " I " ) ;

:
:
|
|
|

|
I |
|###### |
|################|
I !

,
i n s e r t () :
public s t r i n g I n s e r t ( i n t start, s t r i n g s t r )
s t r , .
() start. ,
.
Remove () :
public string Remove(int start, int count)
count. (),
, start. ,
.
Replace ()
. :
public string Replace(char chl, char ch2)
public string Replace(string strl, string str2)

chl 2.

556

II. #

strl str2. , .
,
Insert(), Remove() Replace():
// , .
using System;
class InsRepRevDemo {
public static void Main() {
string str = " ";
Console.WriteLine(" : " + str);
// .
str = str.Insert(4, " " ) ;
Console.WriteLine(str);
// .
str = str.Replace("", "");
Console.WriteLine(str);
// .
str = str.Replace('', ' X ' ) ;
Console.WriteLine(str);
// ,
str = str.Remove(4, 5 ) ;
Console.WriteLine(str);

:
:



""
S t r i n g ,
"", .. . ToUpper ()
ToLower():
public string ToLower()
public string ToUpper()
ToLower () , ToUpper () . , . ,
, ,
.

20.

557

Substring ()
S u b s t r i n g () . :
public string Substring(int idx)
public string Substring(int idx, int count)
,
idx, . , , idx, count . .
S u b s t r i n g () :
// S u b s t r i n g ( ) .
using System;
class SubstringDemo {
public static void Main() {
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("str: " + str);
Console.Write("str.Substring(15): " ) ;
string substr = str.Substring(15);
Console.WriteLine(substr);
Console.Write("str.Substring(O, 15): " ) ;
substr = str.Substring(0, 15);
Console.WriteLine(substr);

:
str: ABCDEFGHIJKLMNOPQRSTUVWXYZ
str.Substring(15): PQRSTUVWXYZ
str.Substring(O, 15): ABCDEFGHIJKLMNO

(, i n t double)
, , . #
, . , I, .
, Console.WriteLine (),
S t r i n g . Format () ToString ().
, , , .

558

II. #


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

I Format Provider. .NET
Framework. , ,
.
.
3, . W r i t e L i n e O , ,
.
W r i t e L i n e O ,
W r i t e L i n e O :
WriteLine("_",
arglf
. . . , argN) ;
WriteLineO , " + " . _ : "" "". , " ",
.
:
{_, : }
_
( ). , .
. , , . , {0} , {1} argl ..
WriteLineO
, ( ) , _. , _ , , .
fmt,
. . width
, , ,
, . width ,
20.

559

, ,
.
.


, , . 20 3.
. , , ,
, , F2.
, , , . , , , , .

. , ,
, .
, > :
//
// .
using System;
class FormatDemo {
public static void Main() {
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
Console.WriteLine("{0:F2}", v ) ;
Console.WriteLine("{0:N5}",v ) ;
Console.WriteLine("{0:e}", v ) ;
Console.WriteLine("{0:r}", v ) ;
Console.WriteLine("{0:p}", v 2 ) ;
Console.WriteLine("{0:X}", x ) ;
Console.WriteLine("{0:012}",x ) ;
Console.WriteLine("{0:}", 18 9.99);

:
17688.66
17,688.65849
1.768866+004
17688.65849
15.00 %
560

II. #

15
000000000021
$189.99
,
.

20.3.

(
)

( )

( )

- F

. F

- f

. f

(
)

,
P a r s e () "" ( " ".)

( -

A-F)

a-f)

S t r i n g . Format ()
T o s t r i n g ()
WriteLine ()
,
, ,
. ,
20.

561

, .
GUI-, Windows, - .
: s t r i n g . Format ()
ToString ().

S t r i n g . Format ()


Format (), string (
. 20.4). Format () WriteLineO, , Format () , .
20.4. Format ()

public static string


Format(string str,
object v)

v , s t r .
s t r ,

public static string


Format(string str,
object vl,
object v2)

vl , s t r , v2 . s t r ,

public static string


Format(string str,
object vl,
object v2,
object v3)
public static string
Format(string str,
params object[] v)

vl, v2 v3 , s t r .
s t r ,

public static string


Format(
. IFormatProvider fmtprvdr,
string str,
params object [] v)

, v,
, s t r ,
,
fmtprvdr.
str,

, v,
, str. s t r ,

,
, S t r i n g . Format ( ) . .
// String.Format()
// .
using System;
class FormatDemo {
public static void Main() {
562

II. #

double v = 17688-65849;
double v2 = 0.15;
int x = 21;
string str = String.Format("{0:F2}", v) ;
Console.WriteLine(str);
str = String.Format("{0:N5}",v ) ;
Console.WriteLine(str);
str = String.Format("{0:e}", v) ;
Console.WriteLine(str);
str = String.Format("{0:r}", v) ;
Console.WriteLine(str);
str = String.Format("{0:p}'\ v 2 ) ;
Console.WriteLine(str);
str = String.Format("{0:X}",
Console.WriteLine(str);

) ;

str = String.Formatr{0:D12}", x) ;
Console.WriteLine(str);
str = String.Format("{0:C}",
Console.WriteLine(str);

189.99);

WriteLine (), String. Format ()



. , 1 10:
//

Format().

using System;
class FormatDemo2 {
public static void Main() {
int i;
int sum = 0 ;
int prod = 1;
string str;
/*
1 10. */
for(i=l; i <= 10; i++) {
sum += i;
prod *= i;
str = String.Format(
":{0,3:D}
:{1,8:D}",
sum, prod);
Console.WriteLine(str) ;

20.

563

:
1
: 1 :
2
: 3 :

: :
24
: 10 :
120
: 15 :
: 21 :
720
: 28 :
5040
: 36 :
40320
: 45 : 362880
: 55 : 3628800
:
s t r = String.Format(":{0,3:D}
:{1,8:D}",
sum, p r o d ) ;

Format () :
( sum), ( prod). ,
,
WriteLineO.
(: :),
.

Tostring

, (, Int32
Double), ToString ():
p u b l i c s t r i n g T o S t r i n g ( s t r i n g fmt)
ToString ()
, fmt.
, 188.99,
:
string str = 189.99.ToString("");
,
ToString (). WriteLine () Format (), ( ), ToString () .
,
ToString ().
.
// ToString()
// .
using System;
class ToStringDemo {
public static void Main() {
double v = 17688.65849;
double v2 = 0.15;
int x = 21;

564

II. #

string str = v.ToString("F2");


Console.WriteLine(str);
str = v.ToString("N5") ;
Console.WriteLine(str) ;
str = v.ToString("e") ;
Console.WriteLine(str) ;
str = v.ToString("r") ;
Console.WriteLine(str);
str = v2.ToString("p");
Console.WriteLine(str);
str = x.ToString("X");
Console.WriteLine(str) ;
str = x.ToString("D12") ;
Console.WriteLine(str) ;
str = 189.99.ToString("C") ;
Console.WriteLine(str) ;

, #
, ,
(picture format).
, (.. ) ,
. I. .
{

-
, ,
. ,
. 20.5.
20.5. -,

,
%
0

20.

565

. 20.5

, ,

+ -
+0 -0

"" .
" # " . ( )
, ()
. . " # "
, , .
.
, " # " , . , " # " , . (
) . , ,
##.##, , .
, - "".
- "" ,
, .
, . ,
1 Console.^riteLine("{0:00##.#00}", 21.3);
:
| 0021.300
, , ( )
, ( ) .

,
" # " . ,
|

Console.WriteLine("{0:#,###.#}",

3421.3);

:
1 3,421.3.
, ""
.
( ) . ,
|

Console.WriteLine{"{0:#,###.#}",

8763421.3);

:
| 8,763,421.3.
"" .
( ),

566

II. #

. 1 000.
,
Console.WriteLine(
" : { 0 : # , # # # , . # } " , 8763421.3);

:
I : 8,7 63.4
, , .
-
. , , , . ,
Console.WriteLine(
" {0:##.# }",
21.3);

:
I 21.3
, \ t \.
- ,
( ).
"0". " 0 " , .
. - ,
().
+ +, : , , - -.
" ; " ,
, . -
" ; " :
- ; - ; -

:
Console. WriteLine ("{0 :#.##; (#.##) ;0.00}lf, num) ;
num , . num ,
. num ,
0.00. - " ; "
. , , - .
, - . - - " ".

, :
// .
using System;
20.

567

class PictureFormatDemo {
public static void Main{) {
double num = 64354.2345;
Console.WriteLine(" : " + num);
// .
Console.WriteLine(
" : " +
"{0:#.##}", num);
//
// .
Console.WriteLine(" : {0:#,###.##}",
num) ;
//
// .
Console.WriteLine(
" : " +
"{0:#.###+00}", num);
// .
Console.WriteLine(" : " +
"{0:#0,}", num);
/* ,
-. */
Console.WriteLine(" , " +
" " +
" -.");
Console.WriteLine("{0:#.#; (#.##); 0.00}", num) ;
num = -num;
Console.WriteLine("{0:#.##;(#.##);0.00}", num);
num = 0 . 0 ;
Console.WriteLine("{0:#.##; (#.##); 0 . 00}", num);
// ,
num = 0.17;
Console.WriteLine(" : {0:#%}",
num) ;

:
: 64354.2345
: 64354.23
: 64,354.23
: 6.435+04
: 64
,
.
64354.2
(64354.23)
0.00
: 17%

568

II. #

-J
,
DateTime. 19, DateTime .
. :
02/25/2002
Monday, February 25, 2002
12:59:00
12:59:00
,
. # .
, . 20.6. ,
,
.
20.6.


;
(Universal Time Coordinated UTC)
l

,
, :
// .
u s i n g System;
c l a s s TimeAndDateFormatDemo {
20.

569

public static void Main() {


DateTime dt = DateTime.Now; // .
Console.WriteLine(" d: {0:d}"f dt) ;
Console.WriteLine(" D: {0:D}", dt);
Console.WriteLine(" t: {0:t}", dt) ;
Console.WriteLine(" T: {0:T}", dt) ;
Console.WriteLine(" f: {0:f}", dt) ;
Console.WriteLine(" F: {0:F}", dt) ;
Console.WriteLine(" g: {0:g}", dt) ;
Console.WriteLine(" G: {0:G}", dt) ;
Console.WriteLine(" m: {0:m}", dt);
Console.WriteLine(" M: {0:M}", dt) ;
Console.WriteLine(" : {0:r}"f dt) ;
Console.WriteLine(" R: {0:R}", dt) ;
Console.WriteLine(" s: {0:s}", dt);
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
Console.WriteLine ("

u:
U:
:
Y:

{0:u}"/
{0:U}",
{0:y}",
{0^}",

dt);
dt);
dt);
dt) ;

:
d: 10.09.2003
D: 10 2003 .
t: 14:53
: 14:53:11
f: 10 2003 . 14:53
F: 10 2003 . 14:53:11
: 10.09.2003 14:53
G: 10.09.2003 14:53:11
: 10
: 10
: Wed, 10 Sep 2003 14:53:11 GMT
R: Wed, 10 Sep 2003 14:53:11 GMT
s: 2003-09-10T14:53:11
u: 2003-09-10 14:53:11Z
U: 10 2003 . 11:53:11
: 2003 .
Y: 2003 .
. . .
( ) T o S t r i n g O ,
DateTime. (\).
I // .

I
| using System;

570

II. #

class SimpleClock {
public static void MainO {
string t;
int seconds;
DateTime dt = DateTime.Now;
seconds = dt.Second;
for(;;) {
dt = DateTime.Now;
// '
// seconds,
if(seconds != dt.Second) {
seconds = dt.Second;
t = dt.ToString("T");
if(dt.Minute==O && dt.Second==0)
t = t + "\a"; //
/ / .
Console.WriteLine (t);


, .
, . , () , ,
. -,
. 20.7.
, , d, f, g, m, M, s t , ,
. 20.6. , , . . , , (%).
:
//
// .
(

using System;
class CustomTimeAndDateFormatsDemo {
public s t a t i c void MainO {
DateTime dt = DateTime.Now;
20.

571

Console.WriteLine(": {0:hh:mm tt}", dt) ;


Console.WriteLine(
" 24- : {0:HH:mm}", dt);
Console.WriteLine(": {0:ddd dd, yyyy}", dt) ;
Console.WriteLine(": {0:gg}", dt) ;
Console.WriteLine(" : " +
"{0:HH:mm:ss tt}", dt) ;
Console.WriteLine(" m : {0:m}",
dt) ;
Console.WriteLine(" m : {0:%m}",
dt);

:
: 11:14
24- : 11:14
: 11, 2003
: A.D.
: 11:14:52
m : 11
m : 14
: A.D. . . anno Domini, .. .
20.7. -,

, 1-31

dd

, 1-31. 1-9

ddd

dddd
f, ff,
fffff,
fffffff


fff,
ffff,
ffffff,

1-12
1-12. 1-9
0-23
0-23. 1-9

. 1-9
1-12
1-12. 1-9

hh
H
HH

m
mm
M
MM

MMMM
s

572

II. #

. 20 7

ss

. 1-9

"" "", . ( ) P.M. ( ),

tt

AM. P.M.

. 1 -9

zz

. 1-9

zzz

%fmt

, fmt

_J
# , .

. , ,
. 20.8. G F. ,
, Flags.
,
. Flags G
. F
, ,
, .
:
// .
using System;
class EnumFrntDemo {
enum Direction { , , , }
[Flags] enum Status { =01, _=02,
=04, _=08,
_=010,
_=020 }
public static void Main() {
Direction d = Direction.;
Console.WriteLine("{0:G}", d) ;
Console.WriteLine("{0:F}", d ) ;
Console.WriteLine("{0:D}", d) ;
Console.WriteLine("{0:X}", d ) ;
20.

573

Status s = Status. I Status.__;


Console.WriteLine("{0:G}",
Console.WriteLine("{0:F}",
Console.WriteLine("{0:D}",
Console.WriteLine("{0:X}",

s);
s);
s);
s);

3
00000003
, _
, __
9
00000009

20.8.

. Flags,
( ,
)

. ,
, ,
, , Flags

>

574

II. #

1
# , ,
^ ^ (multithreaded programming). ,
.
(thread), . , .
, #, , .NET Framework. , , , # , .

I
:
. . . , ,
, , . , , , (
) Internet. -
, .
. ,
, ,
. , . ,
- , .
, - -
. -
, -
.
,
, (), . , - ( ,
) ,
().
( ). , , . ,
,
, Internet.
.
. ( ).
, ..
. .
576

II. #

. , ,
() .
.NET Framework :
(foreground) , (background).
, , .. . -
, ,
.
-
, ,
. # , , .
,
(main thread), . ,
. .
# .NET Framework -, . , #,
, , . ,
, , . , #
.
, # ,
C++ ( ).
, ,
System.Threading.
:
I u s i n g System.Threading;

Thread
# Thread, . Thread sealed-, .. . Thread .
.


, Thread. Thread
:
public Thread(ThreadStart entryPoint)
entryPoint , ,
. ThreadStart ,
.NET Framework:
public delegate void ThreadStart()

21.

577

, void .
, Start (), Thread. :
public void S t a r t ( )
, , , entryPoint. entryPoint . s t a r t () , , ThreadstateException. He , Thread System. Threading.
:
// .
using System;
using System.Threading;
class MyThread {
public int count;
string thrdName;
public MyThread(string name) {
count = 0;
thrdName = name;
}
// ( ) ,
public void run() {
Console.WriteLine(thrdName + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrdName +
", count - " + count);
count++;
} while(count < 10);
Console.WriteLine(thrdName + " .");

class MultiThread {
public static void Main() {
Console.WriteLine(" .");
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(new ThreadStart(mt.run));
// , .
newThrd.Start();
do {
Console.Write<".");
578

II. #

Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine (" .tf) ;

. MyThread . run() ,
"" 0 9. S l e e p ( ) ,
Thread. Sleep () , , , . :
public static void Sleep(int milliseconds)
milliseconds
,
. milliseconds
, ,
.
Main()
Thread:
// MyThread.
MyThread mt = new MyThread(" # 1 " ) ;
// .
Thread newThrd = new Thread(new T h r e a d S t a r t ( m t . r u n ) ) ;
// ,
newThrd.Start();

, MyThread.
Thread mt. run , . ,
s t a r t () .
run () . s t a r t ()
Main (), do.
, , . :
.
. #1 .
.... #1, count = 0
#1, count = 1
.... #1, count = 2
#1, count = 3
.... #1, count = 4
#1, count = 5
#1, count =
.... #1, count = 7
#1, count = 8
.... #1, count = 9
#1 .
.
, .
, . ,
21.

579

.
,
. , do , count 10.
count 10 ,
newThrd, .
.


,
. -, .
MyThread Thread MyThread. -,
MyThread, Thread Name, . Name :
p u b l i c s t r i n g Name { g e t ; s e t ; }
Name , .
:
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name; // .
thrd.Start(); // .
}
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10) ;
Console.WriteLine(thrd.Name + " .");

class MultiThreadlmproved {

580

II. #

public static void Main() {


Console.WriteLine(" .");
// MyThread.
MyThread rat = new MyThread (" #1");
do {
Console.Write (".");
Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine(" .");

, .
, t h r d
MyThread.


. , auHH. , :
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// .
void run() {
Console.WriteLine(thrd.Name + " .");

do {
Thread.Sleep(500);
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10);
Console.WriteLine(th d.Name + " .");

class MoreThreads {
public static void MainO {
21.

581

Console.WriteLine(" .");
//
MyThread mtl =
MyThread mt2 =
MyThread mt3 =

.
new MyThread(" #1");
new MyThread(" #2");
new MyThread(" #3");

do {
Console.Write(".");
Thread.Sleep(100);
} while (mtl.count < 10 I
mt2.count < 10 |
mt3.count < 10);

Console.WriteLine(" .");

:
.
. #1 .
#2 .
#3 .
.... #1, count = 0
#2, count = 0
#3, count = 0
#1, count = 1
#2, count = 1
#3, count = 1
.... #1, count = 2
#2, count = 2
#3, count = 2
#1, count = 3
#2, count = 3
#3, count = 3
.... #1, count = 4
#2, count = 4
#3, count = 4
#1, count = 5
#2, count = 5
#3, count = 5
#1, count =
#2, count =
#3, count -
.... #1, count = 7
#2, count = 7
#3, count - 7
#1, count = 8
#2, count = 8
#3, count = 8
.... #1, count = 9
#1 .
#2, count = 9
#2 .
#3, count = 9
#3 .
.

582

II. #

, . - ,

.

, . count, . , Thread ,
. i s A l i v e .
:
public bool IsAlive { get; }
I s A l i v e t r u e , , , . f a l s e .
,
MoreThreads , :
// I s A l i v e
// ,
c l a s s MoreThreads {
p u b l i c s t a t i c void Main() {
Console. WriteLine (" . 1 1 ) ;
//
MyThread mtl =
MyThread mt2 =
MyThread mt3 =

.
new MyThread(" # 1 " ) ;
new MyThread(" # 2 " ) ;
new MyThread(" # 3 " ) ;

do {
Console.Write(".");
Thread.Sleep(100);
} while (mtl.thrd.IsAlive &&
mt2.thrd.IsAlive &&
mt3.thrd.IsAlive);
Console.WriteLine(" .");
MoreThreads
.
, IsAlive.
, "" ,
Join (). :
public void Join()
Join () , , , .
("join" . . )
21.

583

, . ,
ThreadStateException. J o i n O , .
, ,
, J o i n ():
// J o i n ( ) .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start() ;
}
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
do {
Thread.Sleep(500) ;
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10) ;
Console.WriteLine(thrd.Name + " .");

// Join() ,
class JoinThreads {
public static void Main() {
Console.WriteLine(" .");
//
MyThread mtl =
MyThread mt2 =
MyThread mt3 =

.
new MyThread(" #1");
new MyThread(" #2");
new MyThread(" #3");

mtl.thrd.Join() ;
Console.WriteLine(" #1 .");
mt2.thrd.Join();
Console.WriteLine(" #2 .");
mt3.thrd.Join();
Console.WriteLine(" #3 .");

584

II. #

Console.WriteLine(" .");

. , , , .
.
#1 .
#2 .
#3 .
#1, count

#2, count

#3, count
#1, count
#2, count
#3, count
#1, count
#2, count
#3, count
#1, count
#2, count
#3, count
#1, count
#2, count
#3, count
#1, count
#2, count
#3, count
#1, count
#2, count

#3f count

#1, count

#2, count

#3, count

#1, count

#2, count

#3, count

#1, count

#1 .
#2, count
#2 .
#3, count
#3 .
#1 .
#2 .
#3 .
.

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

0
0
0
1
1
1
2
2
2
3
3
3
4
4
4
5
5
5

7
7
7
8
8
8
9

= 9
= 9

, Join () .

I s B a c k g r o u n d
, .NET Framework : . ,
, 21.

585

, . .
IsBackground, Thread
:
public bool IsBackground { g e t ; s e t ; }
,
IsBackground true. f a l s e ,
.


. , ,
, .
, . , , ,
, .
, ( ),
, . , ,
, , . , .
.
Priority,
Thread. :
public ThreadPriority P r i o r i t y ! g e t ; s e t ; }
ThreadPriority , :
ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority. BelowNoritial
ThreadPriority.Lowest

ThreadPriority
.Normal.
, ,
, , .
MyThread. run () ,
.
1 000 000 000, , stop true. stop f a l s e .
, "" 1 000 000 000, stop
true. (
, ).
currentName .
, , . 586

II. #

, currentName . ,
. , .
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
static bool stop = false;
static string currentName;
/* . ,

. */
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
currentName = name;
}
// ,
void run() {
Console. WriteLine (" " + thrd. Name + " .11);
do {
count++;
if(currentName != thrd.Name) {
currentName = thrd.Name;
Console.WriteLine(" " + currentName);
}
} while(stop == false && count < 1000000000);
stop = true;
Console.WriteLine(" " + thrd.Name + " .");
}
class PriorityDemo {
public static void Main() {
MyThread mtl = new MyThread(" ");
MyThread mt2 = new MyThread(" ");
// .
mtl.thrd.Priority = ThreadPriority.AboveNormal;
mt2.thrd.Priority = ThreadPriority.BelowNormal;
// ,
mtl.thrd.Start();
mt2.thrd.Start();

21.

587

mtl.thrd.Join();
mt2.thrd. JoinO ;
Console.WriteLine();
Console.WriteLine(" " + mtl.thrd.Name +
11
" +
mtl.count);
Console.WriteLine(" " + mt2.thrd.Name +
" " +
mt2.count);

1- Pentium, Windows 2000:
.

.










.
.
1000000000
25600064
, 98% . , ,
, , , . Windows.
-,
, . , , , .
, , .

. .
, , . ,
,
588

II. #

. . ,
, , "" . , ,
. "" .
, ..
. , ,
. ,
.
#,
. lock. # ,
.
lock :
lock(object) {
// , .
}

object .
, . lock , , , , . ,
. .

s u m l t o ,
:
// lock
// .
using System;
using System.Threading;
class SumArray {
int sum;
public int sumlt(int[] nums) {
lock(this) { // ,
sum = 0 ;
// .
for(int i=0; i < nums.Length; i++) {
sum += nums[i];
Console.WriteLine(
" " +
Thread.CurrentThread.Name +
" " + sum);
Thread.Sleep(10); // .
}
return sum;

c l a s s MyThread {

21.

589

public Thread thrd;


inttl a;
int answer;
/* SumArray
MyThread. */
static SumArray sa = new SumArray (*) ;
// .
public MyThread(string name, int[] nums) {
a = nums;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start(); // .
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
answer = sa.sumlt(a);
Console.WriteLine(" " + thrd.Name +
" " + answer);
Console.WriteLine(thrd.Name + " .");

class Sync {
public static void Main() {
int[] a - {1, 2, 3, 4, 5};
MyThread mtl = new MyThread(" #1", a ) ;
MyThread mt2 = new MyThread(" #2", a ) ;
mtl.thrd.Join();
mt2.thrd.Join();

:
#1 .
#2 .






#1 15
#1 .




#2 15
#2 .

590

#1
#1
#1
#1
#1
#2

1
3
6
10
15
1

#2
#2
#2
#2

10
15

II. #

, .
. .
SumArray. sumlt (), . , MyThread, s t a t i c sa SumArray. , MyThread SumArray. . ,
sum SumArray. ,
sumlt () , sum "" . , sumlt () . ,
Sync, " ", .. .
sumlt () lock . , t h i s .
lock, .
Sleep () , (
), . sumlt ()
, . ,
, , sumlt ()
, () . .
lock,
sumlt (). sumlt () ,
.
, sum ,
, sumlt (). ,
sumlt () ,
, sum
. , ,

lock sumlt ():
#1 .
#1 1
#2 .
#2 1
#1 3
#2 5
#1 8
#2 11
#1 15
#2 19
#1 24
#2 29
#2 29
#2 .
^
#1 29
#1 .
, sumlt () , sum .
, lock.

21.

591

1. lock
, ,
.
2. , , ,
.
3. , .
, lock
, p r i v a t e - , internal-.
.


, , , , , . , , ,
.
, , , . , , lock
. ? ,
:
( ) , lock. , .
, sumit() . sumlt () MyThread.
// lock
// .
using System;
using System.Threading;
class SumArray {
int sum;
public int sumlt(int[] nums) {
sum = 0 ; // .
for(int i=0; i < nums.Length; i++) {
sum += nums[i];
Console.WriteLine(
" " +
Thread.CurrentThread.Name +
" " + sum);
Thread.Sleep(10); // .
}
return sum;

class MyThread {
592

II. #

public Thread thrd;


int[] a;
int answer;
/* SumArray
MyThread. */
static SumArray sa = new SumArray();
// .
public MyThread(string name, int[] nuras) {
a = nums;
thrd = new Thread(new T h r e a d S t a r t ( t h i s . r u n ) ) ;
thrd.Name = name;
t h r d . S t a r t ( ) ; // .
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
// lock sumlt().
lock(sa) answer = sa.sumlt(a);
Console.WriteLine(" " + thrd.Name +
" " + answer);
Console.WriteLine(thrd.Name + " .");

class Sync {
public static void Main() {
int[] a - / { i f 2, 3, 4, 5};
MyThread mtl = new MyThread(" #1", a ) ;
MyThread mt2 = new MyThread(" #2", a ) ;
mtl.thrd.Join();
mt2.thrd.Join() ;

sa.sumltO,
sumlt (). :
I/ lock sumlt().
lock(sa) answer = sa.sumlt(a);

,
.


,
, static-,
, . . static-,
lock :
21.

593

lock(typeof{class) ) {
// .
}

class , static-,
.

Monitor lock
lock ,
, Monitor, System. Threading. Monitor . , , Enter (), Exit (). :
public static void Enter(object syncOb)
public static void Exit(object syncOb)
syncOb . Enter() , ,
. Microsoft , lock-
" " Enter ()
Exit (). lock #, #- .
TryEnterO Monitor.
:
public s t a t i c bool TryEnter(object syncOb)
true,
syncOb, f a l s e . , , .
Monitor : Wait(), Pulse () PulseAlK).
.


Wait(), Pulse() HPulseAll()
. ( )
lock- ( R), .
2? R, , .
, . ,
"" , .
R , , . , , ,
, . #
Wait (), Pulse () PulseAll ().
Wait (), Pulse () PulseAll () Monitor. lock- . 594

II. #

, Wait , ..
("") ,
. ,
Pulse PulseAlK), "" "". Pulse () , , . PulseAll () .
wait ():
p u b l i c s t a t i c bool Wait(object waitOb)
p u b l i c s t a t i c bool Wait(object waitOb, i n t
milliseconds)
. , .
waitOb , .
Pulse () PulseAll () :
p u b l i c s t a t i c void Pulse(object waitOb)
p u b l i c s t a t i c void PulseAll(object waitOb)
waitOb , .
Wait (), Pulse () PulseAll () ,
lock-, SynchronizationLockException.

W a i t ( ) P u l s e ( )
Wait() Pulse ,
,
"" "". TickTock, : t i c k () tock (). t i c k () "", tock ()
"". " " ,
t i c k (), tock (). ,
"-", .. "", "".
// Wait() Pulse()
// .
using System;
using System.Threading;
c l a s s TickTock {
public void tick(bool running) {
lock(this) {
if(!running) { // .
Monitor.Pulse(this); //
// ,
return;
}

Console.Write("");
Monitor.Pulse(this); //
// t o c k ( ) .
Monitor.Wait(this); //
// tock().

21.

595

public void tock(bool running) {


lock(this) {
if(!running) { // .
Monitor.Pulse(this); //
// ,
return;
Console.WriteLine("");
Monitor.Pulse(this); //
// tick().
Monitor.Wait(this); //
// tick().

class MyThread {
public Thread thrd;
TickTock ttOb;
// .
public MyThread(string name, TickTock tt) {
thrd = new Thread(new ThreadStart(this.run));
ttOb = tt;
thrd.Name = name;
thrd.Start();
// ,
void run() {
if(thrd.Name == "") {
for(int i=0; i<5; i++) ttOb.tick(true);
ttOb.tick(false);
}
else {
for(int i=0; i<5; i++) ttOb.tock(true);
ttOb.tock(false);

class TickingClock {
public static void Main() {
TickTock tt = new TickTock();
MyThread mtl = new MyThread("", tt) ;
MyThread mt2 = new MyThread("", tt) ;
mtl.thrd.Join();
mt2.thrd.Join();
Console.WriteLine(" ");

:
596

II. #







. Main()
TickTock t t , . run () MyThread "". , t i c k ( ) , t o c k ( ) . t r u e . "" ,
t r u e . (
f a l s e ) .
t i c k ( ) t o c k ( ) . t i c k (), :
p u b l i c void t i c k ( b o o l running) {
lock(this) {
i f ( ! r u n n i n g ) { // .
M o n i t o r . P u l s e ( t h i s ) ; //
// .
return;
}

Console.Write(" " ) ;
Monitor.Pulse(this); //
// t o c k ( ) .
Monitor.Wait(this); //
// t o c k ( ) .
, t i c k ( )
lock-. , Wait () Pulse () .
running. .
f a l s e , . Pulse ,
. , , () ,
"", Pulse () Wait (). Pulse () . Wait () t i c k ()
, Pulse (). , t i c k ( ) "", "" , .
tock() t i c k ( ) , , "". , "", Pulse (), Wait (). , t i c k () tock (), , , t i c k ( ) ...
, .
Pulse () ,
Wait (). ,
21.

597

t i c k () tock() Wait (). ,


. , Pulse () .
Pulse () , . , ""
<CTRL + . , Wait () tock () Pulse ,
tock () . ( t o c k O ) .
-
Wait () Pulse () "",
, TickTock . Wait () Pulse ().
// TickTock.
class TickTock {
public void tic(bool running) {
lock(this) {
if(!running) { / / ,
return;
Console.Write(" " ) ;

public void tock(bool running) {


lock(this) {
if(!running) { // ,
return;
Console.WriteLine("");

TickTock "" :


, t i c k () tock () !

,
, . (deadlock) , 598

II. #

, .
, , ,
. ,
, !
, , . , .
TickTock. , Pulse () t i c k () tock (), (.. tock () t i c k ())
, . , ,
. ,
. , "",
.

MethodlmplAttribute
MethodlmplAttribute, .
lock ,
. MethodlmplAttribute System.Runtime.CompilerServices. , , :
public MethodlmplAttribute(MethodlmplOptions opt)
opt .
MethodlmplOptions .Synchronized.
.
TickTock,
_ MethodlmplAttribute:
// MethodlmplAttribute
// .
using System;
using System.Threading;
using System.Runtime.CompilerServices;
class TickTock {
/*
tick() . */
[MethodlmplAttribute(MethodlmplOptions.Synchronized)]
public void tick(bool running) {
if(!running) { // .
Monitor.Pulse(this); //
// ,
return;
}
Console.Write(" " ) ;
Monitor.Pulse(this); //
21.

599

// tock().
Monitor.Wait(this); // ,
// tock().
}
/*
tock() . */
[MethodlmplAttribute(MethodlmplOptions.Synchronized)]
public void tock(bool running) {
if(!running) { // .
Monitor.Pulse(this); //
// ,
return;
Console.WriteLine("");
Monitor.Pulse(this); //
// tick().
Monitor.Wait(this); // ,
// tick().
}

class MyThread {
public Thread thrd;
TickTock ttOb;
// .
public MyThread(string name, TickTock tt) {
thrd = new Thread(new ThreadStart(this.run))
ttOb = tt;
thrd.Name = name;
v
thrd.Start();
// ,
void run() {
if(thrd.Name "") {
for(int i=0; i<5; i++) ttOb.tick(true);
ttOb.tick(false);
else {
for(int i=0; i<5; i++) ttOb.tock(true);
ttOb.tock(false);

class TickingClock {
public static void Main() {
TickTock tt = new TickTock();
MyThread mtl = new MyThread("", tt) ;
MyThread mt2 = new MyThread("", tt);

600

II. #

mtl.thrd. Join<) ;
mt2.thrd. Joint) ;
Console.WriteLine(" .");

TickTock
( "").
lock-
MethodlmplAttribute . . lock #,
.

,

. ,
.
, . ,
, .
.
.
, ,
.
Thread. Suspend(), Thread.Resume ( ) . :
public void Suspend()
public void Resume()
, ThreadStateException.
, , , .
, Thread.Abort ().
:
public void Abort()

Abort () ThreadAbortException ,
. .
, (
). ,
Abort () ,
, , ,
Abort () J o i n .
( ) Abort () . , f inally- .
, :
// , .
u s i n g System;
u s i n g System.Threading;

21.

601

class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
for(int i = 1; i < 1000;
Console.Write(i + " " ) ;
if ( (i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
Console.WriteLine(thrd.Name + " .");

class SuspendResumeStop {
public static void Main() {
MyThread mtl = new MyThread(" ");
Thread.Sleep(1000); //
// .
mtl.thrd.Suspend();
Console.WriteLine(" .");
Thread.Sleep(1000);
mtl.thrd.Resume();
Console.WriteLine(" .");
Thread.Sleep(lOOO);
mtl.thrd.Suspend();
Console.WriteLine(" . ") ;
Thread.Sleep(1000);
mtl.thrd.Resume();
Console.WriteLine(" .");
Thread.Sleep(1000) ;
Console.WriteLine(" .");
mtl.thrd.Abort();
mtl.thrd.Join(); // .
Console.WriteLine(" .");

602

II. #

:
.
1 2 3 4 5 6 7 8 9 10
II 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
.
41 42 43 44 45 46 47 48 49 50
.
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
.
81 82 83 84 85 86 87 88 89 90
.
91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110
III 112 113 114 115 116 117 118 119 120
.
.

Abort ()
Abort ( ) :
public void Abort(object info)
info , . E x c e p t i o n S t a t e
ThreadAbortException. , :
// Abort(object).
using System;
using System.Threading;
class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// ,
void run() {
try {
Console.WriteLine(thrd.Name + " .");
for(int i = 1; i <= 1000;
Console.Write(i + " " ) ;
Console.WriteLine();
Thread.Sleep(250);
Console.WriteLine(thrd.Name +
" .");
21.

603

} catch(ThreadAbortException exc) {
Console.WriteLine(
" , =
exc.ExceptionState);

class UseAltAbort {
public static void Main() {
MyThread mtl = new MyThread(" ");
Thread.Sleep(1000); //
// .
Console.WriteLine(" .");
mtl.thrd.Abort(100) ;
mtl.thrd.Join(); //
// .
Console.WriteLine(" .");

:
.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
.
41 42 43 44 45 46 47 48 49 50
, = 100
.
, Abort () 100. ExceptionState
ThreadAbortException, .

Abort ()
.
ThreadAbortException,
Reset Abort (). . Reset Abort () :
p u b l i c s t a t i c void ResetAbortO
ResetAbortO ,
, .
Reset Abort () :
// ResetAbortO.
using System;
using System.Threading;
class MyThread {
public Thread thrd;
604

II. #

public MyThread(string name) {


thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
// ,
void run() {
Console.WriteLine(thrd.Name + " .");
for(int i 1; i <= 1000; i++) {
try {
Console.Write(i + " ") ;
if ( (i%10)==0) {
Console.WriteLine() ;
Thread.Sleep(250);
}
} catch(ThreadAbortException exc) {
if((int)exc.ExceptionState = = 0 ) {
Console.WriteLine(
" ! = " +
exc.ExceptionState);
Thread.ResetAbort();
}
else
Console.WriteLine(
" ,
+ exc.ExceptionState);
Console.WriteLine(thrd.Name + " .")

class ResetAbort {
public static void Main() {
MyThread mtl = new MyThread(" ");
Thread.Sleep(1000); //
// .
Console.WriteLine(" .");
mtl.thrd.Abort(0); //
// .
Thread.Sleep(1000); //
// .
Console.WriteLine(" .");
mtl.thrd.Abort(100); //
// .
mtl.thrd.Join(); //
// .
Console.WriteLine(" .");

21.

605

:
.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
.
! = 0
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
.
, = 100
.
, , Abort () , , ResetAbort ()
, .
.


ThreadState,
Thread:
public Thread ThreadState{ get; }
,
ThreadState. :
ThreadState.Aborted

ThreadState.AbortRequested

ThreadState.Background

ThreadState.Running

ThreadState.Stopped

ThreadState.StopRequested

ThreadState.Suspended

ThreadState.SuspendRequested

ThreadState.Unstarted

ThreadState.WaitSleepJoin

. , ThreadState.WaitSleepJoin, , Wait (), Sleep () Join ().


,
, , .
.
, Thread,
. CurrentThread,
Thread. :
p u b l i c s t a t i c Thread CurrentThread{ g e t ; }
, . ,
606

II. #

CurrentThread, . ,
, .
, JOK, , :
// .
using System;
using System.Threading;
class UseMain {
public static void Main() {
Thread thrd;
// ,
thrd = Thread.CurrentThread;
// ,
if(thrd.Name == null)
Console.WriteLine(" .");
else
Console.WriteLine(" : " +
thrd.Name);
// .
Console.WriteLine(": " +
thrd.Priority);
Console.WriteLine();
// .
Console.WriteLine(" .\");
thrd.Name = " ";
thrd.Priority = ThreadPriority.AboveNormal;
Console.WriteLine(
" : " +
thrd.Name);
Console.WriteLine(" : " +
thrd.Priority);
}
}

:
.
: Normal
.
:
: AboveNormal
: . , Join ()
1 thrd.Join () ;

Main (), ,
, !
21.

607

f t ; -


""
( ). , ,
. ,
. : .
, !


#- ,
- . , , , . #
Process, System. Diagnostics.

S t a r t (), Process. :
public static Process Start(string name)
name ,
.
C l o s e ( ) ,
, . C l o s e () :
public void Close()
.
GUI-, Windows,
CloseMainWindowO, :
p u b l i c bool CloseMainWindowO
, .
t r u e , . f a l s e , GUI-
. , CloseMainWindowO
. , .
K i l l ( ) :
public void Kill()
K i l l . . , , , , .
Wa i t For E x i t ().
:
p u b l i c void WaitForExit()
p u b l i c bool W a i t F o r E x i t ( i n t
milliseconds)

608

II. #

, , . WaitForExit ( ) , , t r u e , , f a l s e , .
. Windows WordPad. exe.
// .
using System;
using System.Diagnostics;
class StartProcess {
public static void Main() {
Process newProc = Process.Start("wordpad.exe");
Console.WriteLine(" .");
newProc.WaitForExit();
newProc.Close(); // .
Console.WriteLine(" .");
WordPad,
" ". , WordPad. WordPad " ".

21.

603

# .
S y s t e m . C o l l e c t i o n s , . , ,
" " . , , , ,
-. #-.


,
.
.
, ArrayList, Hashtable, Stack Queue,
" ".
, .
.NET Framework : , . , , . , /.
object,
.
. , , .
, ,
.
, . , - B i t Array
, .

(), IEnumerator IEnumerable.
.
IEnumerable, , IEnumerator. , , ,
. ,
, for each.
. ++-, , #-
(Standard Template Library - STL), C++. ,
C++ , # .
Java. Java- Collections Framework, #-.

22.

611

-J
System. C o l l e c t i o n s .
, , . , , . 22.1.
.

I C o l l e c t i o n
I C o l l e c t i o n ,
. ,
. IEnumerable. He
I C o l l e c t i o n , .
I C o l l e c t i o n :

int

count { g e t ; }

bool
isSynchromzed { g e t ; }

t r u e , ,
f a l s e

o b j e c t syncRoot { g e t ; }

Count , , . Count , , . I C o l l e c t i o n :
void CopyTo (Array target,
mt
startldx)
CopyTo () ,
target, , s t a r t l d x . , CopyTo () #-.
I C o l l e c t i o n IEnumerable,
GetEnumerator ( ) :
IEnumerator GetEnumerator()
.
22.1.

ICollection

IEnumerable

G e t E n u m e r a t o r ( ) ,

IEnumerator

iList

iDictionary

, /

612

II. #

. 22.1

IDictionaryEnumerator

,
IDictionary

IComparer

Compare ( ) , ,

IHashCodeProvider

I L i s t
I L i s t I C o l l e c t i o n , . , I C o l l e c t i o n , I L i s t
( . 22.2). .
, NotSupportedException.
22.2. , I L i s t

int Add(object

obj)

obj . ,

void Clear()

bool Contains(
object obj)

t r u e , ,
obj, f a l s e

int IndexOf(object obj)

obj, () . obj , -1

void Insert(int idx,


object obj)

obj , idx. , i d x ,
, obj

void Remove(object obj)

void RemoveAt(int idx)

, , idx. , , , ""
obj . , , , ""

I L i s t Add().
, Add() o b j e c t . o b j e c t , . ( ),
(boxing).
Remove ()
RemoveAt ( ) . Remove () , RemoveAt () , . Clear ().

22.

613

, ,
C o n t a i n s ( ) . IndexOf ( ) , I n s e r t ( ) .
i L i s t :

bool IsFixedSize { get; }


bool IsReadOnly { get; }
, I s F i x e d S i z e
t r u e . ,
. ,
IsReadOnly t r u e . , .
I L i s t :
object this[int idx]

{ get; set; }

. . Add ( ) .
, .

I D i c t i o n a r y
I D i c t i o n a r y ,
. - , . ,
, I D i c t i o n a r y ,
/. . I D i c t i o n a r y i C o l l e c t i o n . , I D i c t i o n a r y , . 22.3.
NotSupportedException.
22.3. , I D i c t i o n a r y

v o i d A d d ( o b j e c t ,
o b j e c t v)

/, v. . ,
,
ArgumentException

void ciear()

b o o l c o n t a i n s (obj e c t )

t r u e ,
. f a l s e

iDictionaryEnumerator
GetEnumerator()
v o i d Remove (ob j e c t )

/ lDictionary-, Add (). , . - ,


Remove () .
Clear ().

614

II. #

, ,
Contains (), .
GetEnumerator () , IDictionary.
"" (/) .
I D i c t i o n a r y :

bool i s F i x e d S i z e { g e t ; }
bool isReadOnly { g e t ; }
i C o l l e c t i o n Keys { g e t ; }
i c o l l e c t i o n Values { get; }

t r u e ,
t r u e ,

, Keys Values , , .
I D i c t i o n a r y :
object t h i s [ o b j e c t key] { g e t ; s e t ; }
. .
, "" , .

IEnumerable, IEnumerator
IDictionaryEnumerator
IEnumerable ,
. , IEnumerable,
I C o l l e c t i o n . IEnumerable
GetEnumerator():
IEnumerator GetEnumerator()
. ,
IEnumerable
foreach.
IEnumerator, , .
, . , / (.. ),
GetEnumerator () IDictionaryEnumerator,
IEnumerator. IDictionaryEnumerator
IEnumerator
.
, IEnumerator,
.

IComparer
IComparer Compare (), :
i n t Compare(object vl, object v2)
22.

615

Compare () , vl v2, , vl v2, ,


. .

IHashCodeProvider
IHashCodeProvider , GetHashCode ().
, ( -)

Object. GetHashCode (), . IHashCodeProvider .

D i c t i o n a r y E n t r y
S y s t e m . C o l l e c t i o n s
D i c t i o n a r y E n t r y . , /,
D i c t i o n a r y E n t r y . :
public object Key { get; set; }
public object Value { get; set; }
. D i c t i o n a r y E n t r y :
public DictionaryEntry(object , object v)
, v .


, ,
, . ,
: , .
. .
.
.
, :

ArrayList

, ..

Hashtabie

- /

Queue

, , :

SortedList

stack

, , :


.
616

II. #

A r r a y L i s t
A r r a y L i s t ,
. #
,
. , ,
. , .
ArrayList. ArrayList ,
. A r r a y L i s t
. . . ArrayList, , ,
.
A r r a y L i s t I C o l l e c t i o n , I L i s t , IEnumerable
ICloneable. ArrayList :
public ArrayList()
public ArrayList(ICollection )
public ArrayList(int capacity)

ArrayList- , 16 . , , .
. (
) . ArrayList- ,
, , .
, ,
ArrayList, .
. 22.4. A r r a y L i s t Sort ().
, BinarySearch ().
ArrayList- , Reverse ().
A r r a y L i s t , . , insertRange (), ArrayList- . RemoveRange ()
.
, SetRange (). , . .
A r r a y L i s t . , Synchronized ().
22.4. A r r a y L i s t

public v i r t u a l void
A d d R a n g e ( I C o l l e c t i o n )

public virtual i n t
BinarySearch (object

,
v. .
, .

22.

v)

617

. 22.4

public virtual int


BinarySearch(object v,
IComparer comp)

,
v, ,
. . ,
.

public virtual int


BinarySearch(int startldx,
int count,
object v,
IComparer comp)

,
v, ,
. , startldx,
count .
.
, .

public virtual void


CopyTo(Array ar,
int startldx)

, , startldx,
, .

public virtual void


CopyTo(int srcldx,
Array ar,
int destldx,
int count)

count ,
, srcidx, ,
, ,
destldx.

public virtual ArrayList


GetRange(int idx,
int count)

A r r a y L i s t .
i d x
count .
,

public static ArrayList


FixedSize(ArrayList ar)

ArrayList-

public virtual void


InsertRange(int startldx,
ICollection c)

, , , ,
startldx

public virtual int


LastlndexOf(object v)

v . ,
-1

public static ArrayList


Readonly(ArrayList ar)

ArrayList-, ,

public virtual void


ReraoveRange(int idx,
int count)

count ,
, idx

public virtual void Reverse()

public virtual void


Reverse(int startldx,
int count)

public virtual void


SetRange(int startldx,
ICollection c)

,
startldx,
,

public virtual void Sort()

public virtual void


Sort(IComparer comp)


, .
,

618

c o u n t
startldx

II. #

. 22.4

public v i r t u a l void
S o r t ( i n t startidx,
int endidx,
icomparer comp)
public static ArrayList
Synchronized(ArrayList

, . startidx

endidx. ,

list)

p u b l i c v i r t u a l object [ ]
ToArray ()
p u b l i c v i r t u a l Array
ToArray (Type type)

,
, . type

p u b l i c v i r t u a l void
TrimToSi ze()

Capacity
Count

, , A r r a y L i s t ,
C a p a c i t y :
p u b l i c v i r t u a l i n t Capacity { g e t ; s e t ; }
Capacity ArrayList. , ArrayList- . , ArrayList- , . ,
ArrayList-, Capacity . , .
, ArrayList-, Capacity .
Count. , Count, i C o l l e c t i o n ,
, .
Capacity , Count,
ArgumentOutOfRangeException.
ArrayList- , , Capacity Count.
, TrimToSi ze ().
ArrayList . ArrayList-,
. . . ""
^ .
// ArrayList-.
using System;
using System.Collections;
class ArrayListDemo {
public static void Main() {
22.

619

// .
ArrayList al = new ArrayListO;
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" :
a1.Count);
Console.WriteLine();
Console.WriteLine(" 6 .");
// .
al.AddCC :
al.Add( f A f ;
al.Add( f E f ;
al.Add( f B f ;
al.AddCD 1 ) ,
al.Add('F'),
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" : " +
al.Count);
// , .
Console.Write(" : " ) ;
for(int i=0; i < al.Count; i++)
Console.Write (al[i] + " " ) ;
Console.WriteLine("\n");
Console.WriteLine(" 2 .");
// .
al.Remove('F');
al.Remove( f A 1 );
f
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" : " +
a1.Count);
// foreach.
Console.Write(": " ) ;
foreach(char in al)
Console.Write(c + " " ) ;
Console.WriteLine("\n");
Console.WriteLine(" 20 .");
// ,
// .
for(int i=0; i < 20; i++)
al.Add((char)('a' + i) ) ;
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(
" 20 : " +
al.Count);
Console.Write(": ") ;
foreach(char in al)

620

II. #

Console.Write( + " " ) ;


Console.WriteLine("\n");
// , .
Console.WriteLine(" .");
al[0] = 'X';
al[l] = f Y';
al[2] = f Z f ;
Console.Write(": " ) ;
foreach(char in al)
Console.Write(c + " " ) ;
Console.WriteLine();

:
: 16
:
6 .
: 16
: 6
: D F
2 .
: 16
: 4
: D
20 .
: 32
20 : 24
: C E B D a b c d e f g h i j
k l m n o p q r s t
.
: X Y Z D a b c d e f g h i j

k l m n o p q r s t

,
, 16. , , , .

ArrayList-
A r r a y L i s t
Sort (). ,
BinarySearch ().
:
// ArrayList-
// .
using System;
using System.Collections;
class SortSearchDemo {
public static void Main() {
// .
ArrayList al = new ArrayList();

22.

621

// .
al.Add(55);
al.Add(43);
al.Add(-4);
al.Add(88);
al.Add(3);
al.Add(19);
Console.Write(" : " ) ;
foreach(int i in al)
Console.Write(i + " " ) ;
Console.WriteLine("\n");
// ,
al.Sort();
// foreach
// .
Console.Write(" : " ) ;
foreach(int i in al)
Console.Write(i + " " ) ;
Console.WriteLine("\n");
Console.WriteLine(" 43 " +
al.BinarySearch(43));

:
: 55 43 -4 88 3 19
: -4 3 19 43 55 88
4 3 3
ArrayList-
, ,
. , ,
. (, , , .
.)


ArrayList- , .
. . , . , , ,
, A r r a y L i s t , ,
:
// ArrayList- .
using System;
using System.Collections;
622

II. #

class ArrayListToArray {
public static void Main{) {
ArrayList al = new ArrayList();
// .
al.Add(l);
al.Add(2);
al.Add(3) ;
al.Add(4);
Console.Write(": " ) ;
foreach(int i in al)
Console.Write(i + " " ) ;
Console.WriteLine();
// .
int[] ia = (int[j) al.ToArray(typeof(int));
int sum = 0;
// ,
for(int i=0; i<ia.Length; i++)
sum += ia [i] ;
Console.WriteLine(" : " + sum) ;

:
I : 1 2 3 4
I : 10
.
ToArray ( ) , i n t .
.
, ToArray (), Array, i n t [ ]. ,
.

Hash t a b l e
Hashtable ,
-. , , -
, (hashing).
, , -,
. - , , . - , .. - . ,
, , , . Hashtable I D i c t i o n a r y , I C o l l e c t i o n ,
IEnumerable, I S e r i a l i z a b l e , I D e s e r i a l i z a t i o n C a l l b a c k ICloneable.
Hashtable ,
( ):
p u b l i c Hashtable()
p u b l i c H a s h t a b l e ( I D i c t i o n a r y )
22.

623

public Hashtable(int capacity)


public Hashtable(int capacity, float

fillRatio)

Hashtable.
Hashtable- .
- capacity, a
( capacity), ( fillRatio).
( ), 0,1-1,0,
-, . ,
, ,
. ,
, 1,0.
Hashtable , , . . 22.5. , Hashtable-
, ContainsKey (). , - , ContainsValue ().
Hashtable-
IDictionaryEnumerator, GetEnumerator (). , , /,
IDictionaryEnumerator.
22.5. H a s h t a b l e

public v i r t u a l bool
ContainsKey ( o b j e c t k)

t r u e ,
Hashtable- , . f a l s e

public v i r t u a l bool
ContainsValue ( o b j e c t v)

t r u e ,
Hashtable- , v. f a l s e

public v i r t u a l
IDictionaryEnumerator
GetEnumerator()
p u b l i c s t a t i c Hashtable
Synchronized (Hashtable ht)

Hashtable- p IDictionaryEnumerator

TO


Hashtable-, ht

Hashtable, , , public-. , Hashtable- :


public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
Hashtable , . Hashtable protected-
Comparer, .
Hashtable /
D i c t i o n a r y E n t r y , , . ,
s h t able- Add(), : .
624

II. #

, Hashtable-
. ,
.
,

Hashtable:
// Hashtable-.
using System;
using System.Collections;
class HashtableDemo {
public static void Main() {
// -.
Hashtable ht = new Hashtable();
// -.
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
// ,
ht[""] = " ";
// *.
ICollection = ht.Keys;
// ,
foreach(string str in )
Console.WriteLine(str + ": " + ht[str]);

:
:
:
:
:
:
, /
. ,
- h t . -,
Keys. - h t ,
, .
, , I D i c t i o n a r y Hashtable, .

SortedList
S o r t e d L i s t ,
/ , .
S o r t e d L i s t I D i c t i o n a r y , I C o l l e c t i o n , IEnumerable
ICloneable.
S o r t e d L i s t , :

22.

625

public
public
public
public

SortedList()
SortedList(IDictionary c)
SortedList(int capacity)
SortedList(IComparer comp)

,
16 . SortedList-, , . SortedList-, , capacity.
,
, .
,
.
, 16 .
SortedList- , , . ,
, . SortedList- , . ,
, , .
S o r t e d L i s t , , .
. 22.6. , SortedList- ,
ContainsKey (). , , ContainsValue ().
SortedList-

IDictionaryEnumerator, GetEnumerator (). , , /,


IDictionaryEnumerator. S o r t e d L i s t Synchronized ().
22.6. , S o r t e d L i s t

public virtual bool


ContainsKey(object )

t r u e ,
SortedList- , . f a l s e

public virtual bool


ContainsValue(object v)

t r u e ,
SortedList- , . f a l s e

public virtual object


GetBylndex(int idx)

, idx

public virtual
IDictionaryEnumerator
GetEnumerator()

I D i c t i o n a r y E n u m e r a t o r
SortedList-

public virtual object


GetKeyUnt idx)

, idx

public virtual iList


GetKeyList()

iList- , SortedList-

public virtual IList


GetValueList()

iList- , SortedList-

626

II. #

. 22.6

public virtual int


IndexOfKey(object k)

, . - 1 ,

public virtual int


IndexOfValue(object v)

, v. -1,

public virtual void


SetBylndex(int idx, object v)

,
idx, , v

public s t a t i c SortedList
Synchronized(SortedList si)

s o r t e d L i s t , si

public virtual void TrimToSize()

capacity Count

. , , GetBylndex ( ) ,
, , SetBylndex ( ) .
, , GetKey ( ) . GetKeyList ( ) ,
GetValueList ( ) .
IndexOf Key ( ) , IndexOf Value ( ) .
S o r t e d L i s t ,
i D i c t i o n a r y , ,
.
S o r t e d L i s t , , .
, SortedList-,
:
public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
SortedList-.
s h t a b l e -, SortedList- /
DictionaryEntry, , S o r t e d L i s t ,
.
S o r t e d L i s t , , Hashtable-.
, , S o r t e d L i s t ^ .
// SortedList-.

using System;
using System.Collections;
class SLDemo {
public static void Main() {
// SortedList.
SortedList si = new SortedList();

22.

627

// .
si.Add("", " ");
si.Add("", " ");
si.Add("", " ");
si.Add("", " ");
// ,
si[""] = " ";
// .
ICollection = si.Keys;
// .
Console.WriteLine(
" , " +
".");
foreach(string str in )
Console.WriteLine(str + ": " + si[str]);
Console.WriteLine();
// , .
Console.WriteLine(
" , " +
" .");
for(int i=0; i<sl.Count; i++)
Console.WriteLine(sl.GetBylndex(i));
Console.WriteLine();
// .
Console.WriteLine(
" .");
foreach(string str in )
Console.WriteLine(str + ": " + si.IndexOfKey(str));

:
, .
:
:
:
:
:
, .





.
:
: 1
: 2
: 3
: 4

628

II. #

S t a c k
, , ,

" " (/ast-m, first-out LIFO). ,
, . ,
, , .. . . , ( ,
).
, , Stack.
I C o l l e c t i o n , IEnumerable ICloneable. , ,
, , ,
.
s t a c k :
public Stack()
public Stack(int capacity)
public Stack(ICollection c)
, 10 . , capacity. , , .
, , stack,
, . 22.7.
,
, Push ().
, Pop (). Pop () , , InvalidOperationException. Peek () , .
22.7. , stack

public virtual bool


Contains(object v)

t r u e , v . f a l s e

public virtual void Clear()

c o u n t ,

public virtual object Peek()

, ,

public virtual object Pop()


public virtual void
Push(object v)
public static Stack
Synchronized(Stack stk)
public virtual object[]
ToArray()

, ,
v
stack-, stk
,

: I n t e g e r , .
22.

629

// Stack.
using System;
using System.Collections;
class StackDemo {
static void showPush(Stack st, int a) {
st.Push(a);
Console.WriteLine(
" : Push(" + + " ) " ) ;
Console.Write(" : " ) ;
foreach(int i in st)
Console.Write(i + " ") ;
Console.WriteLine();
static void showPop(Stack st) {
Console.Write(" : Pop -> " ) ;
int a = (int) st.Pop();
Console.WriteLine(a);
Console.Write(" : " ) ;
foreach(int i in st)
Console.Write(i + " ") ;
Console.WriteLine();
p u b l i c s t a t i c void Main() {
Stack s t = new S t a c k ( ) ;
f o r e a c h ( i n t i in s t )
Console.Write(i + " " ) ;
Console.WriteLine();
showPush ( s t , 22);
showPush(st, 65);
showPush(st, 91);
showPop(st);
showPop(st);
showPop(st);
try {
showPop(st);
} catch (InvalidOperationException) {
Console.WriteLine(" . ") ;

.
, (
InvalidOperationException), ( ).

630

II. #

: Push(22)
: 22
: Push(65)
: 65 22
: Push(91)
: 91 65 22
: Pop ->
: 65 22
: Pop ->
: 22
: Pop ->
:
: Pop ->

91
65
22
.

Queue
.
"
" (first-in, first-out FIFO). ,
, , . ? , , ,
,
.
, ( ) , Internet. .
, , Queue.
i C o l l e c t i o n , IEnumerable ICloneable. , ,
, , ,
,
2,0.
Queue :
public Queue()
public Queue (int capacity)
public Queue (int capacity, float growFact)
public Queue (ICollection c)
, 32 , 2,0.
, capacity,
2,0. ,
growFact. , , .
, , Queue,
, . 22.8.
.
, Enqueue (). , Dequeue ().
Dequeue () , ,
I n v a l i d O p e r a t i o n E x c e p t i o n . () ,
.
22.

631

22.8. , Queue

p u b l i c v i r t u a l bool
C o n t a i n s ( o b j e c t v)
p u b l i c v i r t u a l v o i d c l e a r ()

t r u e , v
. f a l s e
Count ,

,

v

public virtual object


Dequeue ()
p u b l i c v i r t u a l void
Enqueue(object v)
p u b l i c v i r t u a l ob j e c t Peek ()

p u b l i c s t a t i c Queue
Synchronized(Queue q)
p u b l i c v i r t u a l ob j e c t [ ]
()
public v i r t u a l void
TrimToSizeO

, g
,
Capacity
Count

, Queue:
/ / Queue.
using System;
using System.Collections;
class QueueDemo {
static void showEnq(Queue q, int a) {
q.Enqueue(a) ;
Console.WriteLine(
" : Enqueue(" + + " ) " ) ;
Console.Write(" :
foreach(int i in q)
Console.Write(i + " " ) ;

" ) ;

Console.WriteLine();
static void showDeq(Queue q) {
Console.Write(
" : Dequeue -> " ) ;
int a = (int) q.Dequeue();
Console.WriteLine(a);
Console.Write(" :
foreach(int i in q)
Console.Write(i + " ") ;

" ) ;

Console.WriteLine();
public s t a t i c void Main() {
Queue q = new Queue();
foreach(int i in q)

632

II. #

Console.Write(i + " " ) ;


Console.WriteLine() ;
showEnq(q, 22) ;
showEnq(q, 65) ;
showEnq(q, 91);
showDeq(q);
showDeq(q);
showDeq(q);
try {
showDeq(q);
} catch (InvalidOperationException) {
Console.WriteLine(" .")

:
: Enqueue(22)
: 22
: Enqueue(65)
: 22 65
: Enqueue(91)
: 22 65 91
: Dequeue ->
: 65 91
: Dequeue ->
: 91
: Dequeue ->
:
: Dequeue ->

22
65
91
.

B i t A r r a y
BitArray . , ,
. BitArray icollection,
IEnumerable ICloneable.
BitArray . , BitArray , :
public BitArray(bool[] bits)
bits BitArray. bits.
, b i t s .
BitArray- . :
public BitArray(byte[] bits)
, bits,
bits[0] , bits[l] 22.

633

.. BitArray-
int-, :
public BitArray(int[] bits)
bits[0] 32 , bits[l]
32 ..
BitArray-
:
public BitArray(int size)
size , f a l s e .
, :
public BitArray(int size, bool v)
,
v.
, BitArray- .

p u b l i c BitArray(BitArray bits)
,
bits, .
Bit Array- . , .
BitArray , , (. . 22.9). ,
BitArray Synchronized (). ,
,
isSynchronized f a l s e .
BitArray- , SyncRoot.
22.9. , BitArray

p u b l i c B i t A r r a y And
( B i t A r r a y ba)
p u b l i c b o o l Get ( i n t idx)
p u b l i c B i t A r r a y Not ()
p u b l i c BitArray
o r ( B i t A r r a y ba)
p u b l i c v o i d s e t ( i n t idx,
b o o i v)
public void
S e t A l l ( b o o l v)
p u b l i c BitArray
x o r ( B i t A r r a y ba)

634

() , . BitArray-,
, idx
()
BitArray-,
() , . BitArray-,
, idx, v
v
, .
BitArray-,

II. #

BitArray , , Length:
public int Length { get; set; }
Length . , Length ,
Count, . Count
, Length. , Length BitArray. , ""
. BitArray- ,
, f a l s e .
BitArray :
object t h i s [ i n t idx] { g e t ; s e t ; }
.
, BitArray-:
// BitArray.
using System;
using System.Collections;
class BADemo {
public s t a t i c void showbits(string rem,
BitArray b i t s )
Console.WriteLine(rem);
for (int i=0; i < bits.Count; i++)
Console.Write("{0, -6} " , b i t s [ i ] ) ;
Console.WriteLine("\n");

public s t a t i c void Main() {


BitArray ba = new BitArray(8);
byte[] b = { 67 };
BitArray ba2 = new BitArray(b);
showbits(" ba:",
ba) ;
ba = ba.Not();
showbits(
" ba Not():",
ba) ;
showbits(" 2:", 2);
BitArray ba3 = ba.Xor(ba2);
showbits(" ba XOR ba2:", ba3);
}
}
:
1 ba:
I False False False False False False False
22.

False
635

ba Not():
True
True
True
True
True
True
True
True
2:
True
True
False False

False

ba XOR ba2:
False False True
True
True

False

True

False

True

False True


NET Framework ,
( System. C o l l e c t i o n s . S p e c i a l i z e d )

Coiiectionsutii

HybndDictionary

, / L i s t D i c t i o n a r y
Hashtable

ListDictionary

, /

NameVaiueColiection

/, , s t r i n g

stnngCollection

stringDictionary

- /,
, s t r i n g

System. C o l l e c t i o n s , C o l l e c t i o n B a s e , ReadOnlyCollectionBase DictionaryBase,




, for each, , IEnumerator
IEnumerator Current
object Current

636

{ get;

II. #

C u r r e n t , . Current , ,
.
IEnumerator . , MoveNextO, :
bool MoveNext()
MoveNext () . t r u e ,
, f a l s e ,
. MoveNext ()
Current .
Reset ():
void Reset()
Reset () ,
MoveNext ( ) .


,
. GetEnumerator (), , .
, .
, :
1. ( ),
GetEnumerator().
2. , MoveNext ().
, , MoveNext () t r u e .
3.
Current.
A r r a y L i s t ,
j n n y .
// .
using System;
using System.Collections;
class EnumeratorDemo {
public static void Main() {
ArrayList list = new ArrayList(1);
for(int i=0; i < 10; i++)
list.Add(i);
// .
IEnumerator e t r = l i s t . G e t E n u m e r a t o r ( ) ;
while (etr.MoveNext())
Console.Write(etr.Current + " " ) ;

22.

637

Console.WriteLine();
// .
etr.Reset ();
while(etr.MoveNext())
Console.Write(etr.Current + " " ) ;
Console.WriteLine();

|
|0

:
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9

, ,
foreach , .
" " .

IDictionaryEnumerator
, IDictionary, /. IDictionaryEnumerator, IEnumerator. IDictionaryEnumerator IEnumerator ""
. :
D i c t i o n a r y E n t r y Entry { g e t ; }
E n t r y
/ D i c t i o n a r y E n t r y . , D i c t i o n a r y E n t r y , Key Value, , . IDictionaryEnumerator:
object Key { get; }
object Value { get; }
,
.
IDictionaryEnumerator
, Entry, Key Value, Current. , IDictionaryEnumerator-, MoveNextO,
. MoveNext ().
, MoveNext () f a l s e .

I D i c t i o n a r y E n u m e r a t o r Hashtable:
//
// I D i c t i o n a r y E n u m e r a t o r .
using System;
using System.Collections;
class IDicEnumDemo {
public s t a t i c void Main() {
// -.
638

II. #

Hashtable ht = new Hashtable();


// -,
ht.Add("", "555-3456");
ht.Add("", "555-9876");
ht.Add("", "555-3452");
ht.Add("", "555-7756");
// .
IDictionaryEnumerator etr = ht.GetEnumerator();
Console.WriteLine(
" Entry.");
while(etr.MoveNext ())
Console.WriteLine(etr.Entry.Key + ": " +
etr.Entry.Value);
Console.WriteLine();

Console.WriteLine(" " +
" Key Value.");
etr.Reset();
while(etr.MoveNext())
Console.WriteLine(etr.Key + ": " +
etr.Value);

:
Entry.
: 555-3456
: 555-9876
: 555-3452
: 555-7756
Key Value.
: 555-3456
: 555-987 6
: 555-3452
: 555-7756


, i n t , s t r i n g char. , . .
, ,
, . , , ,
,
Inventory, A r r a y L i s t .

ll

u s i n g System;

22.

639

using System.Collections;
class Inventory {
s t r i n g name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
public override s t r i n g ToStringO {
return
String.Format("{0,-16}: {1,8:}
name, cost, onhand);

{2}",

class InventoryList {
public s t a t i c void Main() {
ArrayList inv = new ArrayList();
// .
inv.Add(new Inventory("", 5.95, 3 ) ) ;
inv.Add(new Inventory(" ", 8.29, 2 ) ) ;
inv.Add(new Inventory("", 3.50, 4 ) ) ;
inv.Add(new Inventory("", 19.88, 8 ) ) ;
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" + i) ;

:
:

:
$5.95

:
$8.29

:
$3.50

:
$19.88

:
:
:
:

3
2
4
8

Inventory
.
object,
.
, , .
, , , , 40 , , . , ,
, . , .

640

II. #

, , , , : . , ArrayList- "", inventory. . -,


Inventory iComparable. , . -,
, iComparer.
.

iComparable
( A r r a y L i s t ) ,
(
S o r t e d L i s t ) ,
, .
IComparable. , , . CompareTo () :
int CompareTo(object obj)
CompareTo () , obj. ,
( ) ,
, , obj, , obj.
. ArgumentException,
obj .
IComparable.
Inventory, ,
IComparable,
Inventory.
// IComparable.
using System;
using System.Collections;
class Inventory : IComparable {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}

public override string ToString0 {


return
S t r i n g . F o r m a t ( " { 0 , - 1 6 } : {1,8:}
name, c o s t , o n h a n d ) ;

22.

{2}",

641

// IComparable.
public int CompareTo(object obj) {
Inventory b;
b = (Inventory) ob j ;
return name.CompareTo(b.name);

class IComparableDemo {
public static void Main() {
ArrayList inv = new ArrayListO;
// .
inv.Add(new Inventory("", 5.95, 3));
inv.Add(new Inventory(" ", 8.29, 2));
inv.Add(new Inventory("", 3.50, 4));
inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" +i);
}
Console.WriteLine();
// ,
inv.Sort();
Console.WriteLine(
" :")
foreach(Inventory i in inv) {
Console.WriteLine("
" +i);

(
j o , Sort () ):
:

:
$5.95 : 3

:
$8.29 : 2
*

:
$3.50 : 4

:
$19.88 : 8


:
$8.29

:
$3.50

:
$5.95

:
$19.88

:
: 2
: 4
: 3
: 8

icomparer
IComparable
( ) , .
icomparer.
, icomparer,
642

II. #

, . iComparer Compare ():


i n t Compare(object objl, o b j e c t obj2)
Compare () objl obj2. Compare () ,
, , objl obj2,
, objl obj2. .
CompareToO ArgumentException,
.
IComparer
S o r t e d L i s t , A r r a y L i s t . Sort (IComparer),
.
IComparer , ,
IComparable.
.
IComparer. Complnv,
IComparer Inventory.
S o r t ( ) , ,
, .
// IComparer.
using System;
using System.Collections;
// Complnv.
// Inventory.
class Complnv : IComparer {
// IComparer.
public int Compare(object objl, object obj2) {
Inventory a, b;
a = (Inventory) objl;
b = (Inventory) obj2;
return a.name.CompareTo(b.name);

class Inventory {
public string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
public override s t r i n g ToStringO {
return
String.Format("{0,-16}:
{1,8:}
name, c o s t , onhand);
22.

{2}",

643

class MailList {
public static void Main() {
Complnv comp = new Complnv();
ArrayList inv = new ArrayList() ;
// ,
inv.Add(new Inventory(", 5.95, 3));
inv.Add(new Inventory(" ", 8.29, 2));
inv.Add(new Inventory("", 3.50, 4));
inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine ("
" + i);
}
Console.WriteLine();
// , IComparer.
inv.Sort(comp);
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" + i) ;

ILJ
, .
,
. " ",
,
. . , S o r t e d L i s t . .

644

II. #

Internet

# ,
Internet . ,
#-
Internet. ,
C++, Internet, , ,
. # .NET Library ,
Internet-.
. , System.Net, , Internet.
, System.Net.Sockets, , .
System.Net,
, .
I

ASP.NET-
System. Web.

system.Net
System.Net , .
, , . , , System.Net:
AuthenticationManager

Authorization

Cookie

CookieCollection

CookieContainer

CookieException

CredentialCache

Dns

DnsPermission

DnsPermissionAttribute

EndPoint

EndpointPermission

FileWebRequest

FileWebResponse

GlobalProxySelection

HttpVersion

HttpWebRequest

HttpWebResponse

IPAddress

IPEndPoint

IPHostEntry

NetworkCredential

ProtocolViolationException

ServicePoint

ServicePointManager

SocketAddress

SocketPermission

SocketPermissionAttribute

WebClient

WebException

WebHeaderCollection

WebPermission

WebPermissionAttribute

WebProxy

WebRequest

WebResponse

System.Net :
IAuthenticationModule

ICertificatePolicy

IWebProxy

IWebRequestCreate

ICredentials

:
HttpStatusCode

NetworkAccess

TransportType

WebExceptionStatus

646

. #

, System. Net :
HttpContinueDelegate.
System.Net , Internet- .
WebRequest WebResponse. ,
. ( , .) , , HTTP,
HttpWebRequest HttpWebResponse.
HttpWebRequest HttpWebResponse , , WebClient. , ( ) ,
WebClient.


Internet-
(Uniform Resource Identifier URI). URI-
. URI- (Uniform Resource Locator URL). System.Net Microsoft URI, . ,
URI-,
Internet- .
URI- :
Protocol://ServerlD/FllePath?Query

Protocol (, HTTP).
ServerlD
(, Osborne.com
Weather.corn). FilePath .
FllePath , , ServerlD. , Query ,
. Query . # URI Uri,
.

Internet-
, System.Net,
Internet "-". , -
, . , URI- Web. , URI. - , .
, WebRequest WebResponse,
, Microsoft (pluggable protocols).
23. Internet

647

,
. Internet-
(HyperText Transfer Protocol HTTP). (File Transfer Protocol FTP). , URI- . , URI, HTTP: //MyWebSite.com, HTTP,
.
, WebRequest WebResponse , -, .
, .

R e g i s t e r P r e f IX (), WebRequest.
WebRequest ( ), URI.
, .
.NET- HTTP. ,
URI- HTTP,
HTTP- , . , HTTP, HttpWebRequest HttpWebResponse.
WebRequest WebResponse, ,
, HTTP.
System.Net ,
. Internet-
, . , .
. , , . .
, " ". , ,
Internet .
,
, . Internet , , .
, : WebRequest WebResponse, System.Net.

WebRequest
WebRequest .
, . , . WebRequest,
, . 23.1, . 23.2. . WebRequest public-.
URI-,
( WebRequest), .
Create (),
WebRequest. Create () , WebRequest .

648

II. #

23.1. , WebRequest

public static WebRequest


Create(string uri) ,

WebRequest- URI-,
, u r i . , URI-. , , WebRequest. , N o t S u p p o r t e d E x c e p t i o n .
URI-, U r i F o r m a t E x c e p t i o n

public static WebRequest


Create(Uri uri) ;

WebRequest- URI-,
, u r i . , URI-. , , WebRequest. ,
N o t S u p p o r t e d E x c e p t i o n

public virtual Stream


GetRequestStream()

, URI-

public virtual WebResponse


GetResponse()

.
WebReponse.
URI.

WebException

23.2. , WebRequest

public virtual string


ConnectionGroupName
{ get; set; }

.
. Internet-

public virtual long


ContentLength { get; set; }

public virtual string


ContentType { get; set; }

public virtual ICredentials


Credentials { get; set; }

. ,
( , )

public virtual
WebHeaderCollection
Headers{ get; set; }

public virtual string


Method { get; set; }

public virtual bool


PreAuthenticate { get; set; }

t r u e , . f a l s e , URI-

public virtual IWebProxy


Proxy { get; set; }

proxy-.
, proxy-

public virtual Uri


RequestUri { get; }

URI

public virtual int


Timeout { get;

,
. T i m e o u t . i n f i n i t e

set;

23. Internet

649

WebResponse
WebResponse , . WebResponse . , .
WebResponse GetResponse ( ) ,
WebRequest.
( WebReponse), . , WebResponse, . 23.3,
. 23.4. .
WebResponse public-.
23.3. , WebResponse

p u b l i c v i r t u a l v o i d Close ()
public v i r t u a l stream
GetResponse stream ()

, . ,
GetResponseStream()
, URI. URI-

23.4. , WebResponse

public virtual long


C o n t e n t L e n g t h { g e t ; s e t ;}
public virtual string
ContentType { g e t ; s e t ; }
public virtual
WebHeaderCollection
Headers{ g e t ; }
public virtual Uri
ReponseUri { g e t ; }

. -1,

, URI
URI, . ,
URI-

HttpWebRequest HttpWebResponse
HttpWebRequest
HttpWebResponse
(
WebRequest WebResponse, ) HTTP. ,
HTTP-.
. Internet- .


Internet WebRequest
WebResponse. , , "-"
Internet-. , , .
Internet. , URI-. 650

II. #

Web- Osborne.coin, McGraw-Hill, Web-.


400 , ,
.
// Internet.
using System;
using System.Net;
using System.10;
class NetDemo {
public static void Main() {
int ch;
// URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();

/ / .
Stream istrm = resp.GetResponseStream();
/* html-,
URI. " "
,
400 .
4 00 , <ENTER>
. */
for(int i=*l; ;
ch = istrm.ReadByte();
if(ch -1) break;
Console.Write((char) ch) ;
if ( (i%400)==0) {
Console.Write(" .");
Console.Read();

// , .
// istrm.
resp.Close();

. (
2, , Web-, .)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Find all the right computer books and learning tools at Osborne
McGraw-Hill</TITLE>
23. Internet

651

<META NAME="Title" CONTENT="Find all the right computer books and


learning tools at Osborne McGraw-Hill">
<META NAME="Keywords" CONTENT="osborne, mcgraw-hill, mcgraw hill, it
books, computer books, database books, programming
.
books, networking books, certification books, computing books,
computer application books, hardware books, information technology
books, operating systems, web development, oracle press,
communications, complete reference, how to do everything, yellow
pages, book publisher, certification study guide, reference book,
security, network security, ebusiness, e-business,
a+, network+, i-net+, cisco ce
.

, ,
, .
.
System.Net. ,
, #. System. 10.
Stream,
Web-.
WebRequest-, URI-. ,
Create (), . Create ()
WebRequest. WebRequest , . C r e a t e ()

WebRequest-, , "" URI-. HTTP.


Create () HttpWebRequest-. , Create (), HttpWebRequest- req, ( ) HttpWebRequest. ,
URI-.
, GetResponse ()
WebRequest. GetResponse () .
GetResponse () WebResponse-, . resp.
HTTP,
GetResponse () HttpWebResponse. , Web- URI.
GetResponseStream() r e s p ,
Stream, . istrm. istrm, , URI-, , .
.
, 400 , , 652

II. #

<Enter>.
. ,
ReadByte (). ,
int-,
char.
1.
, , ,
Close () resp. . , , .
,
Internet .
. Web- Osborne.com
HttpWebRequest HttpWebResponse. HTTP-,
, WebRequest
WebResponse. Create () GetResponse () :
// WebRequest- URI-.
WebRequest req = WebRequest.Create(
"http://www.osborne.com");
// .
WebResponse resp = r e q . G e t R e s p o n s e ( ) ;
Microsoft , ,
,
, WebRequest WebResponse.
, .
HTTP ( HTTP-), HttpWebRequest HttpWebResponse.


, , , " ",
"". ,
. Create (), GetResponse () GetResponseStream(). .

, c r e a t e ()
Create (), WebRequest,
. , URI-, , NotSupportedException. URI, UriFormatException.
Create (), ,
ArgumentNullException, , .
23. Internet

653

, GetReponse ()
, ..
GetReponse (), WebException. , , WebException , : Response S t a t u s .
Response
WebResponse.
GetReponse (), . Response
:
p u b l i c WebResponse Response { g e t ; }
- , , ,
S t a t u s . :
public WebExceptionStatus Status {get; }
WebExceptionStatus , :
ConnectFailure

ConnectionClosed

NameResolutionFailure

Pending

KeepAliveFailure
PipelineFailure

ProtocolError

ProxyNameResolutionFailure

ReceiveFailure

RequestCanceled

SecureChannelFailure

SendFailure

ServerProtocolViolation

Success

Timeout

TrustFailure

GetResponse Stream ()

GetResponseStreamO GetResponse P r o t o c o l v i o l a t i o n E x c e p t i o n , , , . GetResponseStreamO, ,


.
lOException.


, ,
:
// .
using System;
using System.Net;
using System.10;
class NetExcDemo {
public static void Main() {
int ch;

try {

654

II. #

// WebRequest- URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
/ / .
Stream istrm = resp.GetResponseStreamO;
* html-,
URI. " "
,
400 .
400 , <ENTER>
. */
for(int i=l; ;
ch = istrm.ReadByte();
if (ch == -1) breaksConsole.Write ( (char) ch) ;
if ( (i%400)==0) {
Console.Write(" .");
Console.Read();

// , .
// istrm.
resp.Close();
} catch(WebException exc) {
Console.WriteLine(" : " + exc.Message +
"\ : " + exc.Status);
} catch(ProtocolViolationException exc) {
Console.WriteLine(" : " +
exc.Message);
} catch(UriFormatException exc) {
Console.WriteLine(" URI: " +
exc.Message);
} catch(NotSupportedException exc) {
Console.WriteLine(" : " +
exc.Message);
} catch(IOException exc) {
Console.WriteLine("I/O Error: " + exc.Message);

, Internet-. ,
Create ()
1 WebRequest.Create("http://www.osborne.com/moonrocket");
, , :
: The remote s e r v e r r e t u r n e d an e r r o r : (404) Not Found.
: P r o t o c o l E r r o r

23. Internet

655

Web- Osborne.com "moonrocket",


, URI- .
, . , .

URI
, , . 23.1 WebRequest. Create ()
. URI ,
. URI
Uri. Uri URI-.
Uri, URI-, Create (). URI- . Internet- Uri, .
Uri .
:
public Uri(string uri)
public Uri(string base, string rel)

Un- URI-,
. Uri- URI-, rel, URI-, base. URI-
URI-, .
Uri , ,
URI- .
.

public

string

public

string
LocalPath { get; }

Host { g e t ; }
,

public string

p u b l i c i n t Port { g e t ; }

HTTP
80

p u b l i c s t r i n g Query

public string
Scheme { g e t ; }

PathAndQuery { get; }

{ get; }

URI- . :
// Uri.
using System;
using System.Net;
656

II. #

class UriDemo {
public static void Main() {
Uri sample = new Uri(
"http://MySite.com/somefile.txt?SomeQuery")
Console.WriteLine(": " + sample.Host);
Console.WriteLine(": " + sample.Port);
Console.WriteLine(": " + sample.Scheme);
Console.WriteLine(" : " +
sample.LocalPath);
Console.WriteLine(": " + sample.Query);
Console.WriteLine(" : " +
sample.PathAndQuery) ;

:
: mysite.com
: 80
: http
: /somefile.txt
: ?SomeQuery
: /somefile.txt?SomeQuery

HTTP-
HttpWebResponse, , , , , URI- . , . 23.5 (
WebResponse). .
23.5. , HttpWebResponse

public string

CharacterSet { get; }
public string
.
ContentEncodmg { g e t ; }
p u b l i c long
. ,
C o n t e n t L e n g t h { g e t ; } -1
public string

ContentType { get; }
public cookieCoiiection
cookie-, Cookies { g e t ; s e t ; }
p u b l i c webHeaderCoiiection
,
Headers{ get; }

p u b l i c DateTime
URI-
LastModified { get; }
p u b l i c s t r i n g Method { g e t ; }
,

23. Internet

657

. 23.5

public version
Protocoiversion { get; }
p u b l i c u r i ReponseUri { g e t ; }

public string server { get; }

v e r s i o n ,
HTTP,
URI-, .
,
URI-
,

p u b l i c HttpStatusCode
StatusCode { g e t ; }
public string
statusDescription { get; }

HttpStatusCode,

,
,


Headers, HttpWebResponse,
HTTP-:
public WebHeaderCollection Headers{ get; }
HTTP- /, . WebHeaderCollection. , /,
(. 22). AllKeys. ,
, .
, .
, Web-
Osborne.com:
// Web-.
u s i n g System;
using System.Net;
c l a s s HeaderDemo {
public s t a t i c void Main() {
// WebRequest- no URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// .
s t r i n g [ ] names = resp.Headers.AllKeys;
// /.
Console.WriteLine("{0,-20}{1}\", "", "");
f o r e a c h ( s t r i n g n in names)
Console.WriteLine("{0,-20}{1}", n, resp.Headers[n]);
/ / , .

658

II. #

resp.Close();

( ,
Web- Osborne.com , , , ):

Date
Server
Keep-Alive
Connection
Transfer-Encoding
Content-Type

Mon, 14 Jan 2002 17:45:50 GMT


Apache/1.3.9 (Unix) PHP/3.0.14
timeout=30, max=500
Keep-Alive
chunked
text/html

cookie-
cookie-, HTTP-,
Cookies, HttpWebResponse. Cookie-,
, /.
Web-.
Cookies:
public CookieCollection Cookies { get; set; }
CookieCollection ICollection IEnumerable,
(. 22).
, cookie-
.
CookieCollection
Cookie. Cookie , cookie-. Name Value:
public string Name { get; set; }
public string Value { get; set; }
, cookie- Name,
Value.
cookie-, ,
cookie-. HttpWebRequest
CookieContainer:
public CookieContainer CookieContainer { get; s e t ; }
CookieContainer , , cookie-.
CookieContainer.
CookieCollection, . CookieContainer cookie-.
cookie-,
URI-, . ,
Web- cookie-, ,
.
/* cookie-.
, cookie-
Web-,
23. internet

659

.
,
Cookie,
Cookie http://MSN.COM
cookie-,
Web- MSN.COM.
*/
using System;
using System.Net;
class CookieDemo {
public static void Main(string[] args) {
if(args.Length != 1) {
Console.WriteLine("Usage: CookieDemo <uri>");
return ;
// WebRequest- URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create(args[0]);
// cookie-.
req.CookieContainer = new CookieContainer();
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// cookie-.
Console.WriteLine(" cookie-: " +
resp.Cookies.Count);
Console.WriteLine("{0,-20}{1}", "", "");
for(int i=0; i < resp.Cookies.Count; i++)
Console.WriteLine("{0, -20}{1}",
resp.Cookies[ij.Name,
resp.Cookies[i].Value);
// , ,
resp.Close ();

L a s t M o d i f l e d
, Web-
URI-. HttpWebResponse , LastModif ied:
p u b l i c DateTime LastModified { g e t ; }
LastModified URI-.
Web- M i c r o s o f t . com:
660

II. #

// LastModified.
using System;
using System.Net;
class HeaderDemo {
public static void Main() {
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.Microsoft.com");
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
Console.WriteLine(
" : " +
resp.LastModified);
resp.Close ();

- J : MiniCrawler
, Internet- WebRequest WebReponse, Web-.
Web- ( MiniCrawler), Web- . Web- . MiniCrawler
. URI-, - Web-.
, "" Web- : , ( )
.
MiniCrawlei . -,
, .. , href=. . -, , .. ,
. -,
. , , Web-
. , .
, MiniCrawler - ?
#- .
, MiniCrawler:
// MiniCrawler: Web-.
using System;
using System.Net;
using System.10;
class MiniCrawler {

23. Internet

661

// ,
static string FindLink(string htmlstr,
ref int startloc) {
int i;
int start, end;
string uri = null;
string lowcasestr = htmlstr.ToLower();
i = lowcasestr.IndexOf("href=\"http", startloc);
if(i != -1) {
start = htmlstr.IndexOf("", i) + 1;
end = htmlstr.IndexOf('"f, start);
uri = htmlstr.Substring(start, end-start);
startloc = end;
return uri;
public static void Main(string[] args) {
string link = null;
string str;
string answer;
int curloc; // .
if(args.Length ! = 1) {
Console.WriteLine("Usage: MiniCrawler <uri>");
return ;
string uristr = args[0]; // URI-.
try {
do {
Console.WriteLine(" " + uristr);
// WebRequest- URI.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create(uristr) ;
uristr = null; //
// URI-.
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse() ;
(

/ / , ,
// %
Stream istrm = resp.GetResponseStream();
//
// StreamReader-.
StreamReader rdr = new StreamReader(istrm);
// .

662

II. #

str = rdr.ReadToEnd();
curloc = 0;
do {
// URI-
/ / .
link = FindLink{str, ref curloc);
if(link != null) {
Console.WriteLine(" : " +
link);
Console.Write(", , ?");
answer = Console.ReadLine();
if(string.Compare(answer, "C", true) == 0) {
uristr = string.Copy(link);
break;
} else if(string.Compare(
answer, "B", true) == 0) {
break;
} else if(string.Compare(
answer, "", true) = = 0 ) {
Console.WriteLine(" .");
}
} else {
Console.WriteLine(" .");
break;
} while(link.Length > 0 ) ;
// , ,
resp.Close();
} while(uristr != null);
} catch(WebException exc) {
Console.WriteLine(" : " + exc.Message +
"\ : " + exc.Status);
} catch(ProtocolViolationException exc) {
Console.WriteLine(" : " + exc.Message);
} catch(UriFcrmatException exc) {
Console.WriteLine(" URI: " +
exc.Message);
} catch(NotSupportedException exc) {
Console.WriteLine(" : " +
exc.Message);
} catch(IOException exc) {
Console.WriteLine("I/O Error: " + exc.Message);

Console.WriteLine(" MiniCrawler.");

MiniCrawler:
23. Internet

663

:>MiniCrawler http://osborne.com
http://osborne.com
: http://www.osborne.com/aboutus/aboutus.shtml
, , ?
.
: http://www.osborne.com/downloads/downloads.shtml
, , ?
http://www.osborne.com/downloads/downloads.shtml

, . URI-,
MiniCrawler "", . Main()
URI- u r i s t r . ,
u r i s t r n u l l , , URI- . ,
. GetResponseStreamO , ( ) streamReader-.
ReadToEnd (), .
.
FindLink (),
MiniCrawler. FindLink (), ,
, . , , h t m l s t r s t a r t l o c , .
, s t a r t l o c r e f-.
FindLink () "" "" ,
h r e f = M h t t p , . , URI- u r i ,
s t a r t l o c . s t a r t l o c ref-, Main(),
, . FindLink ()
u r i . , ,
u r i 11-, , "" .
Main () FindLink ()
,
. (
<>), ( <>)
( <>). <>, . .
, .
, MiniCrawler. , Web-, , . ,
- Web- , ,
. ( ) .. , Web- "",
, ( ) .
664

II. #

, URI- URI- . s t a c k .
:
.

J webciient
" " WebClient.
, ( ) ,
WebRequest WebResponse
WebClient. WebClient ,
, .
WebClient :
p u b l i c WebClient()
(. . 23.6) (.
. 23.7). UriFormatException, URI- , WebException,
.
23.6. , WebClient

public string BaseAddress


{ get; set; }

URI. null-. , , W e b C l i e n t ,

public ICredentials
Credentials { get; set; }

.
n u l l

public WebHeaderCollection
Headers! get; set; }

public NameValueCollection
QueryString { get; set; }

,
/, . URI "?". , @"

public WebHeaderCollection
ResponseHeaders{ get; }

23.7. , WebClient

public byte[]
DownloadData(string uri)

Web-, URI- u r i .

public void
DownloadFile(string uri,
string fname)

Web-, URI- u r i , , fname

public Stream
OpenRead(string uri)

, URI-, u r i .

23. Internet

665

. 23.7

public Stream
OpenWrite(string uri)

, URI-, u r i .

, URI-, uri.
. , how,
, info, no URI, u r i .

public Stream
OpenWrite(string uri,
string how)

public byte[]
UploadData(string uri,
byte[] info)
public byte[]
UploadData(string uri,
string how,
byte[] info)
public byte[]
UploadFile(string uri,
string fname)
public byte[]
UploadFile(string uri,
string how,
string fname)
public byte[]
UploadValues(
string uri,
NameValueCollection vals )
public byte[]
UploadValues(
string uri,
string how,
NameValueCollection vals )

, info, no URI, u r i . . ,
how,
, fname, URI-, u r i .
, fname, URI-, uri. . , how,
, , vals, URI-, uri.
, , vals, URI-, u r i . , how,

WebClient
^ :
// WebClient
// .
using System;
using System.Net;
using System.10;
class WebClientDemo {
public static void Main() {
WebClient user = new WebClient();
string uri = "http://www.osborne.com";
string fname = "data.txt";
try {
Console.WriteLine(
" Web- " +
uri + " " + fname);
user.DownloadFile(uri, fname);
666

II. #

} catch (WebException exc) {


Console.WriteLine(exc) ;
} catch (UriFormatException exc) {
Console.WriteLine(exc);
Console.WriteLine(" .")

Web- Osborne.com
d a t a . t x t . ,
, , . URI -: , u r i .
WebRequest WebResponse , ,
WebClient,
. ,
Web-. ,
WebClient .
\

23. Internet

667

#
III #-.
.
#
, ,
,
#.
Windows-
,
System.Windows.Forms. ,
" ":

.

#
, . - #, (component-oriented language). # .NET
Framework ,

. ,
- (Component Object Model )
, . #- .


. , . . .
. , . , . " ", ,
.
. , , . , , (client). ,
.
. . . , ,
.
, . . ,
.
public-. , , , "
".


, ( ) .
, .
, , ,
. ,
, (component
model). .
, , 24.

671

, . ,
. - ( ) ( ) .
, .
, .
# .NET Framework . Windows
C++. , # .NET Framework.
, - .
, # .NET Framework . , -,
#.

#-
#, . , ,
( ) . , 9 : .
, ,
.NET Framework. , :
System. ComponentModel. IComponent. I Component , .NET Framework.
IComponent, System.ComponentModel.Component.
Component IComponent.
, . ,
Component, IComponent, . , # " " .


#- : .
. ,
. . .

# - -
#- , -. , , , - (
), , . , ,
672

III. #

AddRef ().
Release (). ,
. , #- .
# ,
, .
I Component Component
, .

-J IComponent
IComponent , . IComponent . S i t e :
ISite Site { get;

set; }

s i t e .
. null-, .
, IComponent, Disposed :
event EventHandler Disposed
, , Disposed.
IComponent System. IDisposable, Dispose ():
void Dispose()
, .

Component

IComponent, , Component, IComponent .
.
Component, , , .NET- .
Component . Component , .
Component .
, Container, :
p u b l i c IContainer Container { g e t ; }
Container , . , n u l l .
, Container , .
, S i t e , IComponent. Component
:
public v i r t u a l I S i t e S i t e {get; s e t ; }
24.

573

S i t e i s i t e ,
. n u l l , .
S i t e , .
Component .
T o S t r i n g O . , Dispose ( ) ,
. :
p u b l i c void Dispose!)
Dispose ( ) , , , . Dispose , iDisposable. Dispose ().
Dispose ():
p r o t e c t e d v i r t u a l p u b l i c void Dispose(bool how)
how t r u e ,
, , .
how f a l s e , . Dispose ( p r o t e c t e d ) ,
. . ,
Dispose () Dispose (bool).
, ,
Dispose (bool), , .
, Dispose (bool), Component.
Component MarshalByRefObject,
, , , .
( ) ,
. , ,
MarshalByRef Object . , # .


,
CipherComp, . ,
. . , Encode (), .
, Decode (), .
, ( ).
// -.
// CipherLib.cs.
using System.ComponentModel;
namespace CipherLib { //
'
// .
674
III. #

// , CipherComp
// Component.
public class CipherComp : Component {
// .
public string Encode(string msg) {
string temp = "";
for(int i=0; i < msg.Length; i
temp += (char) (msg[i] + 1 ) ;
return temp;
// ,
public string Decode(string msg) {
string temp = "";
for(int i=0; i < msg.Length;
temp += (char) (msg[i] - 1) ;
return temp;

, . , , C i p h e r L i b . c s . , Visual Studio IDE. System. ComponentModel. ,


.
CipherComp CipherLib.
. ,
.
CipherComp Component. , CipherComp
, .NET- . CipherComp , .
.
, CipherComp
. , . Encode () Decode (). CipherComp
, Dispose (bool). ,
Encode () Decode () , , CipherComp.

C i p h e r L i b
d l l - , -.
Visual Studio IDE,
CipherLib (Class Library project).
,
24.

675

/ t : library. , CipherLib,
:
1 esc / t : l i b r a r y CipherLib.es
CipherLib.dll, CipherComp.

, CipherComp
" ". , CipherComp,
^ .
// , CipherComp.
using System;
using CipherLib; //
// CipherComp..
class CipherCompClient {
public static void Main() {
CipherComp cc = new CipherComp();
string text = " ";
string ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext);
string plaintext = cc.Decode(ciphertext);
Console.WriteLine(plaintext);
cc.Dispose(); // .

, CipherLib. CipherComp " " .


CipherComp,
. CipherComp .
Dispose () .
, Dispose () , . , #,
, . Dispose ()
. , ,
, . CipherComp , Dispose ()
. Dispose () , .
-,
, C i p h e r L i b . d l l .
/. , c l i e n t
:
I esc / : C i p h e r L i b . d l l c l i e n t . e s
676

III. #

Visual Studio IDE - C i p h e r L i b . d l l .


c l i e n t :
I !'
I

-J Dispose ()

CipherComp , .
Dispose (bool).
, Dispose (bool) , " ".
, .
,
, . , . ,
, - . , , , , ,
, , , . , ,
. : Dispose (bool).
Dispose (bool)
.
1. Dispose (bool) t r u e
, .
f a l s e , .
2. Dispose (bool) ,
.
3. Dispose (bool) Dispose (bool), .
4. , , Dispose (false).
2, . private-, .
,
Dispose(bool).
// ,
// Dispose(bool).
class MyCoinp : Component {
bool isDisposed; // true,
public MyComp {

24.

677

isDisposed = false;

-MyCornp () {
Dispose(false);
protected override void Dispose(bool dispAll) {
if(!isDisposed) {
if(dispAll) {
// .
isDisposed = true; //
/ / .
}
// ,
base.Dispose(dispAll);

Dispose () Dispose (bool), ,


.

Dispose (bool)
Dispose (bool), CipherComp ,
. , Encode () Decode (). CipherComp.
Dispose (bool) ,
. , Dispose (bool), WriteLine ().
// ,
// .
using System;
using System.ComponentModel;
using System.10;
namespace CipherLib {
// ,
// .
public class CipherComp : Component {
static int uselD = 0;
int id; // .
bool isDisposed; // true,
FileStream log;
//
public CipherComp() {
isDisposed = false; // .
try {
678

III. #

log = new FileStream("CipherLog" + uselD,


FileMode.Create);
id = uselD;
useID++;
} catch (FileNotFoundException exc) {
Console.WriteLine(exc);
log = null;

//
-CipherComp() {
Console.WriteLine(" "
+ id) ;
Dispose(false);
// .
// .
public string Encode(string msg) {
string temp = "";
for(int i=0;i < msg.Length; i++)
temp += (char) (msg[i] + 1 ) ;
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;

// .
// .
public string Decode(string msg) {
string temp = "";
for(int i=0; i < msg.Length; i++)
temp += (char) (msg[i] - 1 ) ;
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;
protected override void Dispose(bool dispAll) {
Console.WriteLine("Dispose(" + dispAll +
") " + id);
if(IisDisposed) {
if(dispAll) {
Console.WriteLine(" " +
" " + id);
log.Close(); // .

24.

679

isDisposed = true;
}
// ,
base.Dispose(dispAll);

CipherComp.
:
s t a t i c i n t uselD = 0;
i n t i d ; // .
bool isDisposed; // t r u e ,
FileStream log;
int-, ( s t a t i c ) ,
CipherComp.
uselD , CipherComp . i d , use ID
. isDisposed , .
(log) FileStream, .
CipherComp:u
public CipherComp() {
isDisposed = false; // ,
try {
log = new FileStream("CipherLog" + uselD,
FileMode.Create);
id = uselD;
useID++;
} catch (FileNotFoundException exc) {
Console.WriteLine(exc) ;
log = null;

isDisposed f a l s e ,
, CipherComp .
. , "CipherLog"
uselD. uselD id . , CipherComp , (ID). , CipherComp
, , . ( ""
, ). ,
Dispose(bool).
Encode () ,
. log- , Encode () . , Encode () , 680

III. #

. Decode () , ,
.
Dispose (bool),
Cipher . :
protected override void Dispose(bool dispAll) {
Console.WriteLine("Dispose(" + dispAll +
") " + id);
if(!isDisposed) {
if(dispAll) {
Console.WriteLine(" " +
" " + id);
log.CloseO; // .
isDisposed = true;
}
// ,
base.Dispose(dispAll);
, Dispose (bool) protected-.
, . , Dispose ,
Component. Dispose (bool) isDisposed.
, .
isDisposed f a l s e , d i s p A l l . t r u e , ,
isDisposed t r u e . :
d i s p A l l t r u e , . d i s p A l l
f a l s e , ( ). , Dispose (bool), ( Component). , .
WriteLine () ,
.
CipherComp:
CipherComp() {
Console.WriteLine(" "
+ id) ;
Dispose(false);
Dispose (bool) f a l s e .
: ,
.
.
.
WriteLine () , .
, CipherComp,
, .
-, :
II -,
// CipherComp.

24.

681

using System;
using CipherLib; //
// CipherComp.
class CipherCompClient {
public static void Main() {
CipherComp cc = new CipherComp();

string text = "";


string ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext);
string plaintext = cc.Decode(ciphertext);
Console.WriteLine(plaintext);
text = " - #.";
ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext) ;
plaintext = cc.Decode(ciphertext) ;
Console.WriteLine(plaintext) ;

cc.Dispose(); // .

!.!!!?!D$/
- #.
Dispose(True)

CipherLogO
:
I !.!!!?!0$/
I - #.
(,
).
, -
Dispose (bool) t r u e . , Dispose () CipherComp. ,
Dispose () Dispose (bool) true,
. Dispose () -,
. :

!.!!!?!D$/
- #.

Dispose(False)
Dispose(False)

682

III. #

Dispose () , CipherComp
. , ,
. , , , ,
, Dispose (bool) f a l s e .
Dispose (bool) Dispose () Dispose (bool), CipherComp.
Dispose (bool) . , , Dispose () "", ,
, .
Dispose (bool)
.


CipherComp " ", . , . ,
CipherComp, Encode (). ,
: ,
isDisposed. ,
Encode () Decode ():
// .
// .
public string Encode(string msg) {
// ,
if(isDisposed) {
Console.WriteLine(": .");
return null;
string temp = "";
for(int i=0;i < msg.Length;
temp += (char) (msg[i] + 1 ) ;
// .
for(int i=0; i < temp.Length; i++)
log.WriteByt.e ( (byte) temp[i]);
r e t u r n temp;
// .
// .
public string Decode(string msg) {
// ,
if(isDisposed) {
Console.WriteLine(": .");
return null;

24.

683

string temp = "";


for(int i=0; i < msg.Length;
temp += (char) (msg[i] - 1 ) ;
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;
isDisposed, t r u e ,
.
.

- J using
18, u s i n g . Dispose () . , u s i n g
:
using

{obj)

// obj.
}
using (type obj = initializer) {
// obj.
}
obj , using. us ing-, .
obj Dispose ()
( System. IDisposable). u s i n g
, System. I D i s p o s a b l e (, , ).
-, CipherComp
Dispose () using:
//

u s i n g .

using System;
using CipherLib;

/ /
/ / CipherComp.

c l a s s CipherCompClient {
p u b l i c s t a t i c void Main()

/ / ,
using(CipherComp cc = new CipherComp()) {
string text

684

= " u s i n g . " ;

III. #

string ciphertext = cc.Encode(text);


Console.WriteLine(ciphertext);
string plaintext = cc.Decode(ciphertext)
Console.WriteLine(plaintext);

:
?!vtj oh/
u s i n g .
Dispose(True)

-,
Dispose () . , : u s i n g
Dispose (), , using .

, . , . , . , Dispose () , .
.
, Container,
System. ComponentModel. Container :
public Container()
.
C o n t a i n e r Add (), :
p u b l i c v i r t u a l void Add(IComponent comp)
p u b l i c v i r t u a l void Add(IComponent comp,
s t r i n g compName)
,
. , , , compName. ,
. , , ArgumentException.
S i t e .
, Remove ():
p u b l i c v i r t u a l void Remove(IComponent comp)
, :
, , . , Remove () .
24.

685

Container Dispose ().


Dispose () , , Dispose ( ) . , , , - Dispose ().
C o n t a i n e r Components:
p u b l i c v i r t u a l ComponentCollection Components { g e t ; }
,
.
, Component C o n t a i n e r S i t e , .
Container S i t e ( ) . C o n t a i n e r , . s i t e ,
, . S i t e i s i t e . i s i t e :

icomponent Component { g e t ; }
iContainer Container { get; }
b o o l DesignMode { g e t ; }
s t r i n g Name { g e t ; s e t ; }



t r u e ,



CipherComp. ,
" ". S i t e . , Dispose (), . ( , using,
Dispose ().)
//
// .
using System;
using System.ComponentModel;
using CipherLib; //
// CipherComp.
class UseContainer {
public static void Main(string[] args) {
string str = " .";
Container cont = new Container ();
CipherComp cc = new CipherComp();
CipherComp cc2 = new CipherComp();

686

III. #

cont.Add(cc);
cont.Add(cc2f " ");
Console.WriteLine(" : " + str);
str = cc.Encode(str);
Console.WriteLine(
" : " +
str) ;
str = cc.Decode(str);
Console.WriteLine(
" : " +
str) ;
str = ", , ";
Console.WriteLine(" : " + str);
str = 2.Encode(str);
Console.WriteLine(
" : " +
str) ;
str = 2.Decode(str);
Console.WriteLine(
" : " +
Console.WriteLine("\ 2: " +
2.Site.Name);
Console.WriteLine();
// ,
cont.Dispose();

:
: .
: !/
: .
: , ,
: -!-!
: , ,
2:
Dispose(True) -1
1
Dispose(True)

, Dispose ()
.
.

24.

687

-

,
. ,
, .
, , ,
. ,
, .

" ". . - " " (), , .
. :
,
, "" . - .
# :
" ?"
: "!"

688

III. #

Windows-

'
, , , .. , (
).
# , , , . , Windows GUI-
(graphics wser /nterface ),
, , # Windows.
Windows-
,
Windows. , # .NET Framework
. .NET- ,
Forms, Windows-. # System.Windows. Forms Windows- .
Windows- ,
. , .
" " Windows. , , , . ,
Windows-, .


Windows-
# .NET Framework
Windows-, .
Windows Windows
API- (Application Programming Interface ), ,
Windows. API- . API- ,
, , . , Windows .
, API-. , MFC (Microsoft Foundation Classes Microsoft).
C++; MFC-
C++. - MFC Windows- . MFC-
, .. , . , MFC
" ", API-, Windows- -
.

690

III. #

# .NET Framework- Forms Windows-.


API Forms , Windows-.
#, . , # , " ".
API-
MFC, , #- . ( Windows) Windows , .

Windows-,

. Visual Studio ,
Windows-. , . Visual Studio ,
. Visual Studio
Windows-,
, Windows- , .
#, Visual Studio, Windows, , ,
, .
, ,
. , .

Windows
Windows-, ,
Windows,
Windows-. , , .
. , Read ()
WriteLine(). , , " ", , .
"" Windows : Windows . : , Windows. , . , ,
Windows, , -
25. Windows-

691

Windows. , Windows- , Windows.


, Windows
. ,
, .
,
. :
. Windows- , . , .

Windows-
Windows-, #, . , ,
. , , .
. , , . ,
Windows-.
, . ,
Windows-, .
.

Form
Form , Form. Form , , , .
System. ComponentModel. Component (.
24) System.Windows. Forms.Control. Control , Windows- . , Form
Control, .
Form Control .

Windows-,

Windows-, . ,
. ,
.
, Windows-. ,
Windows-:
// Windows-,
/ / .

692

III. #

using System;
using System.Windows.Forms;
// WinSkel - Form,
class WinSkel : Form {
public WinSkel() {
// .
Text = " Windows-";
// Main() .
[STAThread]
public static void Main() {
WinSkel skel = new WinSkel(); // .
// .
Application.Run(skel) ;

, , . 25.1.

kJ^M^f^CTlfg^^.^ * iiBJglx|:

. 25.1. ,
WinSkel
. ,
: System System. Windows . Forms. System STAThread, Main(), a System. Windows. Forms
Windows Forms.
WinSkel, Form. ,
WinSkel .
() .
WinSkel :
I Text = " Windows-";
Text, . , Windows-. Text :
p u b l i c v i r t u a l s t r i n g Text { g e t ; s e t ; }
Text Control.
Main (),
Main (), . , ,
25. Windows-

693

. , Main{)
STAThread. Microsoft ,
Main () Windows-. STAThread (threading model), , .. ,
(single-threaded apartment STA). , ,
Windows- :
.
Main () WinSkel s k e l . Run (), A p p l i c a t i o n :
I Application.Run(skel);
. A p p l i c a t i o n
System.Windows. Forms ,
Windows-. Run():
public static void Run(Form ob)
. WinSkel
Form, WinSkel Run ().
, . 25.1.
(300 300 ).
. , , ,
. , ,
, .
: ,
Windows API, !
Windows, . , ,
, Form.
,
A p p l i c a t i o n . Run () .
/

Windows-
Windows- , , Visual Studio. ,
, ,
( ), IDE.
( , , , Visual Studio.) Windows-.


Windows- WinSkel. cs , :
1 esc /trwinexe WinSkel.cs
/ t : w i n e x e Windows-,
. , WinSkel.
694

III. #

(IDE)
Visual Studio IDE,
Windows Application. File^New1^Project
(^^). New Project (
) Windows Application (Windows-).
WinSkel. Forml.cs. . ,
WinSkel,
Add"=>Add New Item (1^ ).
, . 25.2.
Add New I t e m - WinSkei
Categories

liifil

Templates

_i local Project Items


Windows
Form

Component
Class

User Control Data Form


Wizard

XML
Schema

Data Set

! ]

* blank cocte file


Name
Cpen

. 25 2. Add New Item (


)

Templates () Code File (


) WinSkel.cs.
Windows- Builds
Build Solution (^ ).
Debugs Start Without Debugging (^ ).


:
. . . ,
.
Windows , , , .
, . ,
.

25. Windows-

695


Button, ButtonBase. ButtonBase , Control. Button :
public Button()
,
. , , , , Text .

Location . Location
Control :
p u b l i c Point Location { g e t ; s e t ; }
Point,
System. Drawing. :
public int X { get; set; }
public int Y { get; set; }
, " "
100, 200, :
I B u t t o n M y B u t t o n = new B u t t o n ( ) ;
1 M y B u t t o n . T e x t = " " ;
I M y B u t t o n . L o c a t i o n = new P o i n t ( 1 0 0 f 2 0 0 ) ;


. Add (), , . C o n t r o l s ,
Control. Add ():
public virtual void Add(Control cntl)
cntl .
,
.


.
, .
// .
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton = new Button();
public ButtonForm() {

696

III. #

Text = " ";


MyButton = new Button();
MyButton.Text = "";
MyButton.Location = new Point(100, 200)
Controls.Add(MyButton);
[STAThread]
public static void Main() {
ButtonForm skel = new ButtonForm();
Application.Run(skel);

ButtonForm,
Form. Button MyButton.
ButtonForm , .
, . 25.3.
, .
- , ,
.

. 25.3.

1
( -
), , . ,
, . ,
,
. , ,
, . , ,
Click.
Click Button. ( Click
Control.) :
p u b l i c Event EventHandler C l i c k ;
25. Windows-

697

EventHandler :
public delegate void EventHandler(object who,
EventArgs args)
, , who, , , args.
args , EventArgs. ,
.
,
. .
// .
'
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton = new Button();
public ButtonForm() {
Text = " ";
MyButton = new Button();
MyButton.Text = "";
MyButton.Location = new Point(100, 200);
// .
MyButton.Click += new EventHandler(MyButtonClick);
Controls.Add(MyButton);
}
[STAThread]
public static void Main() {
ButtonForm skel - new ButtonForm();

Application.Run(skel);
}
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if (MyButton.Top === 200)
MyButton.Location = new Point (10, 10);
else
MyButton.Location = new Point (100, 200);

'

:
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if(MyButton.Top == 200)
MyButton.Location = new Point(10, 10);
else
MyButton.Location = new Point(100, 200);

}
698

HI. #

MyButtonClick () ,
EventHandler, ,
Click. ,
p r o t e c t e d . , ,
, .
.
( ):
public int Top { get; set; }
public int Bottom { get; }
public int Left { get; set; }
public int Right { get; }
, Left, Bottom Right, . (
Width Height.)
, , , , 200, : 10, 10.
100, 200. .
MyButtonClick () , , Click.
But ton Form :
I MyButton.Click + new EventHandler(MyButtonClick);
MyButtonClick ().


, MyButtonClick ()
-. , who
, . , , , . MyButtonClick () :
// ,
// .
p r o t e c t e d void MyButtonClick(object who, EventArgs e) {
Button b - (Button) who;
if(b.Top == 200)
b.Location = new Point(10, 10);
else
b.Location = new Point(100, 200);
}
who Button,
( MyButton) .

, , . , , .
25. Windows-

699


Windows- . , . ( ), , . ,
, MessageBox.
. Show ().
Show () . :
public s t a t i c DialogResult Show(
string msg,
string caption,
MebsageBoxButtons mbb)
, , msg;
caption. , , mbb. .
MessageBoxButtons , :
AbortRetrylgnore

OK

OKCancel

RetryCancel

YesNo

YesNoCancel

, . , mbb YesNo, .
, Show (), , . :
Abort
Cancel
Ignore
No
None

OK

Retry

Yes

, Show ( ) ,
, . ,
,
, ,
, .
, . , , , , . , . ,
^ .
// .
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton;
Button StopButton;
public ButtonForm() {
Text = " ";
700

III. #

// .
MyButton = new Button();
MyButton.Text = "";
MyButton.Location = new Point(100, 200);
StopButton = new Button();
StopButton.Text = "";
StopButton.Location = new Point(100, 100);
// .
MyButton.Click += new EventHandler(MyButtonClick);
Controls.Add(MyButton);
StopButton.Click += new EventHandler(StopButtonClick)
Controls.Add(StopButton);
[STAThread]
public static void Main() {
ButtonForm skel = new ButtonFormO ;
Application.Run(skel);
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if(MyButton.Top == 200)
MyButton.Location = new Point(10, 10);
else
MyButton.Location = new Point(100, 200);
}
// StopButton.
protected void StopButtonClick(object who, EventArgs e) {
// Yes,
// .
DialogResult result = MessageBox.Show(
" ?",
"",
MessageBoxButtons.YesNo);
if(result == DialogResult.Yes) Application.Exit();

, . , ButtonForm . "",
StopButtonClick ().
StopButtonClick () :
// Yes,
// .
DialogResult result = MessageBox.Show(
" ?",
"",
MessageBoxButtons.YesNo) ;

25. Windows-

701

"". " ?" . Show (), ,


r e s u l t . , :
I if(result

== D i a l o g R e s u l t . Y e s )

Application.Exit ();

, .
A p p l i c a t i o n . Exit , . ,
.
. 25.4.

. 25.4. ,


Windows- , . . , , . , ,
. .
, , .
.
MainMenu , Menultem .
(, ), . MainMenu Menultem Menu.
Windows-,
, . , .
Click,
Menultem. , ,
Click, , .
Menu, :
p u b l i c MainMenu Menu { g e t ; s e t ; }

702

III. #

. , "" .
.
1. MainMenu.
2. MainMenu Menultem, . Menultems, .
3. Menu I t em- Menu I t em, ,
.
Menultems, .
4. .
5. MainMenu Menu, .
, ,
: , .
// .
MainMenu MyMenu = new MainMenu();
// .
Menultem ml = new Menultem("");
MyMenu.Menultems.Add(ml);
// "".
Menultem subml = new Menultem("");
ml.Menultems.Add(subml);
Menultem subm2 = new Menultem("");
ml.Menultems.Add(subm2);
Menultem subm3 = new Menultem("");
ml.Menultems.Add(subm3);
.
MainMenu MyMenu.
.
ml "". MyMenu.
, .
, ml, . Menultem , , , Menu I t em-. , submlsubm3 ml,
File ,
, .
, . , Click. submlsubm3
.
// .
subml.Click += new EventHandler(MMOpenClick);
subm2.Click += new EventHandler(MMCloseClick) ;
subm3.Click += new EventHandler(MMExitClick) ;
25. Windows-

703

, , MMExitClick ().
, Menu MainMenu:
1 Menu = MyMenu;
,
.
, .
// .
using System;
using System.Windows.Forms;
class MenuForm : Form {
MainMenu MyMenu;
public MenuForm() {
Text = " ";
// .
MainMenu MyMenu = new MainMenu();
// .
Menultem ml = new Menultem("");
MyMenu.MenuIterns.Add(ml);
Menultem m2 = new Menultem("");
MyMenu.Menulterns.Add(m2);
// .
Menultem subml = new Menultem("");
ml.MenuIterns.Add(subml) ;
Menultem subm2 = new Menultem("");
ml.Menulterns.Add(subm2) ;
Menultem subm3 = new Menultem("");
ml.MenuIterns.Add(subm3);
// "".
Menultem subm4 = new Menultem("");
m2.Menulterns.Add(subm4);
Menultem subm5 = new Menultem(" ");
m2.MenuIterns.Add(subm5);
Menultem subm6 ='new Menultem("");
m2.Menultems.Add(subm6);
// ,
subml.Click += new EventHandler(MMOpenClick);
subm2.Click += new EventHandler(MMCloseClick);
subm3.Click += new EventHandler(MMExitClick);
subm4.Click += new EventHandler(MMCoordClick);
subm5.Click += new EventHandler(MMChangeClick);
subm6.Click += new EventHandler(MMRestoreClick);

704

III. #

// .
Menu = MyMenu;
[STAThread]
public static void Main() {
MenuForm skel = new MenuFormO ;
Application.Run(skel);
// ,
protected void MMCoordClick(object who, EventArgs e) {
// , ,
string size =
String. Formate1 {0}: , {2}\n{3}: {4}, {5} ",
", ", Top, Left,
", ", Bottom, Right);
// .
MessageBox.Show(size, " ",
MessageBoxButtons.OK);
// ,
protected void MMChangeClick(object who, EventArgs e) {
Width = Height = 200;
}
// .
protected void MMRestoreClick(object who, EventArgs e) {
Width = Height = 300;
}
// .
protected void MMOpenClick(object who, EventArgs e) {
MessageBox.Show(" ", "",
MessageBoxButtons.OK);
}
// .
protected void MMCloseClick(object who, EventArgs e) {
MessageBox.Show(" ", "",
MessageBoxButtons.OK);
}
// .
protected void MMExitClick(object who, EventArgs e) {
DialogResult result = MessageBox.Show(" ?",
"",
MessageBoxButtons.YesNo);
if(result == DialogResult.Yes) Application.Exit();

. 25.5.
25. Windows-

705

. 25.5. ,

. (
, ) . ,
, .
.
, .
: ,
. .
, . .

, 200 .
Width Height:
public int Width { get; set; }
public int Height { get; set; }

300x300. Restore
.


, Windows- .
Windows , . Windows-,
.
, System
.Windows. Forms. Windows-,
, () .
, Windows. Drawing,
,
. Windows . Drawing , Windows GDI (Graphics Device Interface).
, .
706

III. #

, , , (10 5) * 3,
? , , , . , . (expression parsing),
,
, ,
.
,
, .
,
. ,
(recursive-descent
parser), , . , .
, ,
#.
" ". ,
GUI- - .
C++. ,
#, , #
.

-J
,
, .
, . , ,
:
;
+, -, /, *, , % =;
;
.
( ) (
" ", #), "" (=) .
.
:
10-8
(100 - 5) * 14
+ b -

10

= 10

, :
708

III. #

+ - ()


.
, , . , ( ,
26 , z). (
). -, ,
double, . , , .

LJ :
,
, . ,
:
10 - 2 * 3

, 4. , , ,
. :
=
while( ) {
=
b =
= a op b
, , ; .. , 10 2 * 3 24 (..
8 * 3), 4, .
,
, .
, , , . , , , , ..
, .
,
, . ( , ,
, .
.)

26.

709


. , , (recursive data structures),
.. , . ,
+ , - , * , / ,
:
-> [+ ] [- ]
-> [* ] [/ ]
-> , ()
, -> " ". . , : , , , . ,
.

10 + 5 *

: 10 5 * . : .
, .

14 * (7 - )

: 14 (7 - ) .
, .
: .
, , .
.
, ,
:
9/3 - (100 + 56)
.
1. , 9/3.
2. . 3.
3. , (100 + 56). .
4. . 156.
5. 156 3. -153.
, , .
, . "" .
-,
710

III. #

. -,
, .
.
( double),
.
. ,
.


,
. ,
* -

(W + 1 0 )

: , *, , -, (, W, +, 10 ). , .
,
, .
, ,

. " " . , , GetToken().
, , Parser.
,
, GetToken (). , P a r s e r :
c l a s s Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// .
enum E r r o r s { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
s t r i n g exp;
// ,
i n t expldx;
// ,
s t r i n g token; // .
Types tokType; // .
Types. . : , .
VARIABLE, NUMBER DELIMITER, Types. DELIMITER , . NONE
. E r r o r s ,
.
, , . , , "10+4". expldx . token,
tokType.
26.

711

GetTokenO.
, , ,
expldx, .. [expldx].
token, tokType. GetTokenO
i s D e l i m ( ) , , .
//

.
void GetTokenO

tokType = Types.NONE;
token = " " ;
if(expldx

== exp.Length)

r e t u r n ; / /

/ / ,
while(expldx < exp.Length &
&
Char.IsWhiteSpace(exp[expldx]))

++expldx;

/ / ,
if(expldx == exp.Length) r e t u r n ;
if(IsDelim(exp[expldx])) { / / ?
token += exp[expldx];
expldx++;
tokType = Types.DELIMITER;
else if(Char.IsLetter(exp[expldx]))

{ / /
/ / ?

while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
tokType = Types.VARIABLE;
e l s e if(Char.IsDigit(exp[expldx])) { / / ?
while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
tokType = Types.NUMBER;

// true,
// ,
bool IsDelim(char )
{
if((" +-/*%A=()".IndexOf() != -1))
return true;
return false;
}

GetTokenO. , , expldx .Length.


712

III. #

expldx , ,
, , ( ).
, GetToken ()
. exp[expldx]
, , , ( ). , , token,
tokType DELIMITER. , , .
, token, tokType VARIABLE. , , , token,
tokType NUMBER. , , token
.
GetToken (), . , , .
,
.
.
, GetToken (), :
+ 100 -

( * ) / 2

GetToken () ( ):

VARIABLE

DELIMITER

100

NUMBER
DELIMITER

DELIMITER

VARIABLE

DELIMITER

VARIABLE

DELIMITER

DELIMITER

NUMBER

, ,


. , , . GetToken () , 26.

713

. , , "" .
/*

,
.
*/
using System;
// ,
class ParserException : ApplicationException {
public ParserException(string str) : base(str) { }
public override string ToStringO {
return Message;

class Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// .
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string exp;
int expldx;
string token;
Types tokType;

//
//
//
//

,
,
.
.

// .
public double Evaluate(string expstr)
{
double result;
exp = expstr;
expldx = 0 ;

'

try {
GetToken();
if(token =- "") {
SyntaxErr(Errors.NOEXP); //
// ,
return 0.0;
}
EvalExp2(out result);
if(token != "") //
// null-.
SyntaxErr(Errors.SYNTAX);
return result;
} catch (ParserException exc) {
//
// .
Console.WriteLine(exc);

714

III. #

return 0.0;

// .
void EvalExp2(out double result)
{
string op;
double partialResult;
EvalExp3(out result);
while((op = token) == "+" || op == "-") {
GetTokenO ;
EvalExp3(out partialResult);
switch(op) {
case "-":
result = result - partialResult;
break;
case " + ":
result = result + partialResult;
break;

// .
void EvalExp3(out double r e s u l t )
{

string op;
double partialResult = 0.0;
EvalExp4(out result);
while((op = token) == "*" ||
op == "/" II op == "%") {
GetTokenO ;
EvalExp4(out partialResult);
switch(op) {
case "*":
result = result * partialResult;
break;
case "/":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = result / partialResult;
break;
case "%":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = (int) result % (int) partialResult;
break;

// .
void EvalExp4(out double result)
{
double partialResult, ex;

26.

715

int

t;

EvalExp5(out r e s u l t ) ;
ll/4lf
i f (token ==
) {
GetTokenO ;
EvalExp4(out partialResult);
ex = result;
if(partialResult ==0.0) {
result = 1.0;
(
return;
}
for(t=(int)partialResult-l; t > 0; t )
result = result * (double)ex;

// + -.
void EvalExp5(out double result)
string

op;

op = "";
if((tokType == Types.DELIMITER) &&
token == "+" || token == "-") {
op = token;
GetToken();
EvalExp6(out result);
if(op == "-") result = -result;
// .
void EvalExp6(out double result)
{
if((token =="(")) {
GetToken();
EvalExp2(out result);
if(token != ")")
SyntaxErr(Errors.UNBALPARENS);
GetToken ();
}
else Atom(out result);
// ,
void Atom(out double result)
{
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token)
} catch (FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetTokenO ;
return;
default:

716

III. #

result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;

// .
void SyntaxErr(Errors error)
{
string[] err = {
" ",
" ",
" ",
" "
throw new ParserException(err[(int)error]);
// ,
void GetTokenO
tokType = Types.NONE;
token = "";
if(expldx == exp.Length) return; //
// ,
while(expldx < exp.Length &&
Char.IsWhiteSpace(exp[expldx])) ++expldx;
// ,
if(expldx == exp.Length) return;
if(IsDelim(exp[expldx])) { // ?
token += exp[expldx];
expldx++;
tokType = Types.DELIMITER;
else if(Char.IsLetter(exp[expldx])) { //
// ?
while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
tokType = Types.VARIABLE;
else if(Char.IsDigit(exp[expldx])) { // ?
while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
tokType = Types.NUMBER;
}

26.

717

// true,
// ,
bool IsDelim(char )
{
if((" +-/*%=()".IndexOf() != -1))
return true;
return false;

: +, - , *,
/ %. , ( ) , " " .
, Parser. E v a l u a t e ( ) ,
, . , E v a l u a t e ( ) . :
// .
using System;
class ParserDemo {
public s t a t i c void Main()
{

string expr;
Parser p = new Parser();
Console.WriteLine(
" .");
for(;;) {
Console.Write(" : " ) ;
expr = Console.ReadLine();
if(expr == "") break;
Console.WriteLine(": " + p.Evaluate(expr));

:
.
: 10-2*3
: 4
: (10-2)*3
: 24
: 10/3
: 3.33333333333333
: 10/3.5
: 2.85714285714 286
:

718

III. #


Parser.
GetTokenO , P a r s e r .
.
Evaluate (). , , #-. , ,
:
"10 - 5"
"2 * 3.3 / (3.1416 * 3 . 3 ) "
expldx.
expldx . expldx "" . token , tokType .
Evaluate ,
, , .
EvalExp2 ()-EvalExp6 () Atom() .
. ,
, .
EvalExpl ().
SyntaxErr () . GetTokenO i s D e l i m O , ,
. GetToken ()
.
, .
, , :
10 - 3 * 2
Evaluate () . (""), "
", Evaluate () 0.0.
10. EvalExp2 (). EvalExp2 ()
EvalExp3(), EvalExp4(), -
EvalExp5(). EvalExp5() , . ,
EvalExp6 (). EvalExp6 () EvalExp2 () ( , ), Atom () . , Atom() r e s u l t
10. , . , , (
), "" , .. , .
"-", EvalExp2 ().
.
"-", . ,
3, "" . AtomO 3 r e s u l t "*".
26.

719

EvalExp3 (), , 2.
, 2 3. EvalExp2(), .
4. ,
"" ; ,
, ,
.
SyntaxErr ( ) , P a r s e r E x c e p t i o n , . P a r s e r E x c e p t i o n ; , Parser. ,
,
.
, . .

I
,
,
. , .
. , Z. P a r s e r .
26- doubles. ,
P a r s e r :
1 d o u b l e [ ] v a r s = new d o u b l e [ 2 6 ] ;
P a r s e r ,
:
public Parser() {
// .
f o r ( i n t i = 0 ; i < v a r s . L e n g t h ; i++)
v a r s [ i ] = 0.0;
}

" " 0.0.


.
Z,
v a r s ASCII- . FindVar (). :
// ,
double FindVar(string vname)
{
if(IChar.IsLetter(vname[0])){
SyntaxErr(Errors.SYNTAX);
return 0.0;
}
return vars[Char.ToUpper(vname[0])-'A'];

720

III. #

, (.. ) , 12 t e s t , .
.
Atom(),
, . :
// ,
void Atom(out double result)
{

switch(tokType) {
case Types.NUMBER:
try {
r e s u l t = Double.Parse(token);
} catch (FormatException) {
r e s u l t = 0.0;
SyntaxErr(Errors.SYNTAX);
}

GetToken();
return;
case Types.VARIABLE:
r e s u l t = FindVar(token);
GetToken();
return;
default:
r e s u l t = 0.0;
SyntaxErr(Errors.SYNTAX);
break;
, , , . , "" (=). Parser EvalExpl ().
. , ,
, Evaluate ()
EvalExpl (), EvalExp2().
JSvalExpl ():
// ,
void EvalExpl(out double result)
{

int varldx;
Types ttokType;
string temptoken;
if(tokType == Types.VARIABLE) {
// ,
temptoken = String.Copy(token);
ttokType = tokType;
// ,
varldx = Char.ToUpper(token[0]) -

Af;

GetToken();
if(token != "=") {
26.

721

PutBack(); //
/ / ,
// .
token = String.Copy(temptoken);
tokType = ttokType;
}
else {
GetToken(); // .
EvalExp2(out result);
vars[varldx] = result;
return;

EvalExp2(out result);
EvalExpl () , . ,
,
"" ,
. , = 100
, , "", /10 . EvalExpl () . ,
PutBack (), joporo :
// ,
void PutBack()
'
f o r ( i n t i = 0 ; i < t o k e n . L e n g t h ; i++) e x p l d x ;
:
/*

, .
*/
using System;
// ,
class ParserException : ApplicationException {
public ParserException(string str) : base(str) { }
public override string ToStringO {
return Message;

class Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// .
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string ;
int expldx;
string token;

722

// ,
// ,
// .

III. #

Types tokType; // .
// ,
double[] vars = new double[26];
public Parser() {
// .
for(int i=0; i < vars.Length; i
vars[i] = 0.0;
// .
public double Evaluate(string expstr)
{
double result;
exp = expstr;
expldx = 0;
try {
GetToken();
if(token ~ "") {
SyntaxErr(Errors.NOEXP); // ,
return 0.0;
EvalExpl(out result); //
//
// EvalExpl().
if(token != "") //
// .
SyntaxErr(Errors.SYNTAX);
return result;
} catch (ParserException exc) {
// .
Console.WriteLine(exc);
return 0.0;

// ,
void EvalExpl(out double result)
{
int varldx;
Types ttokType;
string temptoken;
if(tokType ~ Types.VARIABLE) {
// ,
temptoken = string.Copy(token);
ttokType = tokType;
// ,
varldx = Char.ToUpper(token[0]) - 'A';

GetToken();
26.

723

if(token != "=") {
PutBack(); //
/ / ,
// .
token = String.Copy(temptoken);
tokType = ttokType;
else {
GetToken(); //
// .
EvalExp2(out result);
vars[varldx] = result;
return;
}
EvalExp2(out result);
// .
void EvalExp2(out double result)
{
string op;
double partialResult;
EvalExp3(out result);
while((op = token) == "+" || op == "-") {
GetToken();
EvalExp3(out partialResult);
switch(op) {
case "-":
result = result - partialResult;
break;
case "+":
result = result + partialResult;
break;

// .
void EvalExp3(out double result)
{
string op;
double partialResult = 0.0;
EvalExp4(out result);
while((op = token) == "*" ||
op == "/" II op == "%") {
GetToken();
EvalExp4(out partialResult);
switch(op) {
case "*":
result = result * partialResult;
break;
case "/":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);

724

III. #

result = result / partialResult;


break;
ase "%":
if(partialResult = = 0 . 0 )
SyntaxErr(Errors.DIVBYZERO);
result = (int) result % (int) partialResult;
break;

// ,
void EvalExp4(out double result)
{
double partialResult, ex;
int t;
EvalExp5(out result);
IIA
if (token == ") {
GetToken();
EvalExp4(out partialResult);
ex = result;
'
if(partialResult ==0.0) {
result = 1.0;
return;
}
for(t=(int)partialResult-l; t > 0; t )
result = result * (double)ex;

// + -.
void EvalExp5(out double result)
{
string op;
op = "";
if((tokType == Types.DELIMITER) &&
token == "+" || token == "-") {
op = token;
GetToken();
}
EvalExp6(out result);
if(op == "-") result = -result;
// .
void EvalExp6(out double r e s u l t )
{

if((token =="(")) {
GetToken();
EvalExp2(out result);
if(token != ")")
SyntaxErr(Errors.UNBALPARENS); *
GetToken();
}
else Atom(out result) ;

26.

725

// .
void Atom(out double result)
{
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token);
} catch (FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetTokenO ;
return;
case Types.VARIABLE:
result = FindVar(token);
GetTokenO ;
return;
default:
result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;

// ,
double FindVar(string vname)
{
if(!Char.IsLetter(vname[0])){
SyntaxErr(Errors.SYNTAX);
return 0.0;
}
return vars[Char.ToUpper(vname[0] ) - f A ' ] ;
// .
void PutBackO
{
for(int i=0; i < token.Length; i++) expldx;
// .
void SyntaxErr(Errors error)
{
string[] err = {
" ",
" ",
" ",
" "
throw new ParserException(err[(int)error]);
// .
void GetTokenO
{
tokType = Types.NONE;
token = "";

726

III. #

if(expldx == exp.Length) return; // .


// .
while(expldx < exp.Length &&
Char.IsWhiteSpace(exp[expldx])) ++expldx;
// ,
if(expldx == exp.Length) return;
if(isDelim(exp[expldx])) { // ?
token += exp[expldx];
expldx++;
tokType = Types.DELIMITER;
}
else if(Char.IsLetter(exp[expldx])) { //
// ?
while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
}
tokType = Types.VARIABLE;
}
else if(Char.IsDigit(exp[expldx])) { // ?
while(!IsDelim(exp[expldx])) {
token += exp[expldx];
expldx++;
if(expldx >= exp.Length) break;
}
tokType = Types.NUMBER;

// true,
// -- .
bool IsDelim(char )
{
if ( +-/*%=() ".IndexOf () ! -1))
return truerreturn false;
, , .
, :

= 10/4
-
= * (F - 21)

26.

727



, .
(, ). , , :
10 ** 8
((10 - 5)
/8

* 9

, ,
. . "" , .
, ,
SyntaxErr (), .
, -
, Atom(), FindVarO EvalExp6(),
.
SyntaxErr () ParserException,
.
Evaluate (). , . .


, . , , , ,
. .

. , , ""
, ,
. , , :
STRING;

Get To ken ( ) , ;
case- Atoin()

STRING.

, :
= ""
b = ""
= + b
, ..
"".
728

III. #

: -,
. .
, P a r s e r . . P a r s e r Component.
Dispose (bool). ! .

26.

729


XML

# .
// /* */. XML- XML. (XML- .)
L- ///. XML-
, , , . XML-,
. XML-
XML-. XML-
IntelliSense Visual Studio.

XML
# XML-, . . ,
XML-, .
<list> (<>) . : . :
<listheader>
<term> </term>
<description> </description>
</listheader>
. .
:
<item>
<term> _ </term>
<description> </description>
</item>
_.
_ . <item>.
.1. XML

<> < / >


<code> </code>
<exampie>
</example>
< e x c e p t i o n c r e f = "">
explanation
</exception>
<include
file =
1
_' path =
' [_ =
"_"] ' />
< i i s t type = "">
_
_
lit>

, ,
, ,
, ,
,
, XML- .
_. , ID
, , ID ,
~
. ,
: b u l l e t (),
number () t a b l e ()

. XML

733

. . 1

<> </>

<param name =
1
^

</param>

>

, _.

<paramref name
"__ " />

, ^

<permission cref -

, ,
. ,

"">

</permission>
<remarks>

, , ,

</remarks>
<returns>

</returns>

, , ,

<see cref
11
"

, />

<seealso cref =
11
" />

". "

<summary>

</summary>

, , ,

<value>

, ,

</value>

XML-
XML-, ,
/doc. , DocTest.cs, XML, :
e s c DocTest.cs
/docrDocTest.xml
XML-
Visual Studio IDE, Property Pages ( ), View^Property Pages (1^
). Configuration Properties1^Build (
^). XML- XML
Documentation File (XML- ).

XML-

XML-:

/1 XML-.
using System;

734

IV.

<remark>
/// XML-.
/// Test .
</remark>
class Test {
/// <summary>
/// Main().
/// </suinmary>
public static void Main() {
int sum;
sum = Summation(5);
Console.WriteLine(" " +
5 + " " + sum);
<summary>
/// Summation() .
/// <param name = "val">
/// val.
</param>
<see cref="int"> </see>
<returns>
/// int-.
</returns>
</summary>
static int Summation(int val) {
int result - 0;
for(int i=l; i <= val; i
result += i;
return result;

, XmlTest.cs.
I esc XmlTest.cs /doc:XmlTest.xml
,
> XmlTest .xml, :
<?xml v e r s i o n = " 1 . 0 " ? >
<doc>
<assembly>
<name>t</name>
</assembly>
<members>
<member name="T:Test">
<remark>
XML-.
Test .
</remark>
</member>
<member name="M:Test.Main">
<summary>
Main().
. XML

735

</summary>
</member>
<member name="M:Test.Summation(System.Int32)">
J
<summary>
Summation() .
<param name="val">
val.
</param>
<see cref="T:System.Int32"> </see>
<returns>
int-.
</returns>
</summary>
</member>
</members>
</doc>
, .
, XML-.

736

IV.


, , , ,
,

, #
, , , C++ #
,
, , () , , ( )
#-
, ,

(,
), , 1,
-, , -, RS-232,
( , ) -,
,

1 ,

738

IV.

Hobbico Ml Abrams R/C. ( , R/C


.) - , () , .
Hobbico
; ,
. , ,
. 18, 8 .
. BASIC Stamp 2,
(- Parallax, Inc. (www.parallaxinc.com). RS-232, Parallax.
RS-232,
300 . , BASIC Stamp.
, .
. "" , , . , . ( RS-232). BASIC Stamp
. ,
"" BASIC Stamp , . . ,
,
.
, . ,
.
, .
, - C++. , #. ,
. "" , #-.

. #

739

BitArray, , 631
BitConverter, , 530
bool, 54; 61; 521
Boolean, , 521
Boxing, 315
break, 109, 120
BufferedStream, , 378
Button, , 694
ButtonBase, , 694
byte, 54; 376; 406
Byte, , 406
Bytecode, 25

#defme, 441
#elif, 441; 444
#else, 443
#endregion, 446
#error, 445
#if, 44/
#line, 445
#region, 445
#undef, 445
#warning, 445

.NET Framework, 27

A.D., 570
abstract, 309, 340
Access specifier, 39
Anno Domini, 570
API, 688
Application Programming Interface, 688
ApplicationException, , 350; 370
ArgumentException, , 384; 392; 641
ArgumentNullException, , 384; 392;
406
ArgumentOutOfRangeException, ,
617
Array, , 521
ArrayList, , 615
ArrayTypeMismatchException, , 365
as, , 450
ASCII, 60; 376
Assembly, 446
Assembly, , 465
AttributeTargets, , 480
AttributeUsage, , 473; 479

base, 286; 291


Binary Reader, , 394
BinaryWriter, , 394
BindingFlags, , 457

740

, , 24
C++, , 24
catch, 350; 357
char, 54; 60; 376
Char, , 516
checked, 372
class, 39; 127
Client, 669
CLR (Common Language Runtime), 27;
350
CLS (Common Language Specification), 29
COBOL, 31
Collection Base, , 634
CollectionsUtil, , 634
COM, 669, 670
COM (Component Object Model), 18
Common Language Runtime, 27; 350; 365
Common Language Specification, 29
Common Type System, 29
Component model, 669
Component Object Model, 18; 669
Component, , 670
Conditional, , 480
Console, , 40; 377
Console.Error, , 376; 382
Console. In, , 376; 380
Console.Out, , 376
const, , 498
Constructorlnfo, , 461
continue, 122
Control, , 694
Cookie, , 657
CookieCollection, , 657

CookieContainer, , 657
CTS (Common Type System), 29
Culturelnfo, , 519

D
DateTime, , 567
Deadlock, 596
decimal, 54; 58; 406
Decimal, , 406] 512
default, 446
Delegate, 410
delete, 149
Dictionary Base, , 634
DictionaryEntry, , 614
DirectoryNotFoundException, , 384
DivideByZeroException, , 350; 365
DLL, 470
double, 44; 54; 57; 406; 509
Double, , 406; 509
do-while, 119
Dynamic link library, 470

Encoding, , 541
enum, 345
Enumeration, 345
ESC-, 66
Event, 416
EventArgs, , 426
EventHandler, , 428
Exception, , 350; 363
explicit, 246
Expression parsing, 706

false, 61; 237


FIFO, 629
File Transfer Protocol, 646
FileNotFoundException, , 384; 392
FileStream, , 378; 383
finally, 350; 362
fixed, 487
float, 44; 55; 57; 406; 509
for, , 47; 110
foreach, 120, 168; 609; 634
Form, , 690
FormatException, , 406
Forms, , 688
FORTRAN, 31

FTP, 646
FullName, , 452

G C , , 534
goto, 123
GUI, 688

H
Hashing, 621
Hashtable, , 621
HTTP, 646
HttpWebRequest, , 646; 648
HttpWebResponse, , 646; 648
HybridDictionary, , 634
HyperText Transfer Protocol, 646

I
ICloneable, , 536
ICollection, , 610
I Comparable, , 535; 639
I Comparer, , 611; 613; 640
IComponent, , 670
I Convertible, , 536
IDE (Integrated Development
Environment), 34
IDictionary, , 610; 612
I Dictionary Enumerator, , 611;
613; 636
I Enumerable, , 609; 613
IEnumerator, , 609; 613
if, , 45; 103
if-else-if, 105
I Format Provider, , 538
IHashCodeProvider, , 611; 614
I List, , 6, 611
implicit, 246
Indexer, 257
IndexOutOfRangeException, , 158;
351; 365
Instance variable, 32
int, 42; 55; 406
Intl6, , 406
Int32, , 406
Int64, , 406
Integrated Development Environment, 34
interface, 320
internal, , 446
InvalidCastException, , 365

741

IOException, , 377; 384


is, , 449
IsAbstract, , 452
IsClass, , 452

Java, 25
Java Virtual Machine, 25
-, 28
JVM (Java Virtual Machine), 25

Length, , 165
LIFO, 627
List Dictionary, , 634
lock, 495; 587
long, 55; 406

NotSupportedException, , 377; 386;


611
NotSupportedExeption, , 385
null, 365
NullReferenceException, , 365
nybble, 251

object, , 313; 535; 609


ObjectDisposedException, , 385
Obsolete, , 481
OOP (-
), 24
operator, 225
out, , 191; 193; 207
OutOfMemoryException, , 365
OverflowException, , 365; 372; 407
override, 302; 481

M
Main(), 213
MainMenu, , 700
MarshalByRefObject, , 672
Math, , 58] 502
Memberlnfo, , 455
MemoryStream, , 378, 402
Menu, , 700
Menultem, , 700
Message, , 363
MessageBoxButtons, , 698
Method overloading, 203
MethodBase, , 455
MethodlmplAttribute, , 597
Methodlnfo, , 455
MFC, , 688
Microsoft Foundation Classes, 688
Microsoft Intermediate Language, 28; 446
Monitor, , 592
MSIL (Microsoft Intermediate Language),
28; 446
Multicasting, 413
Multiple indirection, 493
Multithreaded programming, 574

N
Namespace, 38; 432
NameValueCollect ion, , 634
new, 147; 291; 331; 340

742

params, , 197
Pascal, 23
Picture format, 563
Pluggable protocols, 645
Preprocessor, 441
private, , 39; 180
Process, , 606
protected, , 283; 340
ProtocolViolationException, , 652
public, , 39; 180

Queue, , 629

R
Random, , 532
readonly, 495
ReadOnlyCollectionBase, , 634
Recursive descent parser, 19
Ref, 414
Yef, , 191; 207
Reflection, 453
Reflection API, 454
return, 123; 137
RTTI, 449
Runtime type identification, 449

sbyte, 55; 406


Sbyte, , 406
Scope, 70
sealed, 313
Security Exception, , 384
SeekOrigin, , 400
short, 55; 406
Single, , 406; 509
Single-threaded apartment, 692
sizeof, 495
SortedList, , 623
Spaghetti code, 23
Sqrt(), , 57
STA, 692
Stack, 33
Stack, , 627
stackalloc, 496
StackOverflowException, , 365; 366
StackTrace, , 363
static, , 39; 218
Stream, 376
Stream, , 377
StreamReader, , 379; 391
Stream Writer, , 379
string, 540
string, , 172
StringBuilder, , 178; 540
StringCollection, , 634
StringDictionary, , 634
StringReader, , 379; 404
StringWriter, , 379; 404
struct, 340
switch, 106; 348
System, , 38; 406; 500
System.Attribute, , 473
System.AttributeUsageAttribute, , 479
System.Collections, ,
609; 610
System. Collections. ICollection,
, 334
System.Collections.IEnumerator,
, 334
System.Collections. Specialized,
, 634
System.ComponentModel.Component,
, 670, 690
System.ComponentModel.IComponent,
, 670
System.Delegate, , 415
System. Diagnostics, ,
606

System. Diagnostics.ConditionalAttribute,
, 480
System. Exception, , 350
System. IComparable, , 334
System. I Disposable, , 497
System.Net, , 644
System.Net.Sockets, ,
644
System.Object, , 313
System.ObsoleteAttribute, , 481
System. Reflection, ,
455
System.Reflection.Memberlnfo, , 453
System.String, , 175; 540
System.Text, , 178; 540
System.Threading, ,
575
System.Type, , 452
System.Windows. Forms, , 688
System.Windows.Forms.Control, ,
690
SystemException, , 350

Target Site, , 363


Text Reader, , 378
TextWriter, , 378
this, 151; 212
Thread, 574'
Thread, , 575
ThreadAbortException, , 602
Threading model, 692
ThreadState, , 604
throw, 350; 360
true, 61; 237
try, 350; 358
typeof, , 452

uint, 55; 406


UIntl6, , 406
UInt32, , 406
UInt64, , 406
ulong, 55; 406
Unboxing, 315
unchecked, 372
Unicode, 60; 376
Uniform Resource Identifier, 645
Uniform Resource Locator, 645
Universal Time Coordinated, 567

743

UNIX, 23
unsafe, 484] 486
Unsafe code, 484
URI, 645
URI, , 654
URL, 645
ushort, 55; 406

-, 25
#, 499
, 48
, 24

using, 39] 435] 497] 499

using, , 682
UTC, 567

, 596
Java, 25
, 301

value, 258] 266] 422

virtual, J07; 340


Visual Studio .NET,
, 34
void, 40, 134
volatile, , 498

w
WebClient, , 663
WebException, , 652
WebExceptionStatus, , 652
WebHeaderCollection, , 656
WebRequest, , 645] 646
Web Response, , 645] 648
while, 117
Windows. Drawing, ,
704
Windows-, 688
Windows-, 690

X
XML, 728

, 82
, 410
, 149

, 302
,
449
, 441

, 51
, 86
, 156
, 257
, 328
, 264
, 260
, 157
, 68
, 32
, 82

break, 109] 121

, 309
, 257
, 706
, 40] 140
, 213
, 473
AttributeUsage, 473] 479
Conditional, 480
MethodlmplAttribute, 597
Obsolete, 481

744

continue, 122
do-while, 119
for, 110
foreach, 120] 168
goto, 123
if, 45] 103

return, 123] 137


switch, 106
while, 117
, 320
ICioneable, 536
ICollection, 610
IComparable, 535] 639

IComparer, 611; 613; 640


IComponent, 670; 671
IConvertible, 536
IDictionary, 610; 612
I Dictionary Enumerator, 611; 613; 636
IEnumerable, 609; 613
IEnumerator, 609; 613
IFormatProvider, 538
IHashCodeProvider, 611; 614
IList, 610; 611
System.Collections. ICollection, 334
System.Collections.IEnumerator, 334
System. Component Model. IComponent,
670
System. I Comparable, 334
System.IDisposable, 497; 671
, 330
, 331
, 350
IndexOutOfRangeException, 158
, 350

, 32; 127
ApplicationException, 350
ArgumentException, 384; 392; 641
ArgumentNullException, 384; 392; 406
ArgumentOutOfRange Exception, 617
Array, 521
ArrayList, 615
Assembly, 465
BinaryReader, 394; 395
BinaryWriter, 394
BitArray, 631
BitConverter, 530
BufferedStream, 378
Button, 694
ButtonBase, 694
CollectionBase, 634
CollectionsUtil, 634
Component, 670, 671
Console, 40; 52; 377
Constructorlnfo, 461
Control, 694
Cookie, 657
CookieCollection, 657
CookieContainer, 657
Culturelnfo, 519
Dictionary Base, 634
Directory Not Found Exception, 384
DivideByZeroException, 350
Encoding, 541

EventArgs, 426
Exception, 350; 363
FileNotFoundException, 384; 392
FileStream, 378; 383
Form, 690
FormatException, 406
GC, 534
Hashtable, 621
HttpWebRequest, 646; 648
HttpWebResponse, 646; 648
HybridDictionary, 634
IOException, 384
ListDictionary, 634
MainMenu, 700
MarshalByRefObject, 672
Math, 58; 502
Memberlnfo, 455
MemoryStream, 378; 402
Menu, 700
Menultem, 700
MethodBase, 455
Methodlnfo, 455
Monitor, 592
NameValueCollection, 634
NotSupportedException, 386; 611
NotSupportedExeption, 385
object, 313; 340; 535; 609
ObjectDisposedException, 385
Overflow Exception, 372; 407
Process, 606
ProtocolViolationException, 652
Queue, 629
Random, 532
ReadOnlyCollectionBase, 634
SecurityException, 384
SortedList, 623
Stack, 627
Stream, 377
StreamReader, 379, 389, 391
StreamWriter, 379, 389
String, 540
StringBuilder, 178; 540
StringCollection, 634
^
StringDictionary, 634
StringReader, 379, 404
StringWriter, 379, 404
System.Attribute, 473
System.AttributeUsageAttribute, 479
System.ComponentModel.Component,
670, 690
System.Delegate, 415
System.Diagnostics.ConditionalAttribute,
480

745

System. Exception, 350


System.Object, 313
System.ObsoleteAttribute, 481
System.Reflection.Memberlnfo, 453
System. String, 175; 540
System.Type, 452
System.Windows.Forms.Control, 690
SystemException, 350
TextReader, 378; 389
TextWriter, 378\ 389
Thread, 575
ThreadAbortException, 602
URI, 654
WebClient, 663
WebException, 652
WebHeaderCollection, 656
WebRequest, 645; 646
WebResponse, 645; 648
, 278
, 278
, 669
#, 51
, 609
, 38
csc.exe,
34
, 669
, 669
, 446
, 65
, 144; 285
, 670; 683
, 495

, 551; 709
, 65
, 66
, 67
, 65

, 155; 491; 521


, 494
, 28; 446
, 123
, 32; 134
Compare(), 334
Main(), 213
Object.EqualsQ, 237

746

Object.GetHashCodeO, 237
Read(), 380
ReadLine(), 381
Sqrt(), 57
ToStringO, 364
Write(), 379
WriteLineO, 379
, 309
, 301
, 320
, 413
, 573
,
493
, 669

, 33; 277
, 330
, 279
, 634

, 70
, 70

, 349
, 32; 127
-
, 24; 31
, 31
, 484

&, 486
*, 486
1,99
[], 257
- > , 488
as, 450
is, 449
new, 147; 340
typeof, 452
XOR ( ), 94
, 48; 82
, 81
1, 95
, 92
, 93
, 48; 82
, 95

, 46
, 393
, 246
, 43\ 89
, 80
, 81
, 84
, 87
, 84
, 90
, 101

, 89
, 96
# , 109
# C++, 150, 155; 160, 172;
202; 280, 345; 410, 485; 540; 575; 609,
670
# Java, 484
, 453
, 629

, 140
, 476
, 476
, 134

, 226
, 208
, 240
, 203
, 224
true false, 237
, 236
, 228
, 42; 68
, 70
, 68
, 70
, 345
MessageBoxButtons, 698
SeekOrigin, 400
ThreadState, 604
UnicodeCategory, 517
WebExceptionStatus, 652
, 347
, 283
, 32; 302
, 708
, 557
, 376; 574

, 376
, 380
, 378
, 73
, 441
, 315
, 74
, 101
, 48
Microsoft, 28
, 431
System, 38; 431; 500
System.Collections, 609, 610
System.Collections.Specialized, 634
System. Diagnostics, 606
System. 10, 377
System.Net, 644
System.Net. Sockets, 644
System.Text, 178; 540
System.Threading, 575
Windows. Drawing, 704
, 645
, 646
, 646
, 574

, 215

, 266
Length, 165
Message, 363
StackTrace, 363
TargetSite, 363
, 327
, 208
, 60
, 586
-, 376
, 365
, 29
, 149
, 416
, 39, 128
, 62; 557
, 180
,
29
, 132

747

, 33; 627
, 66; 172; 540
, 340, 488
Boolean, 521
Char, 516
Decimal, 512
DictionaryEntry, 614
, 23
, 507
, 283

XML, 729

bool, 61
char, 60
decimal, 58
double, 44
int, 44
string, 172
, 57
, 54
, 42
, 54
, 55
, 55
, 55
, 54
, 55

, 54
, 54
, 55
, 55

, 484
,
645
, 60

, 66

, 446

, 563
, 556
, 567
, 571
, 32

, 621
-, 621

, 47
for, 47
, 116
, 116

, 66

, 728

, 670

748

Вам также может понравиться