You are on page 1of 1056

C#

Reference

HERBERT SCHILDT

Me
Grauu
Hill

Learn more. Do more.


MHPROFESSIONAL.COM

#4.0

2011

32.973.26-018.2.75
57
681.3.07
""
. ..
..
"" :
info@williamspublishing.com, http://www.williamspublishing.com
, .
57
C# 4.0: . : . . . : ".. ", 2011.
1056 . : . . . .
ISBN 978-5-8459-1684-6 (.)
32.973.26-018.2.75

.

, ,
,
McGrow-Hill Higher Ed.
A uthorized translation from the English language edition published by M cGraw-Hill Companies,
Copyright 2010
All rights reserved. Except as permitted under the Copyright Act of 1976, no part of this publication may
be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without
the prior written permission of publisher, with the exception that the program listings may be entered, stored,
and executed in a computer system, but they may not be reproduced for publication.
Russian language edition published by Williams Publishing House according to the Agreement with R&I
Enterprises International, Copyright 2011

C# 4.0:

..
..
.
.

17.09.2010. 70x100/16.
Times. .
. . . 85,14. .-. . 51,55.
1500 . 24007.
CtP
" " . . .
197110, -, ., 15.
". . ", 127055, . , . , . 43, . 1
ISBN 978-5-8459-1684-6 (.)
ISBN 0-07-174116- (.)

"", 2011
by The McGraw-Hill Companies, 2010

. #
1. C#
2. C#
3. ,
4.
5.
6. ,
7.
8.
9.
10.
11.
12. ,
13.
14. -
15. , -
16. ,
17. ,
18.
19. LINQ
20. , ,

23
25
29
31
41
67
97
121
147
177
209
269
303
329
375
403
431
473
513
537
575
637
681

. C#
717
21. System
719
22.
783
23. . :
833
24. . : TPL
885
25. ,
923
26.
1011
. 1039

1044

22
22

23

25

. #
1. C#
C#

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

2. C#
-


csc.exe
Visual Studio



27
27
27
27
28
28

29
31
32
32
33
33
34
36
37
37
38
38
39

41
41
42
43
44
44
45
46
50
53
54
54







C#

.NET Framework

3. ,

C#


4.







, ,

57
58
58
60
61
63
64
65
66

67
67
68
69
71
73
74
75
76
79
80
80
81
83
83
84
85
86
89
90
91
93
95

97
97
98
101
104
106
107
107
108
114

5.
if
if
if-else-if
'
switch
switch
for
for
while
do-while
foreach
break
continue
return
goto

6. ,




Building



Building


Building
new
new
" "

this

7.

9
117
117
119
119

121
121
122
124
125
129
129
131
137
138
139
139
142
143
143

147
147
148
149
153
154
155
156
158
159
162
164
166
166
168
169
170
170
171
172
174

177
177

10








Length
Length


foreach





switch

8.






ref out
ref
out
ref out



,


this






Main()
MainQ

178
182
182
183
184
185
187
189
191
192
194
198
198
199
203
205
206

209
209
210
212
212
218
220
222
223
224
227
229
231
234
235
241
245
246
247
249
250
251
252
254
254


Main()

static

9.



C#

true false






10.

11.





*
base


11
255
257
260
265
266

269
270
270
273
277
281
283
286
286
288
292
297
298

303
303
304
307
310
311
313
318
319
320
320
324

329
329
333
336
337
339
343
344
346
349
351

12





sealed
object

object

12. ,









.NET Framework

13.
System.Exception

try catch



""

catch

try


finally
Exception

355
359
360
363
367
368
370
372

375
375
377
381
383
385
387
388
388
391
391
391
395
397
399
399
399

403
404
404
404
405
407
408
410
411
412
413
414
415
416
418
420




checked unchecked

422
426
428

14. -

431

- C#



Stream

-

-

ReadKey()

FileStream -

-

FileStream
-
Stream Writer
StreamReader


Binary Writer
BinaryReader
-

MemoryStream
StringReader StringWriter
File
()
Exists() GetLastAccessTime()

431
432
432
432
432
434
434
436
436
436
438
440
441
441
444
446
448
449
449
451
452
454
454
455
457
461
463
465
467
467
468
469

15. , -

13

473

'

473
476
477
478
481

14

System.Delegate






-
-
-
-






-

.NET Framework
EventHandler<TEventArgs> EventHandler

16. ,



using
using



::

#define
#endif
#else #elif
#undef
#
#waming
#
#region #endregion
#pragma
'
internal

483
483
483
484
484
485
486
488
488
489
492
494
496
497
500
504
504
506
508
509

513
513
514
516
518
520
521
523
524
524
528
529
529
531
533
533
534
534
534
534
535


internal

17. ,

is
as
typeof

System.Type








AttributeUsage
Conditional
Obsolete

18.









new()

15
536

537
537
538
539
540
541
541
543
544
548
550
555
560
562
563
566
570
570
571
572

575
576
576
580
580
583
585
585
586
594
598
599
602
603
604
606
607
609
610
610

16

612

615
620











, *

620
622
623
625

636

19. LINQ

626
626
630
633
635
636

637

LINQ

638





where

639
641
642
643
644

orderby
select
from

646
649
653

group

655

into
let

657

join

660
663

666





,
:

669
669
670
673
673
675

676
678

PLINQ

659

680

17

20. , ,

681



unsafe
fixed











??
,





lock
readonly
const volatile
using
extern

681
682
684
685
686
686
688
688
690
691
692
693
695
695
697
698
699
700
701
703
707
708
708
708
709
710
711
712

II. C#
21. System
System
Math
.NET,


Decimal
Char
Boolean
Array

717
719
720
721
727
728
730
735
741
748
750
763

18




Action
BitConverter
Random
GC
object
Tuple
IComparable IComparable<T>
IEquatable<T>
IConvertible
ICloneable
IFormatProvider IFormattable
IObservable<T> IObserver<T>

22.
C#
String
String
, String
String

,

Substring()
String




String.Format() ToString()

String.Format()
ToStringQ

-



^

23. . :

766
767
768
769
771
773
774
776
777
778
778
779
779
781
781

783
783
784
784
785
786
808
810
811
811
812
812
812
814
815
816
816
819
820
820
824
827
829
830

833
834


Thread





IsBackground


Monitor
Wait(),
Pulse() PulseAll()
Wait() Pulse()

MethodlmplAttribute


Interlocked
, .NET Framework 4.0

Abort()
Abort()



,
.NET Framework 4.0

24. . : TPL

Task



Dispose()
TaskFactory
-

19
835
836
838
839
841
844
846
847
849
853
855
855
856
860
860
862
863
867
870
873
874
875
876
878
880
880
880
882
882
882

885
886
887
887
890
891
895
895
896
897

20


AggregateException

Parallel
Invoke()
For()
ForEach()
PLINQ
ParallelEnumerable
AsParallel()
AsOrdered()

PLINQ
PLINQ

25. ,
.


DictionaryEntry

BitArray



KeyValuePair<TKey, TValue>


, ,
IComparable
IComparable
IComparable
IComparer
IComparer
IComparer<T>
StringComparer


IDictionaryEnumerator
IEnumerable IEnumerator


yield

899
901
905
906
906
909
915
917
917
918
919
920
922
922

923
924
925
926
931
931
950
953
954
954
960
960
983
988
990
990
992
994
994
996
997
998
999
1000
1001
1003
1005
1006

26.
System.Net


WebRequest
WebResponse
HttpWebRequest HttpWebResponse


, Create()
, GetResponse()
, GetResponseStream()

Uri
,
HTTP

-
LastModified
MiniCrawler
WebClient

.

XML-

XML

21
1006
1008
1009

1011
1012
1013
1014
1015
1017
1018
1018
1021
1021
1022
1022
1022
1024
1025
1026
1027
1029
1030
1034

1039
1039
1041
1041

1044

06
(Herbert Schildt)
#, C++, Java.

. ,
Java, C++, (
"" 2007 2008 .).
,
, ,
.
.
. , -
w w w .H e r b S c h i l d t .c o m .
N

0
(Michael Howard)
,
(TwC) Microsoft,

,
. (Security
Development Lifecycle SDL)
, Microsoft.
Microsoft 1992 ,
Windows
(Product Support Services) ,
(Microsoft Consulting Services),

. 1997
Windows - Internet
Information Services, -
Microsoft, 2000
.
IEEE Security & Privacy,
, ,

.
.



.
, ,
.


,
,

.

.
,
.
,
, .
, ,
,
, . ,
,
: ,
, .
#.
C# Microsoft
.NET Framework
.
(Anders Hejlsberg)
. C#

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

26


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

.

, ,

. C# .
, C#
.
, C#
1.0 2000 .
,
C# 2.0, , ,
. , C#
2.0 .
, #. ,

.
, C# 3.0 .
, ,
C#
. : LINQ
-. LINQ .
, #.
- -
=>, - LINQ-.
, C# 4.0,
.

. ,
, ;
dynamic, C# ,
, ,
() ;
, #, ,
. .NET
Framework, #,
TPL (Task Parallel Library
) PLINQ (Parallel LINQ
). , -

27


. , C# 4.0

.

C# -
. ,
.
, .
.


4.0 #. . I
#, ,
4.0. , ,
, - ,
.
II #,
.NET Framework. ,
.
II ,
System. , ,
, ,
TPL PLINQ. ,
, #.


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


C# 4.0,
, Visual Studio 2010 ( ).

,
, ,
, w w w . m h p r o f e s s i o n a l .com.

28


"" ,
. ,
.
Java .
Java ( " ", 2007 .)
Java: ( " ", 2008 .)
SWING: ( "", 2007 .)
Java ( "", 2005 .)
Java. ( "", 2008 .)
C++
.
C++ ( "", 2007 .)
C++. ( "", 2005 .)
STL Programming From the Ground Up
C++
C++. ( "", 2009 .)
,
,
( "", 2007 .)


, , .
, ,
.
, .
.
, Web-
. , ,
, ,
.
, ,
.
.
:
E-mail:
i n f o 0 w i l l i a m s p u b l i s h i n g .c om
W W W :

http://www.williamspublishing.com

:
:
:

127055, . , . , . 43, . 1
03150, , / 152

C#
I
#, ,
.
, #,
- .

1 C#
2
C#
3 ,

4 I
5

6 ,

7
8

9

10

11
12 ,


13

14
-
15,

16
,

17
,

18
19 LINQ
20
, ,

C#


.NET
Microsoft.


,
.
, ,
XXI .
C#
, ,
,

. ,
C# .NET Framework.
, C# .NET Framework
.

32

I. C#

C#
. ,
,
. ,
,
,
.
. C# .
C# " ".
: C++.
: Java.
#. ,
C# .

-
.
(Dennis Ritchie) 1970-
- DEC PDP-11 Unix.
, Pascal,
, ,
.

1960- .
,
"" ,
, .

, .

, .

, ,
. ,
, , ,
. ,
" ", .

1980- .
, , .

. ,
,
. ,
, ,
"", .

1. C#

33

C++
1970- ,

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

-
.
, C++
. ,
.
, ,
, .

Java

Java. Java, Oak (),
1991 Sun Microsystems. " " Java
(James Gosling),
(Patrick Naughton), (Chris Warth),
(Ed Frank) (Mike Sheridan).
Java , -
, C++.
Java
, ,
.
,
. ,
, , ,
,
. ,

34

I. C#

,
.
, Java.
( ) Java
, , ,
, Java ,
,
. 1993 ,
,
,
. ,
, "" .
, ,
,
.
Java
, -. -
Java (JVM) Java.
, Java ,
JVM. JVM ,
.
- Java C++,
,
, , .
, C++ ,
.
, C++,
,
. , .
Java
. #.
, Java C++.
, C++. Java
C++ , ,
, C++
Java. , Java
,
. C++,
, .. Java
. , Java C++ ,
.

C#
Java
, . , ,
,
. , ,

1. C#

35

, .
,
. ,
,

.
, Java,
Windows. Java Moiyr
Windows, , Java, Java
Windows . Windows
,
Windows Java.

Microsoft 1990- C# .NET.
- 2000 .
C#
,
. , 1980-
Turbo Pascal,
.
C# , C++ Java. .
.
, C#
, C++ Java. C#
, , C++ Java
. ( )
,
#.
. 1.1 #. C#
, ,
. , C# ,
C++. C++, #.

. 1.1. C#

36

I. C#

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

C#
1.0 C# .
1.0 Microsoft 1.1,
, .
C# 2.0.
2.0 #,
, ,
,
, .
2.0 "" #.
Microsoft
.
C# 3.0.
C# 2.0
#,
, . 3.0 Microsoft
,
. , , -,
(LINQ),
. , ,
, :
(LINQ) -. LINQ C#

.
C# 4.0, .
#,
. ,
. ,

1. C#

37

.
.
dynamic, ,
, .
,
in out. ,
Office Automation API ,
,
. , , C# 4.0,
#.
, 4.0
#, , .NET
Framework 4.0.
(TPL)
(PLINQ).
,
. ,
,
.
,

, #.
TPL PLINQ .

C# .NET Framework
C# ,
.NET Framework.
. -, C#
, .NET Framework. -,
C# .NET Framework.
, C# .NET Framework , C#
.NET Framework.
.NET Framework #.

0 NET Framework
.NET Framework
.
, ,
Windows.
#, .NET Framework
. (Common
Language Runtime CLR). , .
CLR .NET Framework
,
.

38

!. #

.NET Framework .
. ,
-, - ,
.NET. ,
, .
, , , .
, .NET,
,
.NET. C# .NET ,
C# .NET
Framework.

CLR
CLR .NET.
. C# ,
, , Microsoft Intermediate Language,
MSIL ( Microsoft). MSIL
, . , MSIL
. , , , ,
MSIL - Java, .
CLR
. , ,
MSIL, , CLR.
.NET Framework.
MSIL ]1-.
JIT
. .
CLR JIT-,
MSIL
. , C#
, , MSIL.
, , ,
,
MSIL.
MSIL, C#
, , ,
.
, MSIL.


, C#
. ,
CLR, ,
. : -

1. C#

39

MSIL,
CLR, .NET,
#. , ,
,
, ,
.
, CLR.
, .NET Framework Windows
. ,
, , C#
, *
- .


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

C#

,
.
, .

C# .

#,
#,
. ,

#.
,
,
I.

C# -
().
#, C#
-
.
,
#.

.

42

!. #

, , ,
. , , ,

. ,
.
,
,
.

, , , FORTRAN COBOL,
, -
.
,
, .

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

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

2. C#

43

,
.
. , ,
. ,
, .
,
.
C# ,
. , , . C#
,
. , , ,
.
, , . ,
, , . ,
, -,
. C# . (
- , .) ,
, , .

, - " ", ,
.
,

. ,
: ,
. ,
, .
, , , ,
.
.
, .. , "
". ,
: , ,
. ,
, , ,
. , -,
.
C#
. , ,
.

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

44

I. C#

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


#.
.
/*
#.
Example.cs.

*/
using System;
class Example

// C# Main().
static void Main() {
Console.WriteLine(" #.");

}
}
C# Visual Studio
Microsoft. ,
, , C# 4.0,
Visual Studio 2010 , #.
, #, Visual Studio,
: , -,
Visual Studio, -, c s c . .
.

2. C#

45

c s c .
, ,
Visual Studio,
, ,
,
. ,
. ,
, .
, (Command Prompt)
Windows,
,
.

, ,
Visual Studio.
C# - ,
, .

C#
.
1'. , .
2. csc . .
3. .


, ,
www. m h p r o f es-sional . com.
.
, Notepad. ,
, , ,
, ,
#. ,
E x a m p l e .cs.


C#
c s c ., .
C:\>csc Example.cs

csc E x a m pl e ., MSIL
. MSIL ,
. . CLR
JIT- Example .. , ,
, Example . (

46

!. C#

, MSIL) , .NET
Framework , ,
CLR.

c s c .,
, HacTpoeHHoenoAVisualStudio. Visual S tud ios
Visual ^ ^ Visual Studio (Visual Studio^Visual
Studio Tools^Visual Studio Command Prompt) ^ (Start^AII
Programs) Windows. ,
, vsvars32.bat,
Visual Studio.



.
: \>1

.
#.

Visual Studio
Visual Studio ,
Microsoft. ,
, #,
. Visual Studio
, .
,
, , ,
.
,
C# Visual Studio 2010.
, Visual
Studio 2010 Professional. Visual Studio
.
1. () #, => 1^
(File =>New ^Project). W indows
(Installed Templates) (Empty Project),
.

, .

2. C#

47

JLl*J

j NET Framework 4

^ '

: |

(
^ r? ]

Windows Forms
| WPF

W
M
H

: Visual C#

Visual C#

- visual #_
Windows

Visual Ct

Office

Visual C#

Visual C#

Cloud

c#

Reporting
Silver light

WPFVisual C#

WCF
Workflow

*d

. Visual #

... Visual C#


!.'

Visual C#

t 1<=(

Windows

Visual 9

visual C#

|Projectl

|C:\C# Examples|

(projectl

, .
Visual Studio ,
.

- (Solution Explorer)
,
(View^Solution Explorer).

!. #
,
#.
( Project 1) ,
(Add) . ,
.
Project 1 Microsoft Vi ial Studio
!
*
J-

- a *

Create

)
Projecti' ( 1)
I


I 4

"'
^

Cbinof

Wndnwr

?nbcw*i w

it ^

J] 1

. .

ij

(New Item),
(Add New Item). (Code)
,
(Code File) E x a m p l e .cs, .
-*]

Visual #
Wndows Forms
WPF

Reporting
Workflow

| *
j *

"3

Visual C f

Visual #

|
: Veual C#
C#

' !

ADO NET. . Visual C f

.. Visual C f
. . Visual C f

|Example. cs|

2. C#

49

5. , .
, .

6. E x a m p l e .cs,
. ( ,
, w w w . m h p r o f e s s i o n a l .com,
.)
, .
Protect 1 Microsoft Visual Studio
**.

J*

*^

twu

AJ

*-

-4 ^

'

1 sj

Te rr
Debug

*
~

Create

1 -j -

*4

4 Projectl" (; 1)

Projectl

>
13 Example.cs

50

!. #

7. ,
(Build1=>Build Solution).
8. , ^ (Debug^Start
Without Debugging). ,
.
; WINDOWS'
( # .
.+

n32 i. .
'

J
,

.
.
#. .
.
.
.


, , Visual Studio
,
. ,

.
.
, Visual Studio.


E x a m p l e .cs ,
, #.
, .
, Java,
, C#
.
E x a m p l e .cs, , C#
. ,
S a m p l e .cs, T e s t .cs X .cs.

2. C#

51

C# . c s ,
. ,
,
.
E x a m p l e .cs. C# ,
,
. .
, .
/*
#.
Example.cs.

*/
.
, C#
. . ,
,
, .
, E x a m p l e .cs.
,
.
C# .
.
/ * * / . ,
, .
, .
.
using System;

, System.
C# .
, .
.
, , ,
, .
System, ,
.NET Framework, #.
using ,
. (
, ,
.)
.
class Example {

class
. ,
#, a E x a m pl e .
({) (}). ,
, .

52

!. #

, , C# ,
, .
.
// C# Mai n ( ) .

, #.
/ / .
,
,
. ( , #,
.)
.
static void Main()

Main (). , C#
. , ,
. C#
Main ().
,
#. ,
, .
s t a t i c . ,
s t a t i c , .
, Main () .
v o id , Main () .
, .
Main ,
. Main () ,
.
{, Main () . ,
, .
. ,
Main ().
Console.WriteLine(" #.");

"
WriteLine ().
W ri t e L i n e () , .
, , . ,
WriteLine () .
Console ,
- . Console WriteLine ()
, WriteLine () Console.
C#
- .
, , WriteLine (),
, , ,
us i n g System. , C# .
, {
C# .

2. C#

53

}.
.
.
} M a i n ( ) ,
Example.
, C# .
. ,
main Main writeline WriteLine,
. , C#
, Mai n (), .
Main,
, , E x a m p l e .
.


,
( ) ,
.
.
,
. , - ,

.
, ,
.
,
, . C#
- , .
, ,
.
M ai n ()

c s c . (
Visual
Studio.)
E X l .C S (12,21): CS1002: ;
E X l .C S (13, 2 2 ) : CS1519: '('
,
E X l .C S (15,1): CS1022:

, ,
, .
.
,
, ,
.

54

I. C#

. ,
, ,
.
, .



, , .
using System;

. , C#
,
. ,
Console.Write L i n e (" #.");

.
System.Console.WriteLine(" #.");

, .
// "using System;".
class Example

// C# Main().
static void Main() {
// Console.WriteLine .
System.Console.W r i teLine(" #.");

}
}
S ys te m ,
, ,
C# using System ,
, . , ,
, , ,
.


, , ,
. , . ,
. ,
.
.

2. C#

55

// .
*

using System;
class Example2 {
static void Main() {
int x; //
int ; //
= 100;

// 100

Console.W r i teLine(" " + ) ;


= / 2;
Console.W r i t e (" / 2: ");
Console.W r i teLine();

}
}
.
100
/ 2: 50

. ,
int ; //

. C#
. ,
, . .
, .. .
C#
i n t . ,
in t.
.
int ; //

, , ,
, .
, :

_;

, _
. in t, C# .
100.
= 100; // 100

C# (=).
,
, , .

56

I. C#


11 11 .
Console.Writ e L i n e (" " + ) ;

+ ,
. ,
+
WriteLine ().

, 2.
= / 2;

2,
. ,
50. .
, C#
, .

+
*

.
Co nsole.W r i t e (" / 2: ");
Co nsole.Write L i n e ();

. -,
" / 2 : 11
W r i t e (). . ,
. Wr i te ()
W r i t e L i n e (), ,
. -, ,
W r i t e L i n e () . , Wr ite ()
n W r i t e L i n e (),
C# .
>
.
. . ,
.
int , ; //

C# , .
,
. 3.

2. C#

57


i n t .
i n t .
, . , i n t
18, 18,3. , i n t
, #. ,
, C# : float double.
.
double.
double
double result;

r e s u l t d ou b le. r e s u l t
,
, , , 122,23, 0,034 -19,0.
. i n t d ou b le
.
/*

int double.

*/
using System;
class Example3 {
static void Main() {
int ivar; //
double dvar; //
ivar = 100; // ivar 100
dvar = 100.0;

// dvar 100.0

Console.WriteLine(" ivar:
Console.WriteLine(" dvar:

" + ivar);
" + dvar);

Console.WriteLine(); //
// 3.
ivar = ivar / 3;
dvar = dvar / 3.0; Console.W riteLine(" ivar :
Console.WriteLine(" dvar :

" + ivar);
" + dvar);

}
}
.
ivar:
dvar:

100
100

58

I. C#

ivar :
dvar :

33
33.3333333333333

, i v a r i n t 3
33, .
d var double 3 .
,
. ,
100 C# , 100,0 .
.
W rite L in e O .

, . ,
, 3,1416 "".
// .
using System;
class Circle {
static void Main()
double radius;
double area;

radius = 10.0;
area = radius * radius * 3.1416;
Console.WriteLine(" " + area);

}
}
.
314.16

,
, .


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


i f C#
. i f C# ,
IF . ,

2. C#

59

i f , C++ Java.
.
if ( ) ;

, .. , ,
: "" "". ,
. , ,
. .
if (10 < 11) Console .WriteLine (1110 11);

,
10 11, WriteLine () .
.
i f (10 < 9) Console.WriteLine (" ");

10 9. , W r i t e L i n e ()
.
C# ,
. .

<
<=
>
>=
==
i=

,
i f .
// if.
using System;
class IfDemo {
static void Main()
int a, b, c;

a = 2;
b = 3;
if(a < b) Console.WriteLine(" b");
// He .
if(a == b) Console.WriteLine(" ");
Console.W riteLine();
c = a - b ;

//

-1

60

I. C#

Console.WriteLine(" -I);
i f ( >= 0) Console.WriteLine(" ");
i f ( < 0) Console.W r i teLine(" ");
Console.WriteLine();
= b - ; // 1
C onsole.W r i teLine(" I );
i f ( >= 0) Console.WriteLine(" ");
i f ( < 0) Console.WriteLine (" ");

}
}
.
b
-1

1

.
int , , ;

, , , , .
,
, , .



. C#
. for. if,
f or C# , C++ Java.
.
for ( ; ; )


.
, .
, . ,
.
, .
, for.
// - for.
using System;
class ForDemo

2. C#

61

static void Main() {


int count;
for (count = 0; count < 5; count = count+1)
Console.WriteLine(" :

" + count);

Console.WriteLine("!");

}
}
.
:
:
:
:
:
!

0
1
2
3
4

count .
for
. , , count < 5.
, ,
W r i t e Li ne (). for,
count 1.
, count 5.
,
. , .
, , #,
,
, .. .
count = count + 1 ;

, C# ,
1 , .
+ (++). ,
.
count++;

, for
.
for (count = 0; count < 5; count++)

.
, , .
C# , ( ).
1.


C# ,
.

62

I. #

.
, ,
, . ,
if for. if.
if(w < h) {
v = w * h;
w = 0;

}
w
h, .
, .
, ( ) ,
.
.
/
, ,
.
// .
using System;
class BlockDemo {
static void Main()
int i, j, d;

i = 5;
j = 10;
// if ,
if(i != 0) {
Console.WriteLine ("i ");
d = j / i;
Console.Write Line("j / i " + d ) ;

}
}
}
.
i
j / i 2

i f ,
. , i f, ,
.
i, , .
,
1 10.
// 1 10.
using System;

2. C#
class ProdSum {
static void Main()
int prod;
int sum;
int i;

63

sum = 0;
prod = 1;
for (i=l; i <= 10; i++)
sum = sum + i;
prod = prod * i;

}
Console.WriteLine(" " + sum);
Console.WriteLine(" " + prod);

}
}
.
55
362880 0


.
.
:
. , { }, ,
.
, ,
,
.


C# . ,
.
,
, . ,
.
.
C#
.
. , C#
X = ;
= + 1;
Console.WriteLine( + " " + );

,
= ; = + 1 ; Console.WriteLine( + " " + );

64

I. C#

, .
, C# .
Console.Writ e L i n e (" " +
+ + z +
" ");

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

C#
,
, . C#
: .
, .
.
. ,
. 4.0 C# 77
^ (. 2.1).

2.1. , C#
abstract
byte
class
delegate
event
fixed
if
internal
new
override
readonly
short
struct
try
unsafe
void

as
case
const
do
explicit
float
implicit
is
null
params
ref
sizeof
switch
typeof
ushort
while

base
catch
continue
double
extern
for
in
lock
object
private
return
stackalloc
this
uint
using

bool
char
decimal
else
false
foreach
int
long
operator
prot ec t ed
sbyte
static
throw
ulong
virtual

break
checked
default
enum
finally
goto
interface
namespace
out
public
sealed
string
true
unchecked
volatile

2. C#

65

, C# 4.0 18 ,
.
,
, . ,
* . , ,
, .
-
,
. . 2.2.

2.2. C#
add
group
partial
var

dynamic
into
remove
where

from
j oin
select
yield

get
let
set

global
orderby
value

C# , ,
.
.
.
, .
, , , line_count.
, , , m a x __ value,
. C#
. , myvar MyVar .
.
Test
up

X
top

2
my var

Ma xL oa d
sample23

, . , 12
.
, .

, C#
@ . , @ f o r
.
for, @ .
, @.
//
using System;
class IdTest {
static void Main() {
int @if; // if

66

I. C#
//
for(@if = 0; @if < 10; @if++)
Console .Writ-eLine ("@if " + @if) ;

}
}
, @i f
.
@if
@if
@if
@if
@if
@if
@if
@if
@if
@if

0
1
2
3
4
5
6
7
8
9

, @
, . , @
,
.

.NET Framework
, ,
: Wr it e L i n e () Write (). ,
Console, System,
.NET Framework.
, C# ,
.NET Framework, -, ,
. , , C#
C#
.NET. ,
, #.
#, ,
.
.NET Framework I , II
.

,


#: , .

, ,
, ,
. ,
C#
,
.
, C#
.


#,
. ,

,
. ,

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

68

I. C#

C# 4.0 , dynamic
,
. dynamic
. dynamic
17.

C#
C# :
. .
, , 3,1416 212.
, .

, .
.
C# 13 , . 3.1.
, . (
, .)
#, , ,
.
.

. 3.1. C#

bool
byte
char
decimal
double
float
int
long
sbyte
short
uint
ulong
ushort

, :
8-

( )


8-



C# .
, C#
. , int
.

3. ,

69

.
,
.

, C# : ,
. .


C# : char, byte, sbyte, short, ushort,
int, uint, long ulong. char , ,
.
.
.

byte

8
8
16
16
32
32
64
64

sbyte
short
ushort
int
uint
long
ulong

0 -2 5 5
-1 2 8 -1 2 7
-3 2 7 6 8 -3 2 767
0 -6 5 535
-2 147 483 6 4 8 -2 147 483 647
0 - 4 294 967 295
- 9 223 372 036 854 775 8 0 8 -9 223 372 036 854 775 807
0 - 1 8 446 744 073 709 551 615

, C#
: .

. , ,
C# ,
. , ,
, 1.
,
, 1.

, .
, , 32 767 short .
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

1,
, -1,
. ushort,
1 65 535.

70

!. #

,
in t. i n t
, .
,
in t, . ,
, u in t,
lon g,
ulong. ,
.
long.
// .
using System;
class Inches {
static void Main()
long inches;
long miles;

miles = 93000000;

// 93 000 000

// 5 280 , 12 ,
inches = miles * 5280 * 12;
Console.WriteLine(" :
inches + " .");

" +

}
}
.
:

58 92480000000 .

, i n t
u in t.
b y te s b y te . b y te
0 255. b yte
,
, .
s b y te . ,
b y te ,
1 100.
// byte.
using System;
class Use_byte {
static void Main()
byte x;
int sum;
sum = 0;

3. ,

71

for(x = 1; <= 100; ++)


sum = sum + ;
Console.WriteLine(" 1 100 " + sum);

}
}
.
1 100 5050

1 100,
byte,
.
, , byte sbyte,
, int uint, short
ushort.


. C#
: float double.
.
, float 32 ,
5-45 3,4+38. double
64 , 5-324
1,7+308.
C# double, , ,
#,
.NET Framework,
double. , Sqrt (),
System. Math, double,
double, .
Sqrt ()
.
// .
using System;
class FindRadius {
static void Main()
Double r;
Double area;

area = 10.0;
r = M a t h .Sqrt(area / 3.1416);
Console.W riteLine(" " + );

72

I. C#
.

1.78412203012729


Sqrt (). , Sqrt () Math,
* Math .
Con so le W ri t e L i n e () .
, , ,
.

, Math
#. double.
, ,
0,1 1,0 .
// .
using System;
class Trigonometry {
static void Main() {
Double theta; //

for(theta = 0.1; theta <= 1.0;


theta = theta + 0 . 1 ) {
Console.WriteLine(" " + theta +
" i " + M a t h .Sin(theta));
Console.WriteLine(" " + theta +
" " + M a t h .Cos(theta));
Console.WriteLine(" " + theta +
" " + M a t h .Tan(theta));
Console.WriteLine ();

}
}
}
.
0.1 0.0998334166468282
0.1 0.995004165278026
0.1 0.100334672085451
0.2 0.198 6693307 95061
0.2 0.980066577841242
0.2 0.202710035508673
0.3 0.2 9552020666134
0.3 0.955336489125606
0.3 0.309336249609623

,
M a t h .Sin ( ) , M a t h .Cos () M a t h .Tan ( ) .
M a t h . Sqrt (),
double .
.

3. ,

73


, C#
d ecim al, .
128 1-28
7,9+28. , , ,
.
d ecim a l,
28 ( 29) .
,
, .
, d ecim al
.
.
// decimal .
using System;
class UseDecimal {
static void Main() {
decimal price;
decimal discount;
decimal discounted_price;
// ,
price = 19.95m;
discount = 0.15m; // 15%
discounted_price = price - ( price * discount);
Console.W riteLine(" :

$" + discounted_price);

}
}
.
:

$16.9575

, d e c im a l
. ,
m
, d ecim al.
decim al , 10. (
.)
decim al.

.
/*
decimal
.

*/

74

I. #

using System;
class FutVal {
static void Main() {
decimal amount;
decimal rate_of_return;
int years, i;
amount = 1000.0M;
rate_of_return = 0.07M;
years = 10;
Console.W r i teLine(" : $" + amount);
Console.WriteLine(" : " + rate_of_return);
Console.Write L i n e (" " + years + " ");
for(i = 0 ; i < years; i++)
amount = amount + (amount * rate_of_return);
Console.Wri t e L i n e (" $" + amount);

}
}
.
: $1000
: 0.07
10
$1967.151357289565322490000

,
, ..
, ! ,
"" .

C# 8- ,
, C++, 16- ,
(Unicode). ,
.
, , ,
, , ,
,
8- . C# ch a r,
16- 0 65 535.
8- ASCII
0 127. , ASCII -
#.
,
(.. ) . ,
ch X.

3. ,

75

char ch;
ch = 'X';

char W r i t e L i n e ().
, ch.
Console'.WriteLine (" ch :

" + ch) ;

c h a r C# ,
. , C#
.
, .
char ch;
ch = 88; // ,

, 8 8
, .

.
, ,
.


bool : "" "".
C# true false
. , bool
. , C#
. , 1 true,
0 false.

bool.
// bool.
using System;
class BoolDemo {
static void Main()
bool b;
b = false;

Console.WriteLine("b " + b ) ;
b = true;
Console.WriteLine("b " + b ) ;
// if.
if(b) Console.W riteLine(".");
b = false;
if(b) Console.WriteLine("He .");

76

I. C#
//
// .
Console.WriteLine("10 > 9 " + (10 > 9));

}
.
b False
b True
.
10 > 9 True


. -, b o o l
W r i t e L i n e O "True" "False". -,
bool if.
, , if .
if(b == true)

...

-,
. 10 > 9
"True." , 10 > 9 ,
+ , >.


W r i t e L i n e O
, . .NET Framework
,
. -
,
. ,
W r i t e L i n e ().
. , , ,
, ,
.

+, .
Console.WriteLine(" " + 2 +
" $" + 3 + " .");

, ,
. ,

.
Console.WriteLine(" 10/3 :

.
10/3 :

3.33333333333333

" + 10.0/3.0);

3. ,

77

,
. ,
.

WriteLine (), ,
.
WriteLine ( " ",

argO,

a r g l,

... , argN );

WriteLine () , +.
: ,
, .
:
{argnum,

w id th :

fm t}

argnum , ; w id t h
; fm t . w id th fm t .

, ,
argnum. ,

. w id t h fm t' . ,

. , { 0 } ,
{1 } a r g l ..
.
Console.WriteLine("

{0} {1} .",

28, 29);

.
28 2 9

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

28, 29);

28

2 9 .

, . ,
w id th . ,
.
, , ,
. ,
.
.

78

I. C#

// .
using System;
class DisplayOptions
static void Main()
int i;

{
{

Console .WriteLine (" ^ ^ " ) ;


for(i = 1; i < 10; i++)
Console.WriteLine("{0}\ t {1}\ t {2}",

i, i*i,

i*i*i);

}
}
.

1
2
3
4
5
6
7
8
9

1
4
9
16
25
36
49
64
81

1
8
27
64
125
216
343
512
729

.

. :
.
, WriteLine().
#,
. , , .
10 3.
Console.Write L i n e (" 10/3 :

{0:#.##}",

10.0/3.0);

.
10/3 :

3.33

# . ## W r i t e L i n e ()
. , , ,
WriteLine () ,
.
.
Console.WriteLine("{0:###,###.##}",

123456.56) ;

.
123,456.56

, ,
.

3. ,

79

decimal balance;
balance = 12323.09m;
Console.WriteLine(" {0:C}", balance);

,
.
$12,323.0 9

,

.
//
// .
using System;
class UseDecimal {
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:C}",

discounted_price);

}
}
.
:

16,96 .

C# ,
. , 100 .
,
.
.
C# .
. ,
. , 1 1 1%1 .
. ,
10 -1 0 0 .
. ,
1 1 .1 2 3 .
C# .

80

I. C#

, C#
. :
, 2 , 123987 0 . 23? ,
C# .
-,
, , int. ,
: int, uint, long
ulong . -,
double.
,
. , long
1 L. , 12 int, a l 2 L
long.
U. , 100 int, a 100U
uint.
ul UL. , 984375UL ulong.
, float F f.
, 10 .19F float. double,
d D, . , ,
double.
, decimal m
. , 9 .95 decimal.

int, uint, long ulong, byte,
sbyte, sh or t ushort, ,
.


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

, C#
. ,
.. "".
.
count = OxFF;
incr = 0x1;

// 255
// 26


,
, ,
. , ,
, #,

3. ,

81

. C#
,
(. 3.2). ,
.'

3.2.

\a
\b
\f
\n
\r
\t
\v
\0
V

\"
w

()

( )
( )






, ch
.
ch = 1\t 1;
ch
.
ch = 1\ ' ';


C# .
, .
:
" "

.
.
,
, .
,
\ \t.
//
// .
.using System;
class StrDemo {
static void Main()

82

I. C#
Console.W r i teLine(" \ \ ");
Console.WriteLine("OflHH\tflBa\tTpn");
Console .WriteLine ("\triHTb\ " ) ;
// .
Console.WriteLine("\"3?\",

.");

"?", .

,
\.
W r i t eL in e ()
\
( ),
. ,
.
,
. @,
.
. ,
, ,
.
("),
(" ").
.
// ,
using System;
class Verbatim {
,
static void Main() {
Console.WriteLine(@"
,
.

II );

1 2
5

C onsole.Write L i n e (@" :
3
4
6
7
8

) ;
Console.Wr i t e L i n e (@" :

"" #.

VI VV II

);

3. ,

83


,
.
-:
1
2
3
4
5
6
7
8
:

" #."

,
, .
,
,
. ,
.
, ,
.
, .
: . ,
1X 1, ch a r. ,
, "X", - .


:
_;

, ; _
. ,
. ,
. , b ool
. ,
. , i n t
ch ar.
C# .
, , ,
,
. #.
C# . ,
, ,
.


, ,
, . ,
.
(=) .
:

84

I. C#

_ = ;

, .
.
.
int count = 10;
// 10 count.
char ch = 'X';
// ch X.
float f = 1.2F
// f 1,2.

,
, , , .
int a, b = 8 ,

=19,

d; // b

b .



, C#
,
.
.
// .
using System;
class Dynlnit {
static void Main() {
// .
double si = 4.0;
double s2 = 5.0;
// hypot ,
double hypot = M a t h.Sqrt( (si * si) + (s2 * s2) );
Console.Write(" " +
si + " " + s2 + " ");
Console.Write L i n e ("{0:#.###}.",

hypot);

}
}
.
4 5 6.403

: si, s2 hypot.
(si s2) , (hypot)
.
, M a t h . Sqrt ().
, ,
. M a t h .Sqrt () (
) ,

3. ,

85

hypot.
, ,
,
, .


, C# .
, , i n t b o o l,
. C# 3.0,
, ,
. .
v a r
.
, .. ,
. .
var = 2.7183;


, double,
double. :
var = 2.7183F;

float.

.
, ,
.
// ,
using System;
class ImplicitlyTypedVar {
static void Main() {
// .
// double,
// double,
var si = 4.0;
var s2 = 5.0;
// , hypot
// double, ,
// Sqrt(), double,
var hypot = Math.Sqrt( (si * si) + (s2 * s2) );
Console.Write(" " +
si + " by " + s2 + " ");
Console.WriteLine("{0:#.###}.",

hypot);

// ,

86

I. C#
// si double
// .
// si = 12.2; // !

}
}
, .
, -
.
.
// si = 12.2;

// !

, s 1
double. , .
,
, . ,
. , , ,
s 1 .
C# ,
. ,
,
(LINQ),
19. ,
,
.
:
.
var si = 4 . 0 ,

s2=5.0;

// !

.
, s i s2, .


, ,
M a i n (). C#
. 2,
.
. , ,
, .
, ,
.
.
C# ,
. ( )
, .
,
.

3. ,

87

, ,
.
, , .
, ,
, . ,
,
. ,
.
. , ,
, , .
. ,
, ,
. :
, , .
,
.
// ,
using System;
class ScopeDemo {
static void Main() {
int x; // Main().
= 10;
if ( == 10) { //
int = 20; // .
// ,

Console. W riteLine( " : " + + " " + );


= * 2;

}
// = 100;

// !

/ / - .
Console.WriteLine(" " + ) ;

}
}
,
Main ( ) ,
. i f
.
,
. l i n e = 100 ;,
, .
( / / ) , ,
.
i f , ,

88

I. #

, ,
.
,
. ,
,
. , , ,
, .
,
, .
.
// .
using System;
class VarlnitDemo {
static void Main()
int x;

for(x = 0; x < 3; x++) {


int = -1; // .
Console.WriteLine(" : " + ); // -1
= 100;
Console.WriteLine(" :

" + );

}
}
}
.

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

,
-1 fo r. ,
100, .
C# :
, ,
,
.
,
.
/*

,
, .

3. ,
*** .

89

***

*/
using System;
class NestVar {
static void Main()
int count;

for(count = 0; count < 10; count = count+1) {


Console.WriteLine(" : " + count);
int count; // !!!
for(count = 0; count < 2; count++)
Console.WriteLine(" !");

}
}
}
C++,
, ,
, . ,
C++ count ,
fo r, , . C++
.
C# ,
, .



. ,
i n t float.
int i;
float f;
i = 10;
f = i; // float

,

, .
i flo a t,
f .
C# , ,
. , b o o l i n t .
, -
. , ,
. ,
.

90

I. C#


,
:
;
, .
, .
, int ,
byte, , , int byte,
, .
, , ,
. ,
, long
double .
// long double.
using System;
class LtoD {
static void Main()
long L;
double D;

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

}
}
long double ,
do ub le long ,
. ,
.
// *** .

***

using System;

/
class LtoD {
static void Main()
long L;
double D;

D = 100123285.0;
L = D; // !!!
Console.WriteLine("L D: " + L + " " + D) ;

}
}
,
d ec im al float double, char
bool. , char bool .

3. ,

91


,
,
.
.
.
. .
(_ )

_ ,
. .
double , ;

/ i n t ,
.
(int)

( / )

double,
/ i n t .
/ ,
i n t ,
. ,
double i n t .
,
. , long i n t
, long
in t,
.
, . ,
1,23 ,
(1), (0,23) .
,
. ,
.
// .
using System;
class CastDemo {
static void Main()
double x, y;
byte b;
int i;
char ch;
uint u;
short s;
long 1;
x = 10.0;

92

I. C#
= 3.0;
1 1 double int, ,
i = (int) ( / ) ;
Console.WriteLine(" / : " + i) ;
Console.WriteLine();

// int byte ,
i = 255;
b = (byte) i;
Console.WriteLine("b 255: " + b +
" -- .");
// int byte ,
i = 257;
b = (byte) i;
Console.W r i teLine("b 257: " + b +
" .");
Console.WriteLine();
// uint short ,
= 32000;
s = (short) ;
Console.WriteLine("s 32000: " +
s + " .");
// uint short ,
= 64000;
s = (short) ;
Console.WriteLine("s 64000: " +
s + " .");
Console.W r i teLine();
// long uint .
1 = 64000;
u = (uint) 1;
Console.WriteLine(" 64000: " + u +
" -- .");
// long uint .
1

12;

u = (uint) 1;
C onsole.WriteLine(" -12:
" .");
Console.W r i teLine();
// int char,
b = 88; // ASCII X
ch = (char) b;
Console.WriteLine("ch 88:

" + +

" + ch);

}
}
.
/ : 3
b 255: 255 -- .

3. ,
257:

93

. i

s 32000: 32000 -- ,
s 64000: -1536 -- .
- 64000: 64000 ,
-12: 4294967284 -- .
ch 88: X


. /
i n t , , .
b 255, ,
b y te.
b 257, ,
b y te .
, i n t
byte .
s s h o r t 32 000
u in t, ,
s h o r t.
64 000,
s h o r t, .
, u in t s h o r t .
64 000 1 lo n g .
, 64 000
u in t.
-12, ,
u in t.
, long u in t .
, ch a r b y te ,
, .


,
. ,
. ,
s h o r t long, .
,
.
C#
. ,
.
d e cim a l,
decim al ( float double,
).

94

I. C#
d o u b le,
double.
float,
float.
u lo n g ,
ulong ( sb y te , s h o rt, i n t long,
).
long,
long.
u in t, sb yte, s h o rt in t,
long.
u in t,
u in t.
i n t .


. -, . ,
flo a t double d e cim a l , , ,
u lo n g .
.
-, .
: ,
i n t . , ch a r, sb y te , b y te, u s h o rt
s h o rt i n t .
. ,
in t.
,
, . ,
b y te i n t ,
- b y te .
.
. ,
, byte,
. b y te in t.
, i n t . ,
, b y te , in t.
, .
.
// !
using System;
class PromDemo {
static void Main()
byte b;
b = 10;

3. ,

95

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

}
}
, b*b
, byte!
, b*b b i n t
b y te .
,
, , , .

. ,
ch ar, ch i ch 2 in t.
char chi = 'a', ch2 = 'b 1;
chi = (char)

(chi+ ch2);

c h i ch2
in t, ch ar.
,
. , i n t (byte,
sb y te , s h o r t u s h o rt), .. ,
in t. ch ar. ,
u in t,
long.


.

. ,
1 10
. ,
, M a t h . Sqrt (), int.
// .
using System;
class CastExpr {
static void Main()
double n;

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


Console.WriteLine(" {0}
n, M a t h .Sqrt(n));

{1}",

Console.W riteLine(" : {0}" ,


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

);

96

I. C#
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.44948974278318
: 2
: 0 .449489742783178
7 2.64575131106459
: 2
: 0 .645751311064591
8 2.82842712474619
: 2
: 0 .82842712474619
9 3
: 3
' : 0
10 3.16227766016838
: 3
: 0 .16227766016838

, , M a t h . Sqrt (),
int . ,
Math.Sqrt(n)

- (int) Math.Sqrt(n)

int ,
, . ,
double. int ,
M a t h .Sqrt ().

C# ,


. C#
: , ,
.
. , C#
_ ,
,
-.

, .


,
#, .

+
*

/
.

++

98

I. C#

+,
* / , .
.
,
. , ,
/ , ; ,
10/3 3.
(%),
. .
, 10 % 3 1. C# %
, . 1 0 . 0 % 3 . 0 1.
C# C++,
.
.
// %.
using System;
class ModDemo {
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;
Console.W r i teLine(" 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.


(++) ( ) 2.
, .
.
1,
1. ,
+ + ;

4.

99


= + 1;


;

= - 1;

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

:
++; //

:
++; //

( )
.
, .
,
.
,
.
.
= 10;
= ++;

11,
1,
.
X =

10;

= ++;

10,
, 1.
11. ,
11:
.

. ,
.
//
// (++).

100

I. C#

using System;
class PrePostDemo {
static void Main()
int* x, y;
int i;

x = 1;
= 0;
Console.WriteLine(" , " +
" = + ++;"),
for(i = 0; i < 10; i++) {
= + ++; // ++
Console.WriteLine( + " ");

}
Console.WriteLine();
= 1;
= 0;
Console.Write L i n e (" , " +
" = + ++;")<
for(i = 0; i < 10; i++) {
= + ++; // ++
Console.WriteLine( + " ");

}
Console.WriteLine();

.
,

= + ++

1
3

10
15
14
21

28
36
45
55
,
2
5
9
14
20

= + ++;

4.
27
35
44
54
65

101

,
= + ++;

,
.
1.
= + ++;

1,
,
. ,
++ ++
.
:
, :
+ ++


, .
,
1 .



, ,
"7' "".
,
.
.
.

==
I=
>
<
>=
<=



, .

102

I. #

&

&&
II
!


bool.
, ,
== ! =. <, >, <= >=
, .
, .
bool ,
(true) (false) . , -'
true > false C# .
bool,
bool.
&, |, ! , ,
.
p
false
true
false
true

p & q

q
false
false
true
true

false
false
false
true

p 1 q
false
true
true
true

p A q
false
true
true
false

!p
true
false
true
false

,
(true),
true.
,
.
//
// .
using System;
class RelLogOps {
static void Main()
int i, j;
bool bl, b2;

i = 10;

j = 11;
if(i < j) Console.W r i teLine("i < j");
if(i <= j) Console.WriteLine("i <= j");
if (i != j) Console.W r i teLine("i != j");

4.

103

if(i == j) Console.WriteLine(" ");


if(i >= j) Console.WriteLine(" ");
if(i > j) Console.WriteLine(" ");
= true7
2 = false;
i f ( & b2) Console.WriteLine(" ");
if(!(bl & b2)) Console.WriteLine("!( & 2) true");
i f ( | b2) Console.WriteLine(" | b2 - true");
if(bl A b2) Console.WriteLine("bl A b2 true");

}
}
.
i < j
i <= j
i != j
! (bl & b2) true
bl | b2 true
bl A b2 - true

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

p q

true
true
false
false

true
false
false
true

true
false
true
true


! |, .

I q


.
// #.
using System;
class Implication {
static void Main() {
bool p=false, q=false;

104

I. C#
int i, j;
for(i = 0 ; i
for (j = 0;
if (i= =0)
if (i= =1)
if (j = =0)
if (j == 1)

< 2;r i++) {


j < 2; j++)
P = true;
P = false;
q = true;
q = false;

Console.W r i teLine("p " + p + ", q " + q ) ;

i f ( !p I q)
Console.WriteLine(" " + p +
" " + q + " " + true);
Console.WriteLine ();

}
}
}
}
.
True, q True
True True True
True,

q False

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


C# , ,
, .
.
(f a ls e ),
.
(tru e ),
.
,
.
&&,
||.
& |.
,
.
.
: d
. n /d , d .

4.

1 05

,
.
// .
using System;'
class SCops {
static void Main()
int n, d;

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

}
}
- i f
: d. ,
,
. ,
d 2, .
, ,
, . ,
, .
, .
,
.
? ,
- .
.
// .
using System;
class SideEffects {
static void Main() {
int i;
bool someCondition = false;
i = 0;

106

I. C#
1 1 i ,
11 , if ,

if(someCondition & (++i < 100))


Console.WriteLine(" ");
Console.WriteLine(" if :

" + i); // 1

// i ,
// ,
if(someCondition && (+ + i < 100))
Console.WriteLine(" ");
Console.WriteLine(" if : " + i); // - 1 !!

}
}
, someCondition bool
false. if.
, i f
i , s o m e C o nd it io n
false. &,
i f,
. i f
. i
, ( someCondition) false,
, .
:
,
, #.
:
,
.


(=). C#
,
. .
_ =

_ .
,
: .
, , .
int , , z;
= = z = 100;

// 100 , z

100
, z .
z, , , .
" "
.

4.

107


C# ,
.
.
X = X + 10;
, .
X += 10;
+= ,
, 10.
.
= - 100;


X -= 100;
.
, 100.
, .. ,
, .
:
_ =

,
.

.
+=
%=

-=
&=

*
1=

/=
_

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


C# , ,
#.
() .
, b o o l, float
double.
1

108

I. C#

, ,
, .

, , ,
. C# . 4.1.

4.1.






1 ( )

&
1
>>
<<

, ,
, ,
: &, |, ~. , ,
. , .
.

&q

0
1
0
1

0
0
1
1

0
0
0
1

p lq
0
1
1
.1

p A q
0
1
1
0

~P
1
0
1


.
, - 0,
0. :

1101
1010 1010
&

________
1000 0010


& .
. , 9
: 0000 1001. ,
8, 0000 1000.
// , .
using System;

4.

class MakeEven {
static void Main()
ushort num;
ushort i;

for(i = 1; i <= 10; i++)


num = i;
Console.WriteLine("num:
num =

(ushort)

109

" + num);

(num & OxFFFE);

Console.WriteLine("num :
+ num + "\n");

"

}
}
}
.
num: 1
num :

num: 2
num : 2
num: 3
num :

num: 4
num :

num: 5
num :

num: 6
num :

num: 7
num :

num: 8
num :

num: 9
num :

num: 10
num :

10

OxFFFE,
, : 1111 1111 1111 1110. ,

num, , .

110

I. #

, 1
.

.
, .
// , ,
// .
using System;
class IsOdd {
static void Main()
ushort num;

num = 10;
i f ((num & 1) == 1)
Console.Write L i n e ("He .") ;
num = 11;
i f ((num & 1) == 1)
Console.WriteLine(num + " .");

}
}
.
11 .

i f
num 1.
num , ..
1, num & 1 1.
. i f
, .

& ,
b y te
. .
// ,

using System;
class ShowBits {
static void Main()
int t;
byte val;

val = 123;
f o r (t=128; t > 0; t = t/2)

4.

111

i f ((val & t) != 0) Console.Write("1 ");


i f ((val & t) == 0) Console.Write("0 ");

}
}
}
.
0 1 1 1 1 0 1 1

for
v a l , ,
. , 1, ,
0.

. 1 -
, 1 . :

1101
* 10101010
11111011
,
, ,
, .
// , .
using System;
class MakeOdd {
static void Main()
ushort num;
ushort i;

for(i = 1; i <= 10; i++)


num = i ;
Console.WriteLine("num:
num = (ushort)

" + num);

(num | 1);

Console.W riteLine("num :
num + "\n");

" +

}
}
}
.
num: 1
num :
num: 2

1 12

I. C#

num : 3
num:: 3
num : 3
num:: 4
num : 5
num:: 5
num : 5
num:: 6
num : 7
num:: 7
num : 7
num: 8
num : 9
num: 9
num : 9
n u m : 10
num : 11


num 1, 1
, .
1 ,
. ,
, .

,
, .

01111111
10111001

1100
,
. ,
X
Y, Y,
X. ,

R1 = X Y;
R2 = R1 Y;

R2 , X.
,

4.

113

, ,
.
,

.

, .
, ,
.

, .
// .
using System;
class Encode {
static void Main()
char chi = 'H';
char ch2 = 1i 1;
char ch3 = 1!1;
int key = 88;

Console.WriteLine(" :

" + chi + ch2 + ch3) ;

// ,
chi = (char) (chi key);
ch2 = (char) (ch2 key) ;
ch3 = (char) (ch3 key);
Console.WriteLine(" :

" + chi + ch2 + ch3);

// .
chi = (char) (chi key);
ch2 = (char) (ch2 key);
ch3 = (char) (ch3 key);
Console.WriteLine(" :

" + chi + ch2 + ch3);

}
}
.
: Hi!
: Q l y
: H i !

,
. (
, , ,
, .)
( 1)
. ,
1001 0110,
~ 0110 1001.

114

!. #


1 .
// .
using System;
class NotDemo {
static void Main()
sbyte b = -34;

for(int t=128; t > 0; t = t/2) {


i f ((b & t) != 0) Console.Write("1 ");
if ( (b & t) == 0) Console.W r i t e ("0 ");

}
Console.WriteLine ();
//
b = (sbyte) ~b;
for(int t=128; t > 0; t = t/2) {
i f ((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


C# ,
, . C#
.

>>

_
_

_ ,
.

, .
.
, .
, .
,
1. , ,

4.

115

1.
,
.
.
,
.
,
. ,
1. , .
.
. ,
1 , ,
128, .
// .
using System;
class ShiftDemo {
static void Main()
int val = 1;
for(int i = 0 ; i
for(int t=128;
i f ((val & t)
i f ((val & t)

< 8; i++) {
t > 0 ; t = t/2) {
!= 0) Console.Write("1 ");
== 0) Console.Write("0 ");

}
Console.WriteLine();
val = val < < 1 ; //

}
Console.WriteLine() ;
val = 128;
for(int i = 0 ; i <
for(int t=128; t
i f ((val & t)
i f ((val & t)

8; i++) {
> 0 ; t = t/2) {
!= 0) Console.Write("1 ");
== 0) Console.W r i t e ("0 ");

}
Console.WriteLine();
val = val > > 1 ; //

}
}
}
.
0
0
0
0
0
0
0
1

0
0
0
0
0
0
1
0

0
0
0
0
0
1
0
0

0
0
0
0
1
0
0
0

0
0
0
1
0
0
0
0

0
0
1
0
0
0
0
0

0
1
0
0
0
0
0
0

1
0
0
0
0
0
0
0

116

1
0
0
0

0
1
0
0

I. C#

0
0
1
0

0
0
0
1

0
0
0
0

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

2,

2. , ,
. , ,
.
.
// 2.
using System;
class MultDiv {
static void Main()
int n;

n = 10;
Console.Write L i n e (" n: " + n) ;
// 2.
n = n << l^Console .WriteLine (" n " +
" n = n * 2: " + n ) ;
// 4.
n = n << 2;
Console.Write L i n e (" n " +
" n = n * 4: " + n ) ;
// 2.
n = n >> 1;
Console.Write L i n e (" n " +
" n = n / 2: " + n ) ;
// 4.
n = n >> 2;
Console.Writ e L i n e (" n " +
" n = n / 4: " + n ) ;
Console.WriteLine ();
// n ,
n = 10;
Console.WriteLine(" n: " + n ) ;

4.

117

// 2 .
n = << 30; //
Console.WriteLine(" " +
" 30 : " + ) ;

}
}
.

: 10



n
n
n
n

=
=
=
=

*
*
/
/

2:
4:
2:
4:

20
80
40
10

: 10
30 :

-2147483648

.
10 , ,
in t.
''7' ,
, ,
, 1, ,
. ,
2
. ( . 3.)



. ,

127.
= 127;
= 127;

?
? #.

i f - t h e n - e l s e . ? ,
. .
1 ? 2

: 3 ;

1 bool, 2 3
.
?.
? .
!. , 2,
? . 1

118

I. C#

, 3,
?. , ab sv a l
v a l.
absval = val < 0 ? -val

: val;

// val

a b s v a l v a l,
. v a l ,
a b s v a l ,
.
?.
, .
// , ?.
using System;
class NoZeroDiv {
static void Main()
int result;

for(int i = -5; i < 6; i++) {


result = i != 0 ? 100 / i : 0;
if (i != 0)
Console.WriteLine("100 / " + i + " " + result);

}
}
}
.
100
100
100
100
100
100
100
100
100
100

/
/
/
/
/
/
/
/
/
/

-5 -20
-4 -25
-3 -33
-2 -50
-1 -100
1 100
2 50
3 33
4 25
5 20

.
result = i != 0 ? 100 / i : 0;

r e s u l t 100
i. ,
i . , r e s u l t
, .
?
. , , ?,
. ? bool,

4.

1 19

i f .
100 , .
// ,

using System;
class NoZeroDiv2 {
static void Main()

for(int i = -5; i < 6; i++)


if(i != 0 ? (i%2 == 0) : false)
Console.WriteLine("100 / " + i + " " + 100 / i);

}
}
i f .
i , i f .
i , i f ,
i , , .
.
,
.


C# ,
. ,
, , , .
=10/*(127+) ;
= 10 / * (127 + ) ;

I
, ,
, .
^
. ,
,
, . ,
?
= /3-34*temp+127;
= (/3) - (34*temp)

+ 127;


. 4.2 #:
. ,
.

4.2. C#

7]

[]

++

--

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

<

>

<=

op=

=>

I
&&
II
??

?:

>=

is

checked

new

++
() )

sizeof

typeof

un ch ecked


,
#.
:
, if switch,
,
for, while, do-while foreach,
: break, continue, goto, return throw.
throw,
C#
, 13,
.

i f
i f 2,
.
:
if ( ) ;
else ;

,
i f else. else
. ,
if else, .
i f,
.
if ( )

122

I. C#

else

}
,
i f . e l s e ,
. . ,
i f , bool.
, i f e l s e
, ,
.
// ,
.
using System;
class PosNeg {
static void Main()
int i;

for(i=-5; i <= 5; i++) {


Console.Write(" " + i + ": ");
if(i < 0) Console.WriteLine(" ");
else Console.W r i teLine(" ");

}
}
}
.

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

i ,
i f .
e l s e , .

i f
i f ,
i f e l s e . i f
. #,
, e l s e i f , ..

5.

1 23

i f , , e l s e ,
e l s e . .
if (i == ) {
if (j < 20) -a = b;
if(k > 100) = d;
else a = ; // else if(k > 100)

}
else a = d; // else if(i == 10)

,
e l s e i f ( j < 2 0 ) ,
, ,
i f e ls e . ,
e l s e i f ( i == 10 ). e l s e
i f (k > 1 00) ,
i f .

i f .
. ,
, , .
, ,
.
// ,
// , .
using System;
class PosNegZero {
static void Main()
int i;

for(i=-5; i <= 5; i++) {


Console.W r i t e (" " + i + ": ");
if(i < 0) Console.WriteLine(" ");
else if(i == 0) Console.WriteLine(" ");
else Console.Write L i n e (" ");

}
}
}
.

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

1 24

I. C#

i f - e l s e - i f
i f - e l s e i f , i f . .
i f ( )
;
else if ( )
;
else if ( )
;

else
;

.
, ,
.
,
else, ,
. e l s e ,
, .

if-else-if.
, .
//
// , .
using System;
class Ladder {
static void Main(), {
int num;
for(num = 2; num < 12; num++) {
i f ((num % 2) == 0)
Console.W r i teLine("
else i f ((num % 3) == 0)
C onsole.W r i teLine("
else i f ((num % 5) == 0)
C onsole.W r i teLine("
else i f ((num % 7) == 0)
Console.WriteLine("
else
Console.WriteLine(num + " 2, 3, 5

" + num + " 2.")


" + num + " 3.")
" + num + " 5.")
" + num + " 7.")
7.");

}
}
}
.
2 2
3 3

5.

125

4 2
5 5
6 2
7 7
8 2
9 3
10 2
11 2, 3, 5 7.

, else ,
.

s w itc h
C# switch,
. ,

.
i f ,
switch.
.
.
, ,
. switch.
switch () {
case 1:

break;
case 2:

break;
case :

break;

default:

break;

}
switch (char,
byte, short int), . (
string .)
, , switch .
, switch, .
, , .
sw i t c h
.

126

!. C#

default ,
. default
.
, .
, ,
, break.
,
switch.
// switch.
using System;
class SwitchDemo {
static void Main()
int i;

for(i=0; i<10; 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:
C o nsole.WriteLine ("i
break;
default:
Console.WriteLine("i
break;

");

");

");

");

");
(
");

}
}
}
.
i
i
i
i
i
i
i
i
i
i

.
.
.
.
.




, ,
, .

5.

127

i ,
, , default.
switch i
int. , switch
, char.
char switch.
// char switch.
using System;
class SwitchDemo2 {
static void Main()
char ch;

for(ch='A'; ch<= 'E'; ch++)


switch (ch) {
case 'A1:
Console.WriteLine("ch
break;
case ' ':
Console.WriteLine("ch
break;
case ' ':
Console.WriteLine("ch
break;
case 'D ' :
Console.WriteLine("ch
break;
case 'E ':
Console.Write L i n e ("ch
break;

A");

");

");

D");

E " ) ;

}
}
}
.
ch
ch
ch
ch
ch

d e f a u l t
switch. , default . ,
.
, case,
case , C#
""
. case
switch break. ( "",
goto,
, break.)

128

I. #

case break,
, switch,
,
switch. default
'''7, , , break.
"" #,
, C++ Java.
case (.. "") .
C# case . -,

case . ,
case . -,
case
, case .
""
case , case
,
.
// "" case.
using System;
class EmptyCasesCanFall
static void Main() {
int i;

for(i=l; i < 5; i++)


switch(i) {
case 1:
case 2:
case 3: Console.WriteLine("i 1, 2 3 );
break;
case 4: Console.WriteLine("i 4");
break;

.
i
i
i
i

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

i 1, 2 3,
, W r i t e L i n e ().
case "";
.
c a s e
, .
.

5.

1 29

s w itc h
switch
, switch. switch .
s witch
, . ,
.
switch(chi) {
case 'A': Console.WriteLine(" ^ " +
" switch.");
switch(ch2) {
case 'A':
Console.WriteLine(" A " +
" switch");
break;
case ' 1: // ...
} // switch
break;
case ' ': // ...

f o r
f o r 2,
. .
, fo r.
f o r
.
f o r {; ; )

:
f o r (; ;

{
;

}
; , ,
,
; ,
; , ,
, , .
, f o r
. f o r
, .
, ,
, fo r.
f o r ,
, .
;
100 -100 5.

130

I. C#

// for .
using System;
class DecrFor {
static void Main()
int x;

for(x = 100; x > -100; x -= 5)


Console.WriteLine(x);

}
}

for ,
. ,
, .
.
for(count=10;
x += count;

count < 5; count++)


//

,
count, , 5.
, count < 5 , ..
.
for
. for
2 20.
, .
// , .
// , .
using System;
class FindPrimes {
static void Main()
int num;
int i;
int factor;
bool isprime;

for(num = 2; num < 20; num++)


isprime = true;
factor = 0;

// , num .
for(i=2; i <= num/2; i++) {
i f ((num % i) == 0) {
// num .
// , ,
isprime = false;
factor = i;

5.

131

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

}
}
}
.
2
3

5

7



11

13



17

19

4 2
6 3
8 4
9 3
10
12
14
15
16
18

f o r
f o r #,
.
f o r .


f o r
.
. .
// for.
using System;
class Comma {
static void M a i n () {
int i, j;
for(i=0, j= 10; i < j; i++, j )
Console.WriteLine("i j: " +

i + " " + j);

132

I. C#

.
i
i
i
i
i

j:
j:
j:
j:
j:

0
1
2
3
4

10
9
8
7
6


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

for.
for
( 100).
.
.
// for
// .
using System;

>

class Comma {
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 ) {

i f ((smallest == 1) & ((num % i) == 0))


smallest = i;
if ( (largest == 1) & ((num % j) == 0))
largest = j;

}
Console.Write L i n e (" :
Console.WriteLine(" :

" + largest);
" + smallest);

}
}
.

5.

133

: 50
: 2


for. ,
i .
2 ,
num. j
.
n um ,
2. , ,
i j, .
.


, for,
, bool.
.
for done.
// bool.
using System;
class forDemo {
static void Main() {
int i, j;
bool done = false;
for(i=0, j=100; !done; i++, j ) {
if(i*i >= j) done = true;
Console.WriteLine("i, j: " + i + " " + j );

}
}
}
.
i,
i,
i,
i,

j
j
j
j

i*
if
if
if
if
if
ir

j
j
j
j
j
j
j

0 100
1 99
2 98
3 97
4 96
5 95
6 94
7 93
8 92
9 91
10 90

f o r ,
done (tru e ). done
, i
j .

134

I. C#


f o r ,
. C#
, fo r.
.
// for .
using System;
class Empty {
static void Main()
int i;

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


Console.WriteLine(" " + i ) ;
i++; //

}
}
}
fo r
, .. . i ,
, . , ,
, i 10,
. i
, ,
.

0
1
2
3
4
5
6
7
8
9

f o r
.
// for.
using System;
class Empty2 {
static void Main()
int i;

i = 0; //
f o r (; i < 10; ) {
Console.WriteLine(" " + i);

5.
i++;

135

//

}
}
}
i ,
for. ,
for.
,
, for.


f o r ,
, .. , .
, C#
.
for(;;)

// ,

{
//. . .
}
.
,
,
""
. ( "
b r e a k " .)


C# for ,

. . ,
1 5.
// ,
using system;
class Empty3 {
static void Main()
int i;
int sum = 0;

// 1 5
for(i = 1; i <= 5; sum += i++);
Console.WriteLine(" " + sum);

}
}
.
15

136

I. C#

,
for, .
.
sum += i++

.
, #, ,
. :
s u m
s u m i, i. ,
.
sum = sum + i;
i+ + ;

f o r
, fo r,
.
for.
, 1 5,
i, for, .
// for.
using System;
class ForVar {
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.Writ e L i n e (" " + sum);
Console.Writ e L i n e (" " + fact);

}
}
for, ,
for. ,
. ,
i for.
-
, for.
,
for.
.

5.

137

w h ile
C# w h ile .
:
while

( ) ;

,

. , .
, ,
.
, w hile
.
// ,
using System;
class WhileDemo {
static void Main()
int num;
int mag;

num = 435679;
mag = 0;
Console.WriteLine(": " + num);
while(num > 0) {
mag++;
num = num / 10;

};
Console.WriteLine(" :

" + mag);

}
}
.
: 435679
:

w hile .
num. , mag,
, , num
10. , num
. , ,
mag .
f o r , w h ile ,
. ,
,
. w h ile
, 2 0 9.

138

I. C#

// 2.
using System;
class Power {
static void Main()
int e;
int result;

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


result = 1;
e = i;

while (e > 0) {
result *= 2;

e ;
}
Console.WriteLine ("2 " + i + " " + result);

}
}
}
.
2
2
2
2
2
2
2
2
2
2

0
1
2
3
4
5
6
7
8
9

1
2
4
8
16
32
64
128
256
512

, w h ile ,
. ,
fo r , w hile .

d o - w h ile
C# d o -w h ile.
f o r n w h ile , ,
d o -w h ile .
, d o -w h ile .
d o-w h ile.
do {
;
( ) ;

} while


. ,

5.

1 39

d o-w hile while.


d o-w h ile , .
d o-w h ile
.
// .
using System;
class DoWhileDemo {
static void Main()
int num;
int nextdigit;

num = 198;
Console.WriteLine(":

" + num);

Console.Write(" :

");

do {
nextdigit = num % 10;
Console.Write(nextdigit);
num = num / 10;
} while(num > 0);
Console.WriteLine() ;

}
}
.
: 198
:

8 91

.

( num) 10. .
num 10. ,
. ,
num .

f o re a c h
f o re a c h
, . C#
, . f o re a c h
7, .

b re a k
b reak
, ,

14 0

I. C#

. b reak , ,
, .
.
// break .
using System;
class BreakDemo {
static void Main()

// break ,
for(int i=10; i <= 10; i++) {
if(i > 0) break; // ,
// i
Console .Write (i + " ") ;.

}
Console .-WriteLine (" !") ;

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

, f o r -10 10, ,
, b re a k , i
.
b reak , #.
,
d o -w h ile.
// break do-while.
using System;
class BreakDemo2 {
static void Main()
int i;

*
{

i = -10;
do {
if (i > 0) break;
Console.Write(i + " ") ;
i++ ;
} while (i <= 10);
Console.Write L i n e ("!");

}
}
break.
.
// .
using System;

5.
class FindSmallestFactor
static void Main() {
int factor = 1;
int num =-1000;

141

for (int i=2; i <= num/i;' i++) {


i f ((num%i) == 0) {
factor = in
break; // ,
//

}
}
Console.WriteLine(" " + factor);

}
}
.
2

b r e a k for,
. b r e a k

, , .
b r e a k ,
.
.
// break ,
using System;
class BreakNested {
static void Main()

for(int i=0; i<3; i++) {


Console.WriteLine(" : " + i) ;
Console.Write("
: ");
int t = 0;
while(t < 100) {
if(t == 10) break; // ,
Console.Write(t + " ");
t++;

t 10

}
Console.WriteLine ();

}
Console.WriteLine(" .");

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

142

1> C#

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

, b r e a k
, .
b r e a k . , break,
, break
. -,
break, switch,
, .

c o n tin u e
continue
.
continue ,
, . , continue
break.
c o nti n ue
0 100.
// continue,
using System;
class ContDemo {
static void Main()

// 0 100.
for (int i = 0; i <= 100; i++) {
if((i%2) != 0) continue; //
Console.WriteLine(i);

}
}
}
,

W r i t e L i n e ().
while do-while continue
,
. for ,
, .
continue , , ,
C# ,
. ,
, continue
.

5.

143

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

g o to
C# goto
. goto,
, . "
" , "
" . goto
.
goto . ,
, , ,
.
,
. goto
. goto
,
. goto , , ,
.
goto C#
. ,
goto, .
1 100
goto .
= 1;
loopl:
++;
i f ( < 100) goto loopl;

, g o t o
case default switch. case default
switch .
goto. goto
switch. ,
switch.
goto switch.
// goto switch.
using System;
class SwitchGoto {
static void Main()

for(int i=l; i < 5; i++)


switch(i) {
case 1:

{
'

144

I. C#
Console.W r i teLine("
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.W r i teLi ne();

}
// goto case 1; // ! switch .

}
}
.
case 1
case 3
default

case 2
case 1
case 3
default

case 3
default
default

, goto switch
case default.
, case break.
goto case ,
"" ,
, b r eak .
, goto
switch. ,
:
// goto case 1; // ! switch .

. ,
goto switch, ,
, ^
.
goto
.

5.

1 45

// goto.
using System;
class Use_goto {
static void Main() {
int i=0, j=0, k=0;
for(i=0; i < 10; i++) {
for(j=0; j < 10; j++ ) {
for(k=0; k < 10; k++) {
Console.WriteLine ("i, j, k: " + i + " " + j +
+ k),
if(k == 3) goto stop;

}
}
stop:
Console.WriteLine("! i, j, k: " + i +
", " + j + " " + k) ;

}
}
.
ir j/ k: 0 0
i , j/ k: 0 0
ir I , k: 0 0
ir i . k: 0 0
!

0
1
2
3
i, j, k: 0, 0 3

g o to ,
i f break,
. goto .
goto,
,
.
: ,
, .

,

.
#,
. ,
- ().
.

#,
.
.



. ,
,
.
,
.
.
,
. ,
. C#
,
. , ,
,
.
, .

, (
.

148

I. C#


, , ,
.
, .
, , ,
-. , C#
-. , ,
, ,
- , , , , ,
.
: .
.
.
class.
, .
class _ {
// .
1;
2;

//...
;

// .
_ 1 ()
1 1

}
_ 2 ()

//

}
//. .

_ ()

//

}
}
,
. , public,
. 2,
(private) , (public), ..
. .
, ,
.
. ,
, , Mai n (),
(public). ,
, .
8.

6. ,

149

,
. .
#,

. , , ... ,
, ,
, .
,
.
, .
, ,
: M ain ().
Main () .
, .


,
, , ,
, .. ( Building)
: ,
.
Building.
: Floors, 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,
.
:
_ ;

; , _ , . ,
, ,
. B u i l d i n g
public. ,
Building.
class .
Building.

150

I. C#

Building. , , , class
, . ,
Building .
Building,
.
Building house = new Buil d i n g (); // Building

h o u s e
Building, .. "" .
.
, , ,
,
. , B u i l d i n g
Floors, Ar e a Occupants.
, . - .
-.
.

, . ,
2 Floors ho use
.
house.Floors = 2;

, -
. ,
Building.
// ,

Building.

using System;
class Building {
public int Floors;
public int Area;
public int Occupants;

//
//
//

}
// Building,
class BuildingDemo {
static void Main() {
Building house = new Building(); // Building
int areaPP; //
// house,
h o u s e .Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// .
areaPP = house.Area / hou s e .Occupants;

6. ,

151

Console.WriteLine(" :\
" +
house.Floors + " \
" +
house.Occupants + " \
" +
house.Area +
" . , \
" +
+ " ");

}
}
: B u i l d i n g B u i l d i n g D e m o .
BuildingDemo house Bu i l d i n g
Main (), Main ()
house
. , B u i l d i n g B u i l d i n g D e m o
. ,
. , ,
, B u i l d i n g D e m o Building,
(public).
public,
Building, , BuildingDemo.
,
UseBuilding.cs. U s eBuilding.exe.
, Building BuildingDemo,
.
.
:
2
4
2500 . ,
625

Building BuildingDemo
. ,
B u i l d i n g .cs B u i l d i n g D e m o .cs, C# ,
. ,
,
.
csc Building.cs BuildingDemo.es

Visual Studio,
.
,
: ,
. ,
.
, ,
. , Building,
Floors, Area Occupants,
. .

152

I. #

// Building.
using System;
class Building {
public int Floors;
public int Area;
public int Occupants;

//
//
//

}
// Building,
class BuildingDemo {
static void Main() {
Building house = new Building();
Building office = new B u ildingO;
int areaPP;

//

// house,
h o u s e .Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office,
o ffice.Occupants = 25;
office.Area = 4200;
o ffice.Floors = 3;
// .
areaPP = house.Area / hou s e .Occupants;
Console.WriteLine(" :\n
" +
house.Floors + " \
" +
h o u s e .Occupants + " \
" +
house.Area +
" . , \
" +
areaPP + " "
// .
areaPP = office.Area / office.Occupants;
Console.Wr i t e L i n e (" :\n
" +
office.Floors + " \
" +
office.Occupants + " \
" +
office.Area +
" . , \
" +
areaPP + "

}
}
.
:
2
4
2500 . ,
625

6. ,

153

:
3
25
4200 . ^ ,
168

, house ,
office. . 6.1.

office

Floors

A rea

2500

O ccupants

Floors

A rea

4200

O ccupants

25

. 6.1.


B u i l d i n g
.
Building house = new B u i l d i n g ();

. -,
house, Building.
, , . -,
, , .
new. , h o use .
, house
Building.
new (.. )
, .
, C# .
, house
, , .
Building house; //
house = new Building(); // Building

h o u s e
Building. , house ,
, .
Building, house.
house .

154

!. #

, , ,
.
, .
, . ,

int ;
= 10;

10, i n t ,
.
Building house = new B u i lding();

house , .


,
, int.
, . ,
, ,
.
, ,
, ,
, , ,
. .

.
.
Building housel = new B u ilding();
Building house2 = housel;

, housel house2
, . housel h o u s e 2, ,
. housel
house 2, h ouse 2
, housel. ,
housel h o u s e 2. ,
housel.Area = 2600;

WriteLine ()
Console.WriteLine(housel.Area);
Console.WriteLine(house2.Area);

: 2600.
, housel h o u s e 2,
, . ,
,
house2.

6. ,
Building
Building
Building
house2 =

155

housel = new Building ();


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


house2 , h o u s e 3.
housel .

,
. Building,
, , . ,
, , .
, ,
, .
, .
.
C# .
, . ,
. , , ,
Main () ,
. , #.
,
#. , .
, GetVal,
: GetVal ().
.
:
_ (_)

//

}
, ,
. ,
. , (private)
, .
(public), .
_ , .
, .
, void.
, .
,
. , _ ,
.
, ,
. , .

156

I. C#

B u ild in g
, , ,
. ,
Main ()
.
,
.
Building, ,
. Area Occupants,
Building. ,
Building. ,
Building,
, Building,
. .
, Building , ,
- ,
, , Building.
Building,
.
Building, A r e a P e r P e r s o n (),
, .
// Building.
using System;
class Building {
public int Floors;
//
public int Area;
//
public int Occupants; //
// ,
public void AreaPerPerson() {
Console.WriteLine(" " + Area / Occupants +
" ");

}
}
// AreaPerPerson().
class BuildingDemo {
static void Main() {
Building house = new B u i lding();
Building office = new B u i lding();
// house,
h o u s e .Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office,
office.Occupants = 25;

6. ,

157

office.Area = 4200;
office.Floors = 3;
Console.WriteLine(" :\n
" +
house.Floors + " \
" +
h o u s e .Occupants + " \
" +
house.Area +
^
" . , ");
house.AreaPerPerson() ;
Console.WriteLine ();
Console.WriteLine(" :\n " +
off i c e .Floors + " \
" +
off i c e .Occupants + " \
" +
office.Area +
" . , ");
office.AreaPerPerson() ;

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

,
AreaPerPerson (). .
public void AreaPerPerson () {

, AreaPerPerson
. public, ,
. AreaPerPerson ()
void, .. .
, .
A reaPerPerson () .
Console.WriteLine(" " + Area / Occupants +
" ");

,
( Area)
( Occupants).
Building Are a Occupants,
AreaPerPerson () ,
.

158

!. #

Are son () .
, .
Main ().
h o u s e .AreaPerPerson();

A r e a P e r P e r s o n () house.
, A r e a P e r P e r s o n () ,
house, -.
A r e a P e r P e r s o n () , .
,
, .
h o u s e . A r e a P e r P e r s o n ()
, house. ,
office . A r e a P e r P e r s o n ()
, office. ,
AreaPerPerson () .
AreaPerPerson ()
: Area Occupants
, .. -.
, , ,
-. ,
.
. , .
. ,
Area Occupants Ar e a P e r P e r s o n ()
, A reaPerPerson ().

, O ccupants
() ( ,
). Occupants ,
- . 13,
, , C# ,
.

AreaPerPerson


, . -,
, ,
AreaPerPerson () . -,
return. return:
void, .. , , ,
. ,
, .
v o i d
return,
return;

6. ,

159

,
, .
.
public void M y M e t h O
int i;

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


if(i == 5) return; // 5
Console.WriteLine();

}
}
5 fo r,
5 i .
return,
. :
public void M y M e t h O

if(done)

//

...
return;

. . .

if (error)

return;

}
:
.
. -
.
, : v o id
:
return.


v o id ,
, .
.
3 M a t h .S q r t (),
.

. , M a t h . Sqrt (),
,
,
.
#.

return:
return ;

160

I. C#

,
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 int Floors;
//
public int Are-a;
//
public int Occupants; //
// ,
public int AreaPerPerson() {
return Area / Occupants;

}
}
// , AreaPerPerson().
class BuildingDemo {
static void Main() {
Building house = new Building();
Building office = new Building();
int areaPP; //

// house,
h o u s e .Occupants = 4;
house.Area = 2500;
house.Floors = 2;

// office,
office.Occupants = 25;
office.Area = 4200;
o ffice.Floors = 3 ;

// .
areaPP = h o u s e .AreaPerPerson();
Console.Writ e L i n e (" :\n
" +
house.Floors + " \
" +
h o u s e .Occupants + " \
" +
house.Area +
" . , \
" +
areaPP + " ");

6. ,

161

Console.WriteLine ();
// .
areaPP = office.AreaPerPerson();
Console'. WriteLine (" :\n " +
office.Floors + " \
" +
office.Occupants + " \
" +
office.Area +
" . , \
" +
areaPP + " ");

}
}
, .
' :
AreaPerPerson () ,
. ,
, AreaPerPerson (). ,

areaPP = house.AreaPerPerson ();

ar eaPP
( house).
, AreaPerPerson ()
int. ,
. , , ,
, ,
, . , double,
double.
, , ,
. ,
areaPP, AreaPerPerson () ,
W riteLine (), .
Console.WriteLine(" :\
" +
house.Floors + " \
" +
h o u s e .Occupants + " \
" +
house.Area +
" . , \
house.AreaPerPerson() +
" ");

" +

,
W r i t e L i n e (), h o u s e . A r e a P e r P e r s o n (),
WriteLine(). ,
AreaPerPerson () ,
Building. ,


.
i f ( .AreaPerPerson() > 2 .AreaPerPerson())
Console.WriteLine(" ");

162

!. C#


. ,
, . , ,
, .
. ,
. .
, ,
.
,
. C h k N u m Is Prime (),
true, , .
false. ,
I s P r i m e O bool.
// .
using System;
class ChkNum {
// true,
// ,
public bool IsPrime(int ) {
if ( <= 1) return false;.
for (int i=2; i <= x/i; i++)
if ( (x %i) == 0) return false;
return true;

}
}
class ParmDemo {
static void Main() {
ChkNum ob = new C h k N u m ();
for (int i=2; i < 10; i++)
i f(ob.IsPrime(i)) Console.WriteLine(i + " .");
else Console.WriteLine(i + " .");

}
}
.
2
3
4
5
6
7
8
9

.
.
.
.
.
.
.
.

IsPrime () ,
. .

6. ,

163

, Is Prime ().
. Is Prime () ,
2. , Is Prime () ,
2.
3, 4 .. , ,
Is Prime () ,
, .
, .
, .
ChkNum, L eastComFactor (),
.
, ,
.
// ,

using System;
class ChkNum {
// true,
// ,
public bool IsPrime(int ) {
i f ( <= 1) return false;
for (int i=2; i <= x/i; i++)
i f ((x %i) == 0) return false;
return true;

}
// ,
public int LeastComFactor(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; i++)
if(((a%i) == 0) && ( (b%i) == 0)) return i;
return 1;

}
}
class ParmDemo {
static void Main() {
ChkNum ob = new C h k N u m ();
int a, b;
for (int i=2; i < 10; i++)
if(ob.IsPrime(i)) Console.WriteLine(i + .");
else Console.WriteLine(i + " .");

1 64

I. C#
= 7;
b = 8;
Console.WriteLine(" " +
+ " " + b + " " +
o b .LeastComFactor(, ) );
= 100;
= 8;
Console.W r i teLine(" " +
+ " " + b + " " +
o b .LeastComFactor(, ) );
= 100;
= 75;
C onsole.Write L i n e (" " +
+ " " + b + " " +
o b .LeastComFactor(, ) );

: L e a s t C o m F a c t o r (),
.
.
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 ild in g
Building
, ,
.
MaxOccupant ().
// , ,
// ,
public int MaxOccupant(int minArea) {
return Area / minArea;

6. ,

1 65

M a x Occupant (), m i n Area


.
,
.
Building, M a x Occupant ().
/*
,
,
,
.

*/
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().
class BuildingDemo {
static void Main() {
Building house = new B u ilding();
Building office = new B u i lding();
// house,
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office,
office.Occupants = 25;
office.Area = 4200;
office.Floors = 3;
Console.WriteLine(" ,
" " +
300 + " . : " +
house.MaxOccupant(300));
Console.WriteLine(" " +

\" +

166

I. C#
" , \" +
" " +
300 + " . : " +
office.MaxOccupant(300));

}
}
.
,
300 . :
,
300 . :

8
14


,
.
C# . , ,
.
.
public void MyMeth()
char a, b;

//

...

if(a==b) {
Console.Wri t e L i n e ("") ;
return;
} else {
Console.W r i teLine(" ") ;
return;

}
Console.Wr i t e L i n e (" ");

}
M yMeth ()
, W r i t e L i n e O .
, .
, ,
.


B u i l d i n g , , ,
.
h o u s e .Occupants = 4;
house.Area = 2500;
house.Floors = 2;

6. ,

167

#.
, (
). , :
^
.
, , .
, .
.
_{_ )

//

}
^ ,
, ,
,
. ,
p u b lic , . _ ,
.
, ,
, C# ,

.
, b ool f a l s e , .
,
.
.
// .
using System;
class MyClass {
public int x;
public M y C l a s s () {
x = 10;

}
}
class ConsDemo {
static void Main() {
MyClass tl = new M y C l a s s ();
MyClass t2 = new M y C l a s s ();
Console.WriteLine(tl,x + " " + t2.x);

}
}
MyClass .

168

I. C#

public M y C l a s s O
X =
10;

}
, p u b lic .
, , .
MyClass
10. new . ,
:
MyClass tl = new M y C l a s s O ;

MyClass () t l ,
t l . 10. t2 .
t2 . 10. ,
.
10

10


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

}
}
class ParmConsDemo {
static void Main() {
MyClass tl = new M y C l a s s (10);
MyClass t2 = new M y C l a s s (88);
Console.WriteLine(tl.x + " " + t2.x);

}
}
.
10

88

MyClass () i,
.
:
MyClass tl = new M y C l a s s (10);

i , .

6. ,

169

B u ild in g
Building , ,
Floors, Are a O c cu p a n t s .
, Building.
// Building.
using System;
class Building {
public int Floors;
//
public int Area;
//
public int Occupants; //
// Building,
public Building(int f, int a, int o) {
Floors = f;
Area = a;
Occupants = o;

// ,
public int AreaPerPerson() {
return Area / Occupants;

}
// , ,
// .
^
public int MaxOccupant(int minArea) {
return Area / minArea;

}
}
// Building,
class BuildingDemo {
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) );

}
}
,
.

170

I. C#

, house office, Building ()


, .
,
Building house = new Build i n g (2, 2500,

4);

Building () 2, 2500 4
. , Floors, A r e a O c c u p a n t s
house 2, 2500 4 .

new
, ,
new, .
new :
new _

( _ )

_ , .
_ .
, new
, C# . , new
, .
, ,
new -
.
( 13).
, , ,
, ,
, , .

new
: new
, i n t float?
C# .
.
, new
. ,
,
.
, i n t ch a r,
, .
,
.
.
, new
, .
int i = new int ();

6. ,

171

int ,
i .
.
// new .
using System;
class newValue {
static void Main() {
int i = new int(); // i
Console.WriteLine(" i :

" + i) ;

}
}
.
i :

, i
. , new,
i .
, W r i t e L i n e ( ) ,
.
, new
, .
. ,
new .


, n ew

. , ,
.
new -
.

,
.
. , C++
delete. C# , : "
".
" " C#
, .
" " .
, ,
.
.

172

I. #

" "
. , ,
. ,
, " ".

C# ,
"
".
, . ,

, . , ,
, ,
, . , , .
#.
:
~_ () {
//

}
_ . ,
, ,
"" (~). ,
.
,
. ,
. ,
, .
, , ,
" ". , , , ,
,
. ( C# C++,
,
.) , ,
. , , "
", , .
,
. . -
" "
.
// .
using System;
class Destruct {
public int x;
public Destruct(int i)

6. ,

173

= i;

}
// .
-Destruct() -{
Console.WriteLine(" " + ) ;

}
// .
public void Generator(int i) {
Destruct = new Destruct (i);

}
}
class DestructDemo {
static void Main() {
int count;
Destruct ob = new Destruct(0);
/* .
- " ".
:
" ", ,
. */
for(count=l; count < 100000; count++)
o b .Generator(count);
Console.WriteLine("!");

}
}
.
.
. ,
. G enerator (),
Destruct. D estru c t D e m o
ob Destruct,
100 . . "
". ,
,
.. - ,
. , ..
, "!",
, for.
: W r i t e L i n e ()
-Destruct () .
, ,
.
,
,

174

I. C#

.
" ", II
#. " "
,
. , " "
" " ,
, .

t h i s
^ t h i s .
,
, .. , .
this. , t h i s
, .
this,
, Rect,
A r e a (),
.
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
static void
Rect rl =
Rect r2 =

{
Main() {
new R e c t (4, 5);
new R e c t (7, 9);

Console.W r i teLine(" r l : " + rl.AreaO);


Console.WriteLine(" r 2 : " + r2.Area());

}
}
,
.

return Width * Height;

6. ,

175

Area () , W i d t h Height,
, , .
.
return this.Width * this.Height;

this ,
Area (). , this .Width
Width , this . Height
Height . , Area ()
, this
. this
.
this .
, . ,
R e c t ()
Width = w;
Height = h;

.
this.Width = w;
this.Height = h;

, .
Rect,
this.
using System;
class Rect {
public int Width;
public int Height;
public Rect(int w, int h)
this.Width = w;
this.Height = h;

}
public int A r e a () {
return this.Width * this.Height;

}
}
class UseRect
static void
Rect rl =
Rect r2 =

{
Main() {
new R e c t (4, 5);
new R e c t (7, 9);

Console.WriteLine(" r l : " + r l . A reaO);


Console.WriteLine(" r 2 : " + r2.Area());

}
}

176

I. C#

t h i s
#, ,
.
t h i s . , C#
,
.
.
t h i s . ,
C# R e ct ().
public Rect(int Width, int Height)
this.Width = Width;
this.Height = Height;

}
R e c t ()
, , . "
" t h i s .


#.
s t r i n g ,
f o r e a ch.


.
C# ,
, .
,

. ,
,
,
.

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

178

I. C#

. ,

" ".


.
. ,

.
foro ,
, C# . -,
, . -,
, new. ,
:
[]

_ = new [] ;

.
, .
, . ,
. .

C++,
, #. ,
, .

.
i n t ,
, sample.
i n t [] sample = new i n t [10];

sample ,
new. ,
in t.
,
. :
i n t [] sample;
sample = new i n t [10];

sample -
, .
.
:
. C#
. , sample 10
0 9.

7.

179

. , sam ple
sample [ 0 ], sample [ 9 ].
, 10 sample.
// .
using System;
class ArrayDemo {
static void Main() {
i n t [] sample = new i n t [10];
4 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]:
sample[1]:
sample[2]:
sample[3]:
sample[4]:
sample[5]:
sample[6]:
sample[7]:
sample[8]:
sample[9]:

0
1
2
3
4
5
6
7
8
9

sample .
0

'cl

03

C/3

CN

03

C/3

Q,
C

03
/3

CO

JJ

03

C
/3

QJ

"cl

C
/3

i/

40

03

C
/3

03

/3

r
'E

cC
d
/3

00

os

Eh

03

C
/3

C
/3

,
. ,
,
nums,
fo r.
// .
using System;
class Average {
static void Main()

180

!. C#
i n t [] nums = new i n t [10];
int avg = 0;
nums[0]
n u m s [1]
n u m s [2]
n u m s [3]
n u m s [4]
n u m s [5]
n u m s [6]
n u m s [7]
n u m s [8]
n u m s [9]

=
=
=
=
=
=
=
=
=
=

99;
10;
100;
18;
78;
23;
63;
9;
87;
4 9;

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


avg = avg + n u m s [i ];
avg = avg / 10;
Console.WriteLine(": " + avg);

}
}
.
:

53



nums . ,
,
. , .
:
[] _ = { v a i l ,

va l2 ,

v a l3 ,

...,

valN) ;

v a i l - v a l N ,
, .
C# .
new .
,
.
// .
using System;
class Average {
static void Main() {
i n t [] nums = { 99, 10, 100, 18, 78, 23,
63, 9, 87, 49 };
int avg = 0;
for(int i=0;

i < 10; i++)

7.

181

avg = avg + n u m s [i ];
avg = avg / 1 0 ;
Console.WriteLine(":

" + avg);

}
}
,
new, . ,
, nums
.
int[] nums = new int[]

{ 99, 10, 100, 18, 78, 23,


63, 9, 87, 49 };

, new
, . :
i n t [] nums;
nums = new i n t [] { 99,
63,

10, 100, 18, 78, 23,


9, 87, 49 };

nums
.
:
, .
nums.
int[] nums = new int[10]

{ 99, 10, 100, 18, 78, 23,


63, 9, 87, 49 };

nums 10 .


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

182

I. C#

i 10,
IndexOutOfRangeException,
, . (
13.)


,
. ,
,
.


.
.
, ,
.
i n t e g e r
10x20.
int[,]

table = new i n t [10, 20];

. ,
.
[, ]
, .
new,
.
i n t [10, 20]

10x20,
.
,
. , table
(3,5) 10.
t a b l e [3, 5] = 10;

,
1 12,
.
// .
using System;
class TwoD {
static void Main()
int t, i;

7.
int[,]

table = new int[3,

183

4];

for(t=0; t < 3; ++t) {


for(i=0; i < 4; ++i) {
tablejt,i] = (t*4)+i+l;
Console.Write(table[t,i]

+ " ");

}
Console.WriteLine();

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

10

3^-----

11

12


table[l][2]
. 7.1. table,
TwoD

, C++ Java,
, #.

, C# .


C# .
.
[, . . ., ] _ = new [1, 2,

. . . ] ;

,
4><10.
int[,,] multidim = new i n t [4, 10, 3];

m ultidim
(2,4,1) 100.
multidim[2, 4, 1] = 100;

184

I. #

,
, 33><3,
.
// 3x3x3.
using System;
class ThreeDMatrix {
static void Main() {
int[,,] m = new int[3,
int sum = 0;
int n = 1;
for(int x=0; x <
for (int y=0;
for(int z=0;
m[x, y, z]
sum = m[0,

3, 3];

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

0, 0] + m [ l ,

1, 1] + m [ 2 ,

2, 2];

Console.WriteLine(" :

" + sum);

}
}
.
:

42



.
:
[ , ] _ = {
{ v a l , v a l , v a l , ..., v a l } ,
{ v a l , v a l , v a l , . . ., v a l } ,

{val,

val,

val,

. . ., v a l }

};
v a l ,
.
, .. ,
,
.
, sq rs
1 10 .
// ,
using System;

7.
class Squares {
static void Main()
int [,] sqrs
{ 1, 1 },
{ 2 , 4 Y,
{ '3, 9 },
{ 4, 16 }
{ 5, 25 }
{ 6, 36 }
{ 7 , 49 }
{ 8, 64 }
{ 9, 81 }
{ 10 , 100

185

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

}
}
}
.
1
2
3
4
5
6
7
8
9
10

1
4
9
16
25
36
49
64
81
100


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

[] _ = new [] [];

186

!. #

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

j agged ,
.
jagged [0][0]

jagged [0][1]

jagged [0] [2]

jagged [1][0]

jagged [1][1]

jagged [1][2]

jagged [2][0]

jagged [2][1]

jagged [2][2]

jagged [0] [3]

jagged [2][3]

jagged [2][4]

, !
,
. ,
j agged, (2,1),
10.
j a g g e d [2] [1] = 10;


.

.
// .
using System;
class Jagged {
static void Main() {
i n t [ ] [] jagged = new int[3][];
j a g g e d [0] = new i n t [4];
jag g e d [1] = new int[3];
j a g g e d [2] = new i n t [5];
int i;
// .
for(i=0; i < 4; i++)
j a g g e d [0][i] = i;
// .
for(i=0; i < 3; i++)
j a g g e d [1][i] = i;

7.

187

// .

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] + " ") ;
Console.WriteLine() ;

}
}
.
0 12
0 12
0 12

3
3 4

,
. , ,
, .. , ,
, .
:
, .
, .
int[] [,] jagged = new int [3] [, ];
j a g g e d [0 ]
4><2.
jagged[0] = new int [4, 2];
j agged [0 ] [1,0]
i.
jagged[0][1,0] = i;



, , , ,

188

I. C#

.
,
. .
// .
using System;
class AssignARef {
static void Main()
int i;

int[] numsl = new int [10];


i n t [] nums2 = new int [10];
for(i=0;

i < 10; i++) numsl[i]

= i;

for(i=0; i < 10; i++) nums2[i] = -i;


Console.W r i t e (" numsl:
for(i=0; i < 10; i++)
Console.Write(numsl[i] + " ");
Console.WriteLine() ;
Console.W r i t e (" nums2:
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ") ;
Console.WriteLine() ;
nums2 = numsl;

");

");

// nums2 numsl

Console.W r i t e (" nums2\n" + " :


for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ") ;
Console.WriteLine() ;
// numsl
// nums2.
nums2[3] = 99;
Console.W r i t e (" 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
n u m s 2 : 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

");

7.

18 9

, nums2 numsl
.

L e n g th
C# .
, Length,
, . ,
, .
, .
// Length .
using System;
class LengthDemo {
static void Main() {
i n t [] nums = new i n t [10];
Console.WriteLine(" nums " + n u m s .Length);
// Length nums.
for(int i=0; i < nums.Length; i++)
n u m s [i ] = i * i ;
// Length
// nums.
Console.W r i t e (" nums: ");
for(int i=0; i < nums.Length; i++)
Console.Write(nums[i ] + " ");
Console.WriteLine();

}
}
.
nums 10
nums: 0 1 4 9 16 25 36 49 64 81

, LengthDemo nums .Length


for .
,
. , , ,
Length ,
. Length ,
.
,
, , .
// Length .
using System;

190

I. C#

class LengthDemo3D {
static void Main() {
int[,,] nums = new i n t [10, 5, 6];
Console.W r i teLine(" nums " + n u m s .Length);

}
}

.
nums 300

, Length
, ( 300 (10><56)
). Length
.
Length
, , .
Length
,
.
// .
using System;
class RevCopy {
static void Main() {
int i ,j ;
i n t [] numsl = new i n t [10];
int[] nums2 = new i n t [10];
for(i=0;

i < n u m s l .Length;

i++) numsl[i]

= i;

Console.Write(" :
for(i=0; i < n u m s 2 .Length; i++)
Console.Write(numsl[i] + " ");

");

Console.W r i teLine();
// numsl nums2 ,
if(nums2.Length >= n u m s l .Length) // ,
// nums2
for(i=0, j=numsl.Length-1; i < n u m s l .Length; i++, j--)
nums2[j] = numsl[i];
Console.Write(" :
for(i=0; i < n u m s 2 .Length; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();

");

7.

1 91

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

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

L e n g th
Length
.
, .
,
() , .
// Length
// .
using System;
class Jagged {
static void Main() {
int[][] network_nodes = new int[4][];
network_nodes[0] = new
int[3];
network_nodes[1] = new
i n t [7];
network_nodes[2] = new
i n t [2];
network_nodes[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; i++)
for(j=0; j < network_nodes[i].Length;
Console.Write("
" " + j + ": ");
Console.Write(network_nodes[i][j] +
Console.WriteLine ();

}
Console.WriteLine();

" +

{
j++) {
" + i +
"% ");

192

!. #

.
: 4
0 0
0 1
0 2

1
1
1
1
1
1
1

0
1
2
3
4
5
6

70%
70%
70%
70%
71%
72%
73%
74%
75%
76%

2 0:: 70%
2 1:: 72%

3
3
3
3
3

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

70%
73%
76%
79%
82%

, Length
network_nodes. ,
. ,
network_nodes.Length

, network_nodes (
). ,
, .
n.etwork_nodes [0] .Length


3, C# 3.0
var. ,
,
. ,
. ,
. ,
,
LINQ, 19.
"" .
#.
var,
[ ]. ,

7.

193

,
.
.
.
var vals = n e w [] { 1, 2, 3, 4, 5 };

i n t, .
v a ls . ,
i n t , .
,
[ ]. ,
, . .
,
double.
var vals = n e w [,]

{ {1.1,

2.2},

{3.3,

4.4}, { 5.5,

6.6}

};

v a l s 2x3.
.
.
// .
using System;
class Jagged {
static void Main()

var jagged = n e w [] {
new [] { 1, 2, 3, 4 },
new[] { 9, 8, 7 },
n e w [] { 11, 12, 13, 14, 15 }

};
for(int j = 0 ; j < jagged.Length; j++) {
for(int i-0; i < jagg e d [j ].Length; i++)
Console.Write(jagged[j] [i] + " ") ;
Console.WriteLine();

}
}
.
12 3 4
9 8 7
11 12 13 14 15

j agged.
var jagged = n e w [] {
new [] { 1, 2, 3, 4 },
n e w [] { 9, 8, 7 },
new [] { 11, 12, 13, 14, 15 }

};

194

!. #

, new [ ] .
-, . -,
, .
,
. ,
,
.
,
LINQ- .
.

f o re a c h
5, C# f oreach,
. .
f o re a c h ,
. C#
, .
fo re a c h .
foreach

( __ in )

_ _
,
fo re a c h .
, . ,
. ,
v a r.
, .
, .
, , .
f o r e a c h . ,
.
,
. ,
. , fo re a c h
.
, , , fo re a c h
. , , ,
.
fo re a c h .

, , .
// foreach.
using System;
class ForeachDemo {
static void Main()

7.

195

int sum = 0;
int[] nums = new int [10];
// nums.
for(int i = 0; i < 10; i++)
n u m s [i ] = i ;
// foreach
// ,
foreach(int in nums) {
Console.WriteLine(" : " + ) ;
sum += ;

}
Console.WriteLine(" :

" + sum);

}
}
.










: 45

:
:
:
:
:
:
:
:
:
:

0
1
2
3
4
5
6
7
8
9

, f o re a c h
.
fo re a c h ,
, ,
break. ,
nums.
// break
foreach.
using System;
class ForeachDemo {
static void Main() {
int sum = 0;
i n t [] nums = new int [10];
// nums.
for(int i = 0; i < 10; i++)
n u m s [i ] = i ;
// foreach
// .

1 96

I. C#
foreach(int x in nums) {
Console.WriteLine(" : " + x ) ;
sum += x;
if(x == 4) break; // , 4

}
Console.WriteLine(" 5 :

" + sum);

}
}
.
:
:
:
:
:
5 :

1
2
3
4
10

, fo re a c h
.
fo re a c h
.
,
.
// foreach .
using System;
class ForeachDemo2 {
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++)
n u m s [i ,j ] = (i+l)*(j+l);
// foreach
// ,
foreach(int in nums) {
Console.WriteLine(" : " + ) ;
sum += ;

}
Console.Wr i t e L i n e (" :

" + sum);

}
}
.

:1
: 2
: 3
: 4

7.











: 90

:
:
:
:
:
:
:
:
:
:
:

197

5
2
4
6
8
10
3
6
9
12
15

fo re a c h
: , ,
, . .
, ,
. ,
fo re a ch .
, .
// foreach.
using System;
class Search {
static void Main() {
i n t [] nums = new int [10];
int val;
bool found = false;
// nums.
for (int i = 0; i < 10; i++)
n u m s [i ] = i ;
val = 5;
// foreach
// nums.
foreach(int in nums) {
if(x == v a l ) {
found = true;
break;

}
}
if(found)
Console.WriteLine(" !");

}
}
.
!

198

I. #

f o r e a c h ,
.
foreach ,
,
.. , foreach
.

string
#.
.
. C# . , string
. string C# ,
,
.
string ,
2, ,
.
. , :
Console.WriteLine(" C# .");

" C# . "
#. ,
string .
, .



. ,
str .
string str = " C# .";

s t r
" C# . 11.
string char. :
c h a r [] charray = {'t', '', 's', 't'};
string str = new string(charray);

s t r i n g , ,
, .
, string
WriteLine ().
// .
using System;

7.
class StringDemo {
static void Main()
char[]

199

charray = { ' ' ,

'1, 'o',

1 ',

'',

't ',

1p',

'o',

'',

'a',

11} ;
string strl = new string(charray);
string str2 = " .";
Console.WriteLine(strl);
Console.WriteLine(str2);

}
}
.
.
.


stri n g .
. 7.1. ,
S t r i n g C o m p a r i s o n .
, ,
. ( 12,
S t r i n g C o m p a r i s o n .)
,
. , ,
. .
, ,
. qpedbi.
( .)
, .
C o m p a r e ( ) , E q u a l s ( ) , I n d e x O f ()
Last IndexOf (),
,
, ,
.
.
,
(.. )
S t r i n g C o m p a r i s o n .C u r r e n t C u l t u r e .
,
S t r i n g C o m p a r i s o n .Ordinal,
: S t r i n g C o m p a r i s o n .C u r r e n t C u l t u r e l g n o r e C a s e
S t r i n g C o m p a r i s o n .Or d i n a l l g n o r e C a s e . ,
( 22).
, Compare () . 7.1 static.
static 8,
, : Co m pare ()

200

!. #

, . , Compare ()
:
= string.C o m p a r e (s t r l , s t r 2 ,

);

,
, 22,
.
ToUpper () ToLower (),
. ,
. 7.1, Culture Inf , ,
, .
, ,
(.. ).
Culturelnf .CurrentCulture. Culturelnf
System. Globalization. ,
,
,
C ulturelnf .CurrentCulture .
string Length, .

7.1.

static int Compare(string


s t r A , string s t r B ,
S tringComparison
com p a rison T yp e)

bool Equals(string
v a l u e , StringComparison
com p a rison T yp e)

int IndexOf(char v a l u e )

int IndexOf(string
v a l u e , StringComparison
com p a rison T yp e)

,
s t r A s t r B ;
, s t r A s t r B ; ,
.
c o m p a r i s o n T y p e
true,
,
v a l u e .
c o m p a r i s o n T y p e

,
v a l u e . .

-1,
.
,
v a l u e .
-1,
.
com p a rison T yp e

7.

201

. 7.1

int LastlndexOf(char

va lu e)

int LastlndexOf(string
v a l u e , StringComparison
com p a rison T yp e)


,
v a l u e .
.
-1,

,
v a l u e .
-1,
.
com parison T ype

string T o L o w e r ( C u l t u r e l n f o .
CurrentCulture c u l t u r e )
string T o U p p e r ( C u l t u r e l n f o .
CurrentCulture c u l t u r e )


.
c u l t u r e

. c u l t u r e

,
.
string str = "";
Console.WriteLine(str [0] ) ;

" " ,
"". , . , ,

,
. .
==. ,
== , ,
. string.
== ,
. ! =.
.
Equals (),
StringCompari so n .CurrentCulture. ,
Compare () ,
.
, Equals ()
.

.
// .
using System;
using System.Globalization;

202

I. C#

class StrOps {
static void Main() {
string strl = " .NET #.";
string str2 = " .NET #.";
string str3 = " C# .";
string strUp, strLow;
int result, idx;
Console.WriteLine("strl: " + strl);
Console.W r i teLine(" strl:

" + str l .Length);

// strl,
// .
strLow = s t r l .ToLower(Cirlturelnfo.CurrentCulture) ;
strUp = st r l .ToUpper (Culturelnfo.CurrentCulture);
Console.W r i teLine(" strl, " +
" :\n
Console.WriteLine(" strl, " +
" :\n

" + strLow);
" + strUp);

Console.W r i teLine();
// strl .
Console.WriteLine(" strl .") ;
for (int i=0; i < strl.Length; i++)
Console.Write(strl[i]);
Console.WriteLine("\n");
// ,
if (strl == str2)
Console.Writ e L i n e ("strl == str2");
else
Console.WriteLine("strl != str2");
if (strl == str3)
Console.WriteLine("strl == str3");
else
Console.Writ e L i n e ("strl != str3");
// .
result = string.Compare(str3, strl, StringComparison.CurrentCulture) ;
if(result == 0)
Console.WriteLine(" strl str3 ");
else if (result < 0)
Console.WriteLine(" strl- str3");
else
Console.WriteLine(" strl str3");
Console.Write L i n e ();
// s t r 2 .
str2 = " ";
// .
idx = str 2 .IndexOf("", StringComparison.Ordinal);
Console.Write L i n e (" <0>:

" + idx)

7.
idx = str2.LastlndexOf("", StringComparison.Ordinal);
Console.WriteLine(" <0>:
idx) ;

203

" +

}
}
.
strl: .NET #.
strl: 41
strl, :
.net #.
strl, :
.net #.
strl .
.NET #.
strl == str2
strl != str3
strl str3
<0>:
<0>: 13

, , Compare ()
.
result = string.Compare(strl, str3, StringComparison.CurrentCulture);

, Compare () static,
, .
+ (.. ) .
, :
string
string
string
string

strl
str2
str3
str4

=
=
=
=

"";
"";
"";
strl + str2 + str3;

str4 "".
: s t r i n g
System. String, .NET Framework,
.. . ,
, stri n g ,
System. String, .
S y s t e m .String II .


,
. .
// .
using System;

204

I. C#

class StringArrays {
static void Main() {
s t r i n g [] str = { "",

"",

"",

Console.WriteLine(" :
for (int i=0; i < str.Length; i++)
Console.Write(str[i] + " ");
Console.WriteLine("\n");

"."

};

");

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

");

}
}
.
:
.
:
!

.
. , 19 " ".
// ,
using System;
class ConvertDigitsToWords
static void Main() {
int num;
int nextdigit;
int numdigits;
int[] n = new i n t [20];

s t r i n g [] digits = { "", "", "",


"", "", "",
"", "", "",
"" };
num = 1 9 0 8 ;
Console.WriteLine(":

" + num);

Console.Write(" :

");

nextdigit = 0;
numdigits = 0;
// .

7.

205

// ,
do {
nextdigit = num % 10;
n[numdigits] = nextdigit;
numdigits++;
num = num / 1 0 ;
} while(num > 0);
numdigits--;
// .
f o r ( ; numdigits >= 0; numdigits--)
Console.Write(digits[n[numdigits]] + " ");
Console.WriteLine() ;

}
}
.
: 1908
:

d i g i t s
0 9.
. ,
int.
.
, ,
.


, s tri n g .
, .
.
, ,
. ,
, ,
.
"'7, .
, , , (..
string) , , .
string .
, ,
: Substring ().
, .
, ,
, , .
Substring ():
string Substring(int _ ,

int )

_ ,
.

206

I. C#

,
S ubstring().
// Substring().
using System;
class SubStr {
static void Main() {
string orgstr = " C# .";
//
string substr = o rgstr.Substring(5, 20);
Console.Writ e L i n e ("orgstr: " + orgstr);
Console.W r i teLine("substr: " + substr);

}
}
.
orgstr: C# ,
substr:

, o r g s t r ,
substr.
: ,
, #,
. #
S t r i n g B u i l d e r , S y s t e m . T e x t .
, . , ,
C# string, StringBuilder.

s w it c h
s t r i n g switch.
,
switch.
,
. ,
, "", "" "".
// switch .
using System;
class StringSwitch {
static void Main() {
str i n g [] strs = { "",
foreach(string s in strs)
switch (s) {
case "":
Console.Write (1);

"",
{

"",

"",

""

};

7.
break;
case "":
Console.Write (2);
break;
case "":
Console.Write (3);
break;

}
}
Console.WriteLine ();

}
}
.
12321

207



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



. -,
.
, 6. -,

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

-
,
.

2 10

I. C#

,
, , ,
.
.
, . ,
" ", ,
.


C#
: public, private, p r o t e c t e d internal.
public private. protected
, ,
11. internal ,
C# ,
16.
public,
, ,
. private,
. ,
(private) .
6, ,
.
private .

. ,
. .
public string errMsg;
private double bal;
private bool isError(byte status)

{ // ...

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

// ,
// .
//

// , alpha beta .
// .
public void SetAlpha(int )
alpha = ;

8.
public int GetAlphaO
return alpha;

211

}
public void-SetBeta(int a)
beta = a;

}
public int GetBeta()
return beta;

}
}
class AccessDemo {
static void Main() {
MyClass ob = new M y C l a s s O ;
// alpha beta
// ,
o b .SetAlpha(-99) ;
ob.SetBeta(19) ;
Console.WriteLine(" o b .alpha " + o b .GetA l p h a ());
Console.WriteLine("ob.beta " + o b .G e t B e t a ());
// alpha beta
// .
// ob.alpha = 1 0 ; // ! alpha - !
// ob.beta = 9 ;
// ! beta - !
// gamma ,
// ,
o b .gamma = 99;

}
}
, MyClass alpha private, beta
p r i v a t e , g a m m a public. ,
alpha beta
, . ,
AccessDemo.
(public) , SetAlpha () GetAlpha (). ,
:
// ob.alpha = 1 0 ;

// ! alpha - !

-
. , a l p h a
MyClass, ,
MyClass, S e t A l p h a ()
GetAlpha (). beta.
:
,
.

21 2

I. C#


.
, ,
.
, , .
, ,
,
.
,
, ..
, , .
, , ,
.
, .
, ,
.
,
, .
, ,
,
. , ,
, .



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

, .
:
. ,
. ,
: ,
.

8.

213

Stack,
.
.
Stack. ,
" ".
, S t a c k ,
.
// .
using System;
class Stack {
// ,
c h a r [] 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]
tos++;

= ch;

}
// ,
public char P o p () {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;

}
tos ;
return stck[tos];

}
// true, ,
public bool IsFullO {
return tos==stck.Length;

}
// true, ,
public bool IsEmptyO {
return tos==0;

214

I. C#

// ,
public int C a pacity() {
return stck.Length;

}
// ,
public int GetNum() {
return tos;

}
}
S ta c k .
.
// ,
c h a r [] stck; // ,
int tos;
//

s t c k (
). ,
. S tack . to s
.
, t o s n s t c k , ,
" ".
s t c k , . ,
t o s ,
, to s ,
S tack , , .
s t c k n t o s S tack
, .
S tack .
// Stack ,
public Stack(int size) {
stck = new char[size]; //
tos = 0;

}
.
to s .
, to s , .
Push () ,
.
// ,
public void Push(char ch) {
if (tos==stck.Length) {
Console.W r i teLine(" - .");
return;

}
stck[tos]
tos++;

= ch;

8.

215

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

}
tos ;
return stck[tos];

}
tos.
, , . tos
, .
Push () Pop (),
. S ta c k
: I s F u l l ( ) , IsEm pty (), C a p a c ity () GetNum ().
.
// true,
public bool IsFull() {
return tos==stck.Length;

}
// true,
public bool IsEmpty() {
return tos==0;

}
// ,
public int Capacity() {
return stck.Length;

}
// ,
public int G e t N u m () {
return tos;

}
I s F u l l () tr u e , ,
f a l s e . IsEm pty ()
tru e , , f a l s e .
(.. , )

2 16

I. C#

Capacity (), ,
, Get N u m (). ,
, ,
tos. ,
.
S t a c k
.
// Stack,
using System;
// ,
class Stack {
// ,
c h a r [] stck; // ,
int tos;
//
// Stack ,
public Stack(int size) {
stck = new char[size]; //
tos = 0;

}
// ,
public void Push(char ch) {
if(tos==stck.Length) {
Co nsole.WriteLine (" - .");
return;

}
stck[tos]
tos++;

= ch;

}
// ,
public char P o p () {
i f (tos==0) {
Console.WriteLine(" - .");
return (char) 0;

}
tos ;
return stck[tos];

}
// true,
public bool Is F u l l O {
return tos==stck.Length;

}
// true,
public bool IsEmptyO {

- ,

8.
return tos==0;

}
// ,
public int C a pacity() {
return stck.Length;

}
// ,
public int GetNum() {
return tos;

class StackDemo {
static void Main()
Stack stkl = new
Stack stk2 = new
Stack stk3 = new
char ch;
int i;

{
Stack (10);
Stack(lO);
S t a c k (10);

// stkl.
Console.WriteLine(" -J stkl.");
for(i=0; !stkl.I s F u l l (); i++)
stkl.P u s h ((char) ('A1 + i));
i f (stkl.IsFull()) C o nsole.WriteLine(" stkl .");
// stkl.
Console.Write(" stkl:
w h i l e ( !stkl.IsEmpty() ) {
ch = stkl.P o p ();
Console.Write(ch);

");

}
Console.WriteLine();
if(stkl.IsEmpty()) Console.WriteLine(" stkl .\");
// stkl.
Console.WriteLine(" -J stkl.");
for(i=0; !stkl.I s F u l l (); i++)
stkl.P u s h ((char) ('A' + i));
// stkl s t k 2 .
// stk2 .
Console.WriteLine(" stkl\n" +
" stk2.");
w h i l e ( !stkl.IsEmpty() ) {
ch = stkl.P o p ();
stk2.Push(ch);

218

I. #
Console.Write(" stk2: ");
w h i l e ( !stk 2 .IsEmpty() ) {
ch = s t k 2 .P o p ();
Console.Write(ch);

}
Console.Write L i n e ("\n");
// 5 .
Console.WriteLine(" 5 stk3.");
for(i=0; i < 5; i++)
st k 3 .P u s h ((char) ('A1 + i)) ;
Console.WriteLine(" stk3: " + stk 3 .Capacity());
Console.WriteLine(" stk3: " +
s t k 3 .G e t N u m ());

}
}
.
-J stkl.
stkl .
s t k l : JIHGFEDCBA
stkl .
-J s t k l .
stkl
stk 2 .
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 ;

8.

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

}
// ob.
public void Copy(MyClass ob)
alpha = ob.alpha;
beta = ob.beta;

}
public void Show() {
Console.WriteLine("alpha: {0}, beta:
alpha, beta);

{1}",

}
}
class PassOb {
static void Main() {
MyClass obi = new M y C l a s s (4, 5);
MyClass ob2 = new MyClass (6, 7);
Console.Write("obi: ");
o b i .Show ();
Console.W r i t e ("ob2: ");
o b 2 .S h o w ();
if(obi.SameAs(ob2))
Console.WriteLine("obi ob2 .");
else
Console.WriteLine("obi ob2 .");
Console.WriteLine() ;
// obi o b 2 .
o b i .Copy(ob2);
Console.Write("obi :
o b i .S h o w ();

");

if(obi.SameAs(ob2) )
Console.WriteLine("obi ob2 .");
else
Console.WriteLine("obi ob2 .");

}
}
.
obi: alpha:
o b 2 : alpha:

4, beta:
6, beta:

5
7

219

220

I. C#
ob2 .

: alpha: 6, beta:
obi 2 .

Same As () ()
M yClass . Same As ()
alpha beta
, ob.
true ,
. ()
alpha beta ,
ob, alpha beta .
,
, .


,
.
.
, .
.
.
. , ,
, ,
. .
, .
,
. , , ,
, .
C# , ,
. ,
, int double, ,
, ,
. .
// ,
using System;
class Test {
/*
, . */
public void NoChange(int i, int j) {
i = i + j;
j = -j;

}
}
class CallByValue

8.

221

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

" +

}
}
.
b : 15 2 0
b : 15 2 0

, , N o C h a n g e (),
, .
, i j
, b i j . ,
i
.
.
- . ,
, , ,
. (, ,
, .)
, ,
, , ,
. .
,
.
, . ,
, ,
, . ,
, .
.
// .
using System;
class Test {
public int a, b;
public Test(int i, int j)
a = i;
b = j;

222

I. C#

/* . ob.a ob.b ,
, . */
public void Change(Test ob) {
ob.a = o b .a + o b .b ;
ob.b = -ob.b;

}
}
class CallByRef {
static void Main() {
Test ob = new T e s t (15, 20);
Console.WriteLine("o b . ob.b :
ob.a + " " + ob.b);

" +

o b .Change(ob);
Console.WriteLine("o b . ob.b :
ob.a + " " + ob.b);

" +

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

, C h a n g e ()
, .
, . ,
, , .
- ,
. , .

r e f o u t
, , int char,
. , , ,
, ,
. , ref out
.
, .
ref out,
,
. , :
.
.
, ,
. Swap ( ),
.

8.

223

, , C#
, ,
, int.
ref.
,
return.
. ,
, ,
? , out.

r e f
ref ,
. ,
. .
Sqr (),
.
ref.
// ref .
using System;
class RefTest {
// .
// ref.
public void Sqr(ref int i) {
i = i * i;

}
}
class RefDemo {
static void Main() {
RefTest ob = new R e f T e s t ();
int a = 10;
Console.WriteLine(" :

" + a);

ob.Sqr(ref a); // ref


Console.WriteLine(" :

" + );

}
}
, ref
.
, ,
Sqr ().
: 10
: 100

224

I. C#

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

}
}
class ValueSwapDemo {
static void Main() {
ValueSwap ob = new ValueSwap();
int x = 1 0 ,

= 20;

Console.WriteLine("x :

" + + " " + );

ob.Swap (ref , ref );


Console.Writ e L i n e (" :

" + + " " + );

}
}
.
: 10 20
: 20 10

ref . ,
,
. , ,
, ,
. , ref
.

o u t

, . , ,
, ,
.
,
. ,

8.

225

ref
. , ref,

. , C#
out.
out ref,
: .
, out, ( )
- . , out
, .. , .
,
. , out
.
out.

GetParts () Decompose. ,
.
// out.
using System;
class Decompose {
/*
. */
public int GetParts(double n, out double frac) {
int whole;
whole = (int) n;
frac = n - whole;
return whole;

// frac
//

}
}
class UseOut {
static void Main() {
Decompose ob = new Decompose();
int i;
double f;
i = ob.GetParts(10.125, out f ) ;
Console.WriteLine(" " + i);
Console.WriteLine(" " + f);

}
}
.
10
0.125

226

I. C#

Get Parts () . -,

return. -,
f out. ,
out, .
, out
.
. out.
HasComFactor () . -,
( 1) ,
true, , false.
-,. out
, .
// out.
using System;
class Num {
/* , v
. , *
out. */
public bool HasComFactor(int x, int y,
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++) {
i f ( ((y%i)==0) & ((x%i)==0) ) {
if (first) {
least = i;
first = false;

}
greatest = i;

}
}
if(least != 1) return true;
else return false;

}
}
<

class DemoOut {
static void Main() {
Num ob = new N u m ();
int lcf, gcf;
i f(ob.HasComFactor(231,

105, out lcf, out gcf))

8.

227

Console.WriteLine(" " +
" 231 105 " + lcf) ;
Console.W r i teLine(" " +
" 231 105 " + gcf);

}
else
Console.W r i teLine(" 35 49 .");
if(ob.HasComFactor(35, 51, out lcf, out gcf)) {
Console.WriteLine(" " +
" 35 51 " + lcf);
Console.WriteLine(" " +
" 35 51 " + gcf);

}
else
Console.W r i teLine(" 35 51 .");

}
}
, lcf gcf
M a i n () H a s C o m F a c t o r ().
HasComFactor () ref, out, .
true false, ,
. ,
out .
.
231 105 3
231 105 21
35 51 .

r e f o u t
ref out
. .
ref out , .
, .
, ref
, .
// .
using System;
class RefSwap {
int a, b;
public RefSwap(int i, int j)
a = i;
b = j;

228

I. C#

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 {
static void Main() {
RefSwap x = new R e f S w a p (1, 2);
RefSwap = new R e f S w a p (3, 4);
Console.W r i t e ("x :
x .Show ();

") ;

Console.Write(" :
. S h o w ();

");

Console.WriteLine() ;
// , .
.Swap (ref , ref );
Console.W r i t e (" :
.S h o w ();

");

Console.Write(" :
.Show ();

") ;

}
}
.
:
:

: 1, : 2
: 3, : 4

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

Swap () ,
. Swap () ,
1 2, ,
3 4. Swap () ,
3 4, ,
1 2. ref, Swap ()
. ,
ref Swap ( ) .

8.

229


,
, . ,
. ,
, .
, , .
.
, .
, .
params.
,
, params.
, .
.
, p a r a m s
M i n V a l (),
.
// params.*
using System;
class Min {
public int MinVal(params i n t [] nums)
int m;

if(nums.Length = = 0 ) {
Console.WriteLine(": .");
return 0;

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

}
}
class ParamsDemo {
static void Main() {
Min ob = new M i n ();
int min;
int a = 10, b = 20;
// ,
min = ob.MinVal(a, b ) ;
Console.WriteLine(" " + m i n ) ;
// ,
min = ob.MinVal(a, b, -1);

230

I. C#
Console.Write L i n e (" " + min ) ;
/ / ,
min = ob.MinVal(18, 23, 3, 14, 25);
Console.WriteLine(" " + min);

// ,
i n t [] args = { 45, 67, 34, 9, 112, 8 };
min = ob.MinVal(args);
Console.WriteLine(" " + min);

}
.

10
-1
3
8

, M i n V a l (),
nums. .
Mi n V a l ()
.
MinVal ().
, .
. params,
, .
p a r a m s
, , .
, MinVal ()
min = ob.MinVal(l,

2.2);

// !

, double
( 2.2) int, nums MinVal ().
p a r a m s ,
, params
! , MinVal ()
#.
min = ob.MinVal(); //
min = o b .M i n V a l (3); // 1

Min V a l ()
nums ,
. , MinVal ()
. (
13.) , MinVal ()
, .
.
,
. , ShowArgs ()

8.

231

s t r i n g ,
params.
//
// params.
using System;
class MyClass {
public void ShowArgs(string msg, params i n t [] nums)
Console.Write(msg + ": ");

foreach(int i in nums)
Console.Write (i + " ") ;
Console.WriteLine ();

}
}
class ParamsDemo2 {
static void Main() {
MyClass ob = new MyClass ();
o b .ShowArgs(" ",
1, 2, 3, 4, 5);
o b .ShowArgs(" ",
17, 20);

}
}
.
: 1, 2, 3, 4, 5
: 17, 20

, ,
param s,
. params .


, .
R e ct, E n la rg e (),
,
, .
// .
using System;
class Rect {
int width;
int height;

232

I. C#

public Rect(int w, int h)


width = w;
height = h;

}
public int Area() {
return width * height;

}
public void Show() {
Console.WriteLine(width + " " + height);

}
/* ,

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

}
}
class RetObj {
static void Main() {
Rect rl = new R e c t (4, 5);
Console.W r i t e (" rl: ");
r l .Show ();
Console.WriteLine(" r l : " + rl.AreaO);
Console.WriteLine();
// r l .
Rect r2 = r l .E n l a r g e (2);
Console.W r i t e (" 2 : ");
r 2 .S h o w ();
Console.WriteLine(" 2 : " + 2.());

}
}
.
r l : 4 5
r l : 20
2: 8 10
2 : 80

, ,
. "".
, ,
.

8.

233


, ,
.

, .
.
.
// .
using System;
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 ) ;

}
}
class MakeObjects {
static void Main() {
MyClass ob = new MyClass ();
int i, j;
// , .
for(i=0, j=10; i < 10; i++, j ) {
MyClass anotherOb = o b .Factory(i, j); //
anotherOb.S h o w ();

}
Console.WriteLine ();

}
}
.

:
:
:
:
:
:
:

0
1
2
3
4
5
6

10
9
8
7
6
5
4

234

I. C#

b: 7 3
b: 8 2
b: 9 1

.
l a s s , ,
. , b
. Fac t or y () ,
. , b
,
Factory ().
Main () MyClass,
for .
, .
MyClass anotherOb = o b .Factory(i,

j); //


anotherOb, ,
. anotherOb

, , , .


C# , ,
. ( C# C++,
.) ,
FindFactors () ,
.
// ,
using System;
class Factor {
*
/* facts, num.
numfactors out
. */
public i n t [] FindFactors(int num, out int numfactors) {
i n t [] facts = new int[80]; // 80
int i, j;
// facts.
for(i=2, j=0; i < num/2 + 1; i++)
i f ( (num%i)==0 ) {
facts[j] = i;
j++;

}
numfactors = j ;
return facts;

8.

235

class FindFactors {
static void Main() {
Factor f = new F a c t o r ();
int numfactors;
inti] 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

Factor FindFactors () .
public int[] FindFactors(int num, out int numfactors)

, int.
. , ,
, . ,
someMeth (),
double.
public doublet,]

s o meMeth() { // ...


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

236

I. C#

, .
// .

using System;
class Overload {
public void OvlDemo() {
Console.Writ e L i n e (" ");

}
// OvlDemo ,
public void OvlDemo(int a) {
Console.Writ e L i n e (" : " + a);

}
// OvlDemo ,
public int OvlDemo(int a, int b) {
Console.WriteLine(" : " + a + " " + b ) ;
return a + b;

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

}
class OverloadDemo {
static void Main() {
Overload ob = new Overload();
int resl;
double resD;
// O v l D e m o ().
o b .O v l D e m o ();
Console.Writ e L i n e ();
o b .O v l D e m o (2);
Console.WriteLine ();
resl = ob.OvlDemo(4, 6);
Console.WriteLine(" o b .Ovl D e m o (4, 6): " + resl
Console.WriteLine ();
resD = o b .O v l D e m o (1.1, 2.32);
C o nsole.Write L i n e (" o b .O v l D e m o (1.1, 2.32):
resD);

}
}
.

" +

8.

237


: 2
: "4 6
o b .OvlDemo(4, 6): 10
double: 1.1 2.32
o b .OvlDemo(1.1, 2.32):

3.42

, Ov l Demo () .
, ,
, double.
, OvlDemo ()
void, , ,
. , , ,
.
, ( )
OvlDemo () .
// OvlDemo(int) ,
public void OvlDemo(int a) {
Console.WriteLine(" : " + a);

}
/* ! OvlDemo(int) ,
. */
public int OvlDemo(int a) {
Console.WriteLine(" : " + a);
return a * a;

}
,
, OvlDemo (),
.
3, C# (.. )
.
. .
//
// .
using System;
class Overload2 {
public void MyMeth(int x) {
Console.WriteLine(" M y M e t h (int): " + x ) ;

}
public void MyMeth(double x) {
Console.WriteLine(" MyMeth(double): " + x ) ;

238

!. C#

class TypeConv {
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.MyMeth(i); // ob.MyMeth(int)
ob.MyMeth(d); // ob.MyMeth(double)
ob.MyMeth(b); // ob.MyMeth(int)
ob.MyMeth(s); // ob.MyMeth(int)
ob.MyMeth(f); // ob.MyMeth(double)

}
}
.

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

My M e t h () :
int double. MyM e t h ()
byte, short float. ,
byte short, C#
int M y M e t h (int) .
float, double
MyMeth (double) .
, , ,
, .
,
MyMeth (), byte.
// MyMeth(byte).
using System;
class Overload2 {
public void MyMeth(byte x) {
Console.WriteLine(" MyMeth(byte): " + x ) ;

}
public void MyMeth(int x) {
Console.WriteLine(" MyMeth(int):

}
public void MyMeth(double x)

" + x) ;

8.
Console.WriteLine(" MyMeth(double): " + ) ;

239

'

}
}
class TypeConv {
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.MyMeth(i); // ob.MyMeth(int)
ob.MyMeth(d); // ob.MyMeth(double)
ob.MyMeth(b); // ob.MyMeth(byte)
//
ob.MyMeth(s); // o b .M y M e t h (int)
ob.MyMeth(f); // ob.MyMeth(double)

MyMeth(int): 10
MyMeth(double): 10.1
MyMeth(byte): 99
MyMeth(int): 10
MyMeth(double): 11.5

M y M e t h (),
byte, byte
MyMeth (byte ) int.
, ref out, ,
. ,
.
public void MyMeth(int x) {
Console.WriteLine(" MyMeth(int):

" + x);

}
public void MyMeth(ref int x) {
Console.WriteLine(" MyMeth(ref int):

" + x);

}
,
ob.MyMeth(i)

M y M e t h (int x),
ob.MyMeth(ref i)

MyMe th(ref int x ).

2 40

I. #

ref out ,
, .
, M y M e t h ()
.
I
// !
public void MyMeth(out int x)
public void MyMeth(ref int x)

{//...
{ // . . .


MyMeth () ,
out, ref.
,
C# :
. , ,
. ,
, . -

. , ,
. , ,

, . , abs ()
, labs ()
, f abs ()
() .
, ,
, , , ,
.
, ,
. C#
, , ,
. ,
.NET Framework Abs (), Sys t e m . Math
. C# ,
Abs () , .
,
. , Abs
,
. .
,
, ,

.
,
.
- ,
. ,
,
. , Sqr ,
.

8.

2 41

.
.
.
C# ,
; ,
. ,
, ,
C# .
params.


, .
.
.
// .
using System;
class MyClass {
public int x;
public MyC l a s s () {
Console.WriteLine(" M y C l a s s ().");
x = 0;

}
public MyClass(int i) {
Console.WriteLine(" MyClass(int).");
x = i;

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

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

}
}
class OverloadConsDemo {
static void MainO- {
MyClass tl = new MyClass ();
MyClass t2 = new M y C l a s s (88);
MyClass t3 = new M y C l a s s (17.23);
MyClass t4 = new M y C l a s s (2, 4);
Console.W riteLine("tl.x : " + tl.x);

int).");

242

I. C#
Console.W r i teLine("t 2 . : " + t2.x);
Console.WriteLine("t3.x : " + t3.x);
C onsole.Write L i n e ("t 4 .x : " + t4.x);

}
}
.




tl.x:
t 2 .x : 88
t 3 .x : 17
t 4 .x : 8

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

MyClass () ,
-. ,
, new.

.


.
S tack , .
// .
using System;
class Stack {
// ,
c h a r [] stck; // ,
int tos;
//
// Stack ,
public Stack(int size) {
stck = new char[size]; //
tos = 0;

}
// Stack ,
public Stack(Stack ob) {
// ,
stck = new char[ob.s t c k .Length];
// ,
for (int i=0; i < ob.tos; i++)
stck[i] = ob.stck[i];
// tos ,
tos = ob.tos;

8.

243

// ,
public void Push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return; -

}
stck[tos]
tos++;

= ch;

}
// ,
public char Pop () {
i f (tos==0) {
Console.WriteLine (" - .");
return (char) 0;

}
tos ;
return stck[tos];

}
// true, ,
public bool IsFullO {
return tos==stck.Length;

}
// true, ,
public bool IsEmptyO {
return tos==0;

}
// ,
public int Capacity() {
return stck.Length;

}
// ,
public int GetNum() {
return tos;

}
}
// Stack.
class StackDemo {
static void Main() {
Stack stkl = new S t a c k (10);
char ch;
int i;
// stkl.
Console.WriteLine(" A-J stkl.");
for(i=0; !stk l .I sFull(); i++)

244

I. #
st k l .P u s h ((char)

('A' + i));

// stckl.
Stack stk2 = new Stack(stkl);
// stkl.
Console.Write(" stkl:
while ( !s t k l .IsEmpty() ) {
ch = s t k l .Pop ();
Console.Write(ch);

");

}
Console.WriteLine ();
C o nsole.W r i t e (" s t k 2 : ");
while ( !s t k 2 .IsEmpty() ) {
ch = s t k 2 .Pop ();
Console.Write(ch);

}
Console.WriteLine ("\n");

}
}
.
A-J stkl.
stkl: JIHGFEDCBA
stk2: JIHGFEDCBA

S t a c k D e m o (stkl),
. , (stk2).
Stack.
// Stack ,
public Stack(Stack ob) {
// ,
stck = new char[ob.s t c k .Length];
// ,
for (int i=0; i < ob.tos; i++)
stck[i] = ob.stck[i];
// tos ,
tos = ob.tos;

}

, , ob.
, ob, ,
tos, .

, .

8.

2 45

t h i s
,
. C#
t h i s . .
_{_1) : this (_2)
I I ... , .

}
,
_ 2 ,
, .
.
// this.
using System;
class XYCoord {
public int x, y;
public X Y Coord() : t h i s (0, 0) {
Console.WriteLine(" X Y C o o r d ()");

}
public XYCoord(XYCoord o b j ) : this(obj.x, obj.y) {
Console.WriteLine(" XYCoord(obj)");

}
public XYCoord(int i, int j) {
Console.WriteLine(" XYCoord(int,
x = i;

int)");

= j;

}
}
class OverloadConsDemo {
static void Main() {
XYCoord tl = new X Y C o o r d ();
XYCoord t2 = new X Y C o o r d (8, 9);
XYCoord t3 = new XYCoord(t2);
Console.WriteLine("tl.x,
Console.WriteLine ("t2.x,
Console.WriteLine ("1 3 .x ,

tl.y:
t2.y:
t3.y:

" + tl.x + \ " + tl.y)


" + t2 .x + ", " + t2.y)
" + t 3 .x + ", " + t3.y)

}
}
.

XYCoord(int,
X Y C o o r d ()
XYCoord(int,
XYCoord(int,

int)
int)
int)

246

I. C#


t l ., t l . 0 ,
t 2 .x, t2 . 8,
t 3 .x, t3 . 8 ,

XYCoord(obj)

0
9
9

.
, XYCoord,
XYCoord(int, int).
this. ,
1 1, X Y C o o r d ( ) , this (0 , 0 ) ,
XYCoord (0, 0) .
t2.
this
, , , .

,
this .

" " ,
.
XYCoord.
public XYCoord(int )

: t h i s (, )

{ }


, . ,
" "
, .



. ( 10.)
,
,
. ,
.
LINQ-.
( LINQ- 19.)
, ,
.
.
// ,

using System;
class MyClass {
public int Count;
public string Str;

8.

247

class ObjlnitDemo {
static void Main() {
// MyClass,
.
MyClass obj = new MyClass { Count = 100, Str = "" };
Console.WriteLine(obj.Count + " " + obj.Str);

}
}
.
100

,
obj .Count 100, obj .
Str "". ,
MyClass
. obj My C lass
.
MyClass obj = new MyClass

{ Count = 100,

Str = ""

};


. ,
MyClass ( ),
Count Str .
,
. , obj ,
.
MyClass obj = new MyClass

{ Str = "",

Count = 100 };

Str
Count,
. .
:
new _ { = , = ,

. . .}

, .. ,
_ . ,
, , .
, ,
, MyClass, . ,

. , ,
, LINQ-.


C# 4.0 ,
.
.

248

I. C#

,
. ,
.
, ,
. "7'
.

.
, .
.
.
static void OptArgMeth(int alpha,

int beta=10,

int gamma = 20)

: beta gamma,
beta 10, gamma
20. ,
. ,
alpha . , ,
.
O p t A r g M e t h (),
.
// .
OptArgMeth(1, 2, 3);
// gamma .
Op tArgMeth(1, 2);
// beta gamma .
O p tArgMeth(1);

alpha 1, beta
2, g a mma 3. ,
, , , .
alpha 1, beta
2, gamma
20. , alpha
1, b e t a g a m m a
. , , , beta
,
gamma. ,
.

.
// .
using System;
class OptionArgDemo {
static void OptArgM eth(int alpha, int beta=10, int gamma = 20)
Console.WriteLine (" alpha, beta gamma: " +
alpha + " " + beta + " " + gamma);

8.

249

}
static void Main() {
// .
OptArgMeth(1, 2, 3);
i
I I gamma .
OptArgMeth(1, 2);

// beta gamma .
OptArgMeth(1);

}
}

.
alpha, beta gamma:
alpha, beta gamma:
alpha, beta gamma:

12 3
1 2 20
1 10 20

, ,
, .
,
. ,
.
int Sample(string name = "",

int userid)

{ // !

userid
name. ,
. ,
.
int Sample(int accountld, string name = "", int userid)

{ //.!

name , u s e r i d
name ( ).
, ,
. ( .)
, , ,

. ,
.

. , ,
, ,
.
.



. , ,

250

!. C#

Op tArgMeth (). C#
OptArgMeth (),
,
. .
static void OptArgMeth(int alpha)
static void OptArgMeth(int alpha,
static void OptArgMeth(int alpha,

int beta)
int beta,

int gamma)

OptArgMeth ()
, . ( beta gamma
, .)
, OptArgMeth ()
.
,
, .



, .
.
, ,
.
OptArgMeth ().
static void OptArgMeth(int alpha, int beta=10, int gamma = 20)
Console.WriteLine(" alpha, beta gamma: " +
alpha + " " + beta + " " + gamma);

}
static void OptArgMeth(int alpha, double beta=10.0, double gamma = 2 0 . 0 )
Console.WriteLine(" alpha, beta gamma: " +
alpha + " " + beta + " " + gamma);

}
,
beta gamma,
. int,
double. O p t A r g M e t h ()
.
O ptArgMeth(1); // - !

, ,
: , beta gamma
int, , double. ,
O p t Ar g M e t h () ,
.
,
, ,
. , ,
,
.

8.

251


,
, .
D i s p l a y (),
.
// ,

using System;
class UseOptArgs

// ,
static void Display(string str, int start = 0, int stop = -1)

if(stop < 0)
stop = str.Length;
// ,
if(stop > str.Length | start > stop | start < 0)
return;
for (int i=start; i < stop;
Console.Write(str[i] ) ;

i++)

Console.WriteLine() ;

}
static void Main() {
Display(" ");
Display(" ", 12);
Display("3TO ", 4, 14);

}
}
.

Display ().
. ,
.
. stop ,
-1, ,
. start
, 0. ,
.
. ,
Display () (.. ),
. Display () ,
, ,

252

I. C#

start, . Display ()
, , ,
start, , stop.
, , ,
, .
, 1 ,
.
.
,
.
, . ,
,
.
.
,
. ,
. ,
,
. , ,
!


, ,
. C# 4.0.
, ,
, ,
. ,
.
. ,
.
. , -
,
.
.
_

_ ,
. , _
.
,
. I s Factor (),
true, .
// ,
using System;
class NamedArgsDemo

8.

2 53

// , ,
static bool IsFactor(int val, int divisor) {
i f ((val % divisor) == 0) return true;
return false;

}
static void Main() {
// IsFactor().
// ,
if(IsFactor(10, 2))
Console.WriteLine("2 - 10.");
// ,
if(IsFactor(val: 10, divisor: 2))
Console.WriteLine("2 - 10.");
// ,
i f (IsFactor(divisor: 2, val: 10))
Console.WriteLine("2 - 10.");
// , ,
if(IsFactor(10, divisor: 2))
Console.W r i teLine("2 - 10.");

}
}
.
2
2
2
2

10.
10.
10.
10.

, I s F a c t o r ()
.
,
.
-, . ,
IsFactor () .
IsFactor(val :10, divisor: 2)
IsFactor(divisor: 2, val: 10)


. , ( )
. . -,
,
.
IsFactor(10, divisor:

2)

, , ,

.

254

I. C#


. D isp lay (),
.
// .
Display(stop: 10, str: " ",

start:

0);

// start .
Display(stop: 10, str: " ") ;
// , stop by name,
// start
Display("3TO ", stop: 10);

,
.
,
,
. , ,
.

,
, . (06
.)

M ain ()

Main (). .
, .
.

M ain ()

Main () ( ).
Main ().
static int M a i n ()

, Main ()
int void.
, , Main (),
-
.
,
.

8.

255

M ain ()
,
.. ,
. C#
Main ().
Main ().
static void Main(string[ ] args)
static int Main(string[ ] args)

Main () void ,
, .
s t r i n g ,
Main ( ). (a rg s )
, .
,
, .
// .
using System;
class CLDemo {
static void Main(string[] args) {
Console.WriteLine(" " +
args.Length +
" .");
Console.WriteLine(" : ");
for(int i=0; i < args.Length; i++)
Console.WriteLine(args[i]);

}
}
CLDemo :
CLDemo

.
3 .
:

,
, ,
.
.
.
1. , "" "" ..
1. ,
,
. .

256

I. C#

// ,
// .

using System;
class Cipher {
static int Main(string[] args)

// ,
if(args.Length < 2) {
Console.W r i teLine(": " +
"1: <>/<> " +
" [2... ]");
return 1; //

}
// ,
// <> <>.
if(args[0] != "" & args[0] != "") {
Console.Write L i n e (" " +
"<> <>.");
return 1; //

}
// ,
for(int n=l; n < args.Length; n++) {
for(int i=0; i < args[n].Length; i++) {
i f(args[0] == "")
Console.Write((char) (args[n][i] + 1 ) );
else
Console.Write((char) (args[n][i] - 1) );

}
Console.Write(" ");

}
Console.WriteLine() ;
return 0;

}
}
,
, "" ""
, .
, , Cipher.
C:\Cipher

C:\Cipher

. -,
,
, . ,

8.

257

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

C# , .
, , , . ,
, .
- .
, , .
.
.
N 1 N.
, 3 12><3, 6.
.
.
// ,
using System;
class Factorial

// .
public int FactR(int n) {
int result;
if(n==l) return 1;
result = FactR(n-l)
return result;

* n;

}
// .
public int FactI(int n) {
int t, result;
result = 1;
for(t=l; t <= n; t++)
return result;

result *= t;

258

I. C#

class Recursion {
static void Main() {
Factorial f = new Factorial();
Console.WriteLine(", .");
3 " + f.FactR(3));
Console.WriteLine("
4 " + f.FactR(4));
Console.WriteLine("
5 " + f .F a c t R (5));
Console.WriteLine("*
Console.WriteLine() ;
Console.W r i teLine(", .");
Console.WriteLine(" 3 " + f.FactR(3));
Console.WriteLine(" 4 " + f.FactR(4));
Console.WriteLine(" 5 " + f.FactR(5));

.
, .
3 6
4 24
5 120
, .
3 6
4 24
5 120

FactI () .
, , 1,
, , .
F a ctR () .
F a c t R () 1, 1.
FactR(n-l) *.
F actR () -1.
, 1,
. ,
2, FactR ()
1. 1,
2 ( ). 2,
2 (1x2). FactR ()
, W r i t e L i n e O ,
F a c t R (),
.
,
,
.
, .

, .

.

8.

259


.
D i s p l a y R e v ().
// ,

using System;
class RevStr {
// ,
public void DisplayRev(string str) {
if (str.Length > 0)
DisplayRev(str.Substring(1, s t r .Length-1));
else
return;
Console.Write(str[0]);

}
}
class RevStrDemo {
static void Main() {
string s = " ";
RevStr rsOb = new RevStr ();

Console.WriteLine(" :

" + s);

Console.W r i t e (" :
rsOb.DisplayRev(sf;

");

Console.WriteLine();

}
}
.
:
:

, D isp lay R ev ( ) ,
, s t r .
, D isp lay R ev () ,
. ,
.

D isp layR ev ( ) .
, s t ,
.
,
-
. ,
.

260

. C#

, -
. ,
(CLR) .
,
.
,
, . ,
.
, , ,
.

, i f ,
.
.
.
, W r i t e L i n e (),
,
.

s t a t i c
,
. ,
,

. ,
static. static,

- . s t a t i c
, . s t a t i c
M a i n (), ,
.
s t a t i c ,
-.
. s t a t i c
, . , 10
c o u n t static, Timer,
.
Timer.count = 10;

,
, , .
static,
-. ,
, static, , .
, , s t a t i c
.

8.

261

s t a t i c .
. ,
, , ,
, f a l s e ,
b ool. , s t a t i c -
.
s t a t i c ,
, .
. S q rt () s t a t i c ,
System.M ath #.
,
s t a t i c .
// static.
using System;
class StaticDemo {
// static,
public static int Val = 100;
// static,
public static int ValDiv2()
return Val/2;

}
}
class SDemo {
static void Main()

Console.WriteLine(" " +
"StaticDemo.Val " + StaticDemo.V a l );
StaticDemo.Val = 8;
Console.WriteLine(" " +
"StaticDemo.Val " + StaticDemo.V a l );
Console.WriteLine("StaticDemo.ValDiv2(): " + StaticDemo.V a l D i v 2 ());

}
}
.
StaticDemo.Val 100
StaticDemo.Val 8
StaticDemo.Val D i v 2 (): 4

, s t a t i c
.
s t a t i c .
s t a t i c t h i s ,
- .

26 2

I. #

static
static, .
, ,
static . ,
, .
static.
static
static, . , ,
, ,
.
, ValDivDenom ()
static.
class StaticError {
public int Denom = 3 ; //
public static int Val = 1024; //
/* !
. */
static int ValDivDenom() {
return Val/Denom; // !

}
}
Denom ,
static.
Val, static.

, .
using System;
class AnotherStaticError

// ,
void NonStaticMeth() {
C onsole.Write L i n e (" NonStaticMeth().");

}
/* !
. */
static void staticMeth() {
NonStaticMeth(); // !

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

8.

26 3


. ,
.
class MyClass -{
// ,
void NonStaticMeth() {
Console.WriteLine(" NonStaticMeth().");

}
/*
. */
public static void staticMeth(MyClass ob) {
ob.NonStaticMeth(); // !

}
}
NonStaticMeth () staticMeth ()
ob MyClass.
static ,
, .
, . static
.
// static
// .
using System;
class Countlnst {
static int count = 0;
// ,
public Countlnst () {
count++;

}
// ,
~CountInst() {
count ;

}
public static int Ge t C o u n t O
return count;

}
}
class CountDemo {
static void Main()
Countlnst ob;

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

264

I. C#
ob = new C o u n t l nstO;
Console.WriteLine(" :

" + Countlnst.GetCount());

}
}
}
.

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

, C o u n tln st, count


s t a t i c . , , co u n t
. , cou n t
.
s t a t i c .
, ,
.
.
, .
, ,
,
. 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 M y C l a s s ();

t.a = i;
t.b = j;
return t; //

}
public void Show() {
Console.WriteLine(" b: " + a + " " + b ) ;

8.

265

}
}
class MakeObjects {
static void Main()
int i, j;

// , .
for(i=0, j= 10; i < 10; i++, j ) {
MyClass ob = M y C l a s s .Factory(i, j); //
o b .S h o w ();

}
Console.WriteLine ();

}
}
F a c t o r y ()
.
MyClass ob = MyClass.Factory(i,

j); //

MyClass,
.


s t a t i c . ,
, ,
, .
-
.
.
// .
using System;
class Cons {
public static int alpha;
public int beta;
// ,
static C o n s () {
alpha = 99;
Console.WriteLine(" .");

}
// ,
public C o n s () {
beta = 100;
Console.WriteLine(" .");

266

!. C#

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

}
}
.
.
.
Cons.alpha: 99
ob.beta: 100

, sta t i c ,
, .
:
. ,
, ,
.


static.
. -, . -,
.
,
static.
static class _

{ 11

...

static.
, ,
.
. -,
.
LINQ 19.
-,
. .
N u m e r i c F n s t a t i c
, .
N u m e r i c F n static,
static, .
, N u m e r i c F n ,
.
// .
using System;

8.

static class NumericFn {


/ / ,
static public double Reciprocal(double num)
return 1/num;

}
// ,
static public double FracPart(double num) {
return num - (int) num;

}
// true,
// num ,
static public bool IsEven(double num) {
return (num % 2) = = 0 ? true : false;

}
// true,
// num ,
static public bool IsOdd(double num) {
return !IsEven(num);

class StaticClassDemo {
static void Main() {
Console.WriteLine(" 5 " +
NumericFn.Reciprocal(5.0) ) ;
Console.WriteLine(" 4.234 " +
NumericFn.FracPart(4.234));
if(NumericFn.IsEven(10))
Console.WriteLine("10 .");
if(NumericFn.I s O d d (5))
Console.WriteLine("5 .");
// NumericFn,
// .
// NumericFn ob = new NumericFn(); // !

}
}
.
5 0.2
4.234 0.234
10 .
5 .

267

268

!. C#

,
. N um ericFn ,

.
NumericFn.
: ,
, .

_________


C#
.
.

.

. , +
,
,
.
,
.
, .
+, ,

, .. .

,
. ^

-
, #.
,
,
#.
#.

270

I. C#


.
operator, , ,
, .
(operator):
, .
.
// .
public static _ operator o p {_ )

{
//

}
// .
public static _ operator o p (_1 1,
_1 2)

{
1 1

}
, + /; _ ,
. ,
, , .
.
,
1 2 . ,
, public static.
, ,
.
, . , C#
, . ,
+ int string.
:
ref out.


,
, +
ThreeD,
. +
ThreeD .
- .
// .
using System;

9.
// ,
class ThreeD {
int , , z; //
public Thr e e D () { = = 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 T h r e e D ();
/*
result. =
result. =
result.z =

. */
opl.x + 2.; //
opl.y + 2.; // ,
opl.z + op2.z; // .

return result;

}
//
public static ThreeD operator -(ThreeD opl, ThreeD op2)

{
ThreeD result = new T h r e e D ();
/* :
opl , 2 . */
result. = opl.x - 2.; //
result. = opl.y - 2.; //
result.z = opl.z - op2.z; //
return result;

}
// X, Y, Z.
public void Show()

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

class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c;
Console.W r i t e (" a: ");
a .S h o w ();
Console.WriteLine ();
Console.W r i t e (" b: ");
b .S h o w ();
Console.WriteLine() ;

271

27 2

I. #
= + b; // b
Console.Write(" + : ");
.S h o w ();
Console.WriteLine() ;
c = a + b + c ;
// , b
Console.W r i t e (" + b + : ");
.S h o w ();
Console.Writ e L i n e () ;
= - ; //
Console.Write(" - : ") ;
.S h o w ();
Console.WriteLine() ;
= - b; // b
Console.Write(" - : ");
.S h o w ();
Console.WriteLine() ;

}
}
.
: 1, 2, 3
: 10,

10,

10

+ : 11, 12, 13
+ + :

22,

24, 26

- : 21, 22, 23
- : 11,

12,

13

,
+. + ThreeD,
,
o p e r a t o r + (). , , ,
,
ThreeD, .
, + ,
, :
10 + 12. 22, 10, 12.

, ,
.
, operator+ () ThreeD.
C# ,
ThreeD, +
, a + b +. +b
ThreeD, .

9.

273

+b ,
a+b+ .
,
operators- (), ,
, z .
+ ThreeD
, ..
.
operator- (). -
, +, .
, (
), : - , - !

, . ,
, ,
.


, .
, , , .
,
ThreeD.
// ,
public static ThreeD operator - (ThreeD op)

{
ThreeD result = new T h r e e D ();
result.x = -op.x;
result. = -op.;
result.z = -op.z;
return result;

}
,
,
. ,
. ,
. ,
= -

, b .
C# ++ - - .
,
. #,
.
operator++ () ThreeD.

274

I. C#

// ++.
public static ThreeD operator + + (ThreeD op)

{
ThreeD result = new T h r e e D ();
// ,
result.x = op.x + 1;
result. = op. + 1;
result.z = op.z + 1;
return result;

}
,
- ++.
// ,
using System;
// ,
class ThreeD {
int , , z; //
public T h r e e D () { = = 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 T h r e e D ();
/* .
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 T h r e e D ();
/* :
opl , 2 . */
result. = opl.x - 2.;
result. = opl. - 2.;
result.z = opl.z - op2.z;
return result;

}
// -.
public static ThreeD operator -(ThreeD op)

*/

9.

ThreeD result = new T h r e e D ();


result.x = -op.x;
result, -= -op.y;
result.z = -op.z;
return result;

}
// ++.
public static ThreeD operator + + (ThreeD op)

{
ThreeD result = new T h r e e D ();
// ,
result.x = op.x + 1;
result. = op.y + 1;
result.z = op.z + 1;
return result;

}
// X, Y, Z.
public void Show()

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

}
class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new T h r e e D ();
Console.W r i t e (" a: ") ;
a .S h o w ();
Console.WriteLine();
Console.Write(" b: ");
b .Show () ;
Console.WriteLine();
c = a + b ; // b
Console.W r i t e (" a + b: ");
c .S h o w ();
Console.WriteLine();
c = a + b + c ;
// a, b
Console.Write(" a + b + : ");
.S h o w ();
Console.WriteLine();

275

276

I. C#
= - ; //
Console.W r i t e (" - : ") ;
.S h o w ();
Console.W r i teLine();
= - b; // b
Console.W r i t e (" - : ") ;
.S h o w ();
Console.W r i teLine();
= -; //
Console.Write(" -: ");
.S h o w ();
Console.WriteLine();
= ++;

// ,
//
Console.WriteLine(" = ++");
Console.Write(" ");
.S h o w ();
Console.W r i t e ("
");
.S h o w ();
// (1,2,3)
= new ThreeD(l, 2, 3);
Console.Write(" : ");
.S h o w ();
= ++;

// ,
//
Console.WriteLine("\ = ++");
Console.Write(" ");
.S h o w ();
Console.Write("
");
.Show () ;

}
}
.
: 1, 2, 3
: 10,

10, 10

+ : 11, 12,
+ + :

13

22, 24, 26

- : 21, 22, 23
- :

11,

12,

13

-: -1, -2, -3
= ++
1, 2, 3

9.

277

2, 3, 4

: 1, 2 ,

= ++ _
2 ,
2 ,

3, 4
3, 4

C#

. , , ,
, .
ThreeD. ,
+ ThreeD
.
ThreeD. ,
' ThreeD.
. + ,
.
// +
// ThreeD int.
public static ThreeD operator + (ThreeD opl, int op2)

{
ThreeD result = new T h r e e D ();
result.x = opl.x + op2;
result. = opl.y + op2;
result.z = opl.z + op2;
return result;

}
, int. ,

ThreeD. , , ,
,
, .
.
T hreeD
+.
// + :
// ThreeD,
// ThreeD int.
using System;
// ,
class ThreeD {
int , , z; //

278

I. C#

public T h r e e D () { x = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k;

// + ThreeD.
public static ThreeD operator + (ThreeD opl, ThreeD op2)

{
ThreeD result = new T h r e e D ();
/*
result. =
result. =
result.z =

.
opl.x + 2.;
opl. + 2.;
opl.z + op2.z;

*/

return result;

}
// +
// ThreeD int.
public static ThreeD operator + (ThreeD opl, int op2)

{
ThreeD result = new T h r e e D ();
result.x = opl.x + op2;
result. = opl. + op2;
result.z = opl.z + op2;
return result;

}
// X, Y, Z.
public void S h o w ()

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

class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3);
ThreeD b = new T h r e e D (10, 10, 10);
ThreeD = new T h r e e D ();
Console.Write(" a: ");
a .S h o w ();
Console.WriteLine();
Console.Write(" b: ");
b .Show ();
Co nsole.Wr i t e L i n e ();
= a + b; // ThreeD
Console.Write(" a + b: ");
c .S h o w ();
Console.Wr i t e L i n e ();
c = b + 1 0 ;

// ThreeD int

9.

2 79

Console.Write(" b + 10: ");


.S h o w ();

}
}
.
: 1, 2, 3
: 10,
+ :

10,

10

11, 1 2 ,

13

b + 10: 20, 20, 20

, +
ThreeD, .
ThreeD ,
.
+, ,
ThreeD, , .
. operator + (ThreeD, int) ,
.

= 2 + 10;

, , , .
obi = 10 + 2;

,
+,
.
, + .
int, ThreeD.
, operator+ ()
ThreeD ,
ThreeD. + (
) ,
. ThreeD,
+ .
//
//
//
//

+ :
- ThreeD,
ThreeD int,
int ThreeD.

using System;
// ,
class ThreeD {
int , , z; //
public T h r e e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i ; = j ; z = k;

280

I. #

// + ThreeD.
public static ThreeD operator + (ThreeD opl, ThreeD op2)

{
ThreeD result = new T h r e e D ();
/* .
result, = '"opl.x + 2.;
result. = opl. + 2.;
result.z = opl.z + op2.z;
return result;

}
// +
// ThreeD int.
public static ThreeD operator + (ThreeD opl, int op2)

{
ThreeD result = new T h r e e D ();
result.x = opl.x + op2;
result. = opl. + op2;
result.z = opl.z + op2;
return result;

}
// +
// int ThreeD.
public static ThreeD operator +(int opl, ThreeD op2)

{
ThreeD result = new T h r e e D ();
result.x = op2.x + opl;
result. = op2.y + opl;
result.z = o p 2 .z + opl;
return result;

}
// X, Y, Z.
public void Show()

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

class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new T h r e e D ();
Console.Write(" a: ");
a .S h o w () ;

*/

9.

281

Console.WriteLine ();
Console.Write(" b: ");
b .S h o w ();
Console.WriteLine();
= a + b; // ThreeD
Console.Write(" a + b: ");
c .S h o w ();
Console.WriteLine ();
c = b + 1 0 ; // ThreeD int
Console.Write(" b + 10: ");
.S h o w ();
Console.WriteLine() ;
c = 1 5 + b ; // int ThreeD
Console.Write(" 15 + b: ");
.S h o w ();

}
}
.
: 1, 2, 3
b: 10,

10,

10

+ : 11,

12,

13

b + 10: 20, 20, 20


15 + : 25, 25, 25


, == <, ,
. ,
t r u e false.

.
,
.
ThreeD,
< >.
ThreeD, .
, . ,
, .
, , ,
.
true, . ,
.

282
//

I. #

< >.

using System;
/ / ,
class ThreeD {
int , , z; //

public T h r e e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// <.
public static bool operator < (ThreeD opl, ThreeD op2)

{
if(Math.Sqrt(opl.x * opl.x + o p l . * opl. + o p l .z * opl.z) <
M a t h .Sqrt(op2.x * op2.x + o p 2 . * op2.y + o p 2 .z * op2.z))
return true;
else
return false;

// >.
public static bool operator > (ThreeD opl, ThreeD op2)

{
if(Math.Sqrt(opl.x * opl.x + opl. * opl. + opl.z * opl.z) >
M a t h .Sqrt(op2.x * op2.x + o p 2 . * op2.y + o p 2 .z * op2.z))
return true;
else
return false;

}
// X, Y, Z.
public void Show()

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

}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(l, 2 , 3);
ThreeD d = new T h r e e D (6, 7, 5);
Console.W r i t e ("
a .S h o w ();
Console.W r i t e ("
b .S h o w ();
Console.Write("
c .S h o w ();
Console.Write("
d. S h o w ();
Console.WriteLine();

a: ")
b: ")
: ")
d: ")

9.

i f (
i f (
i f (
if (

>
<
>
<

) Console.WriteLine("
) Console.WriteLine("
b) Console.WriteLine("
b)-Console.WriteLine("

>
<
>
<

b
b

2 83

");
");
");
");

i f ( > d) Console.WriteLine(" > d ");


else i f ( < d) Console.WriteLine("a < d ");
else Console.W r i teLine(" a n d " +
" ");

}
' }
.

:
:
:
d:

5, 6, 7
10, 10, 10
1, 2, 3
6, 7, 5

>
< b
a n d


: . , <,
>, .
.
==
<
<=

I=
>
>=

: == ! =,
O b j e c t . E q u a l s O n O b j e c t .
Ge tHashCode ().
11.

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

i f , w hile, f o r d o-w hile ?.
t r u e f a l s e , .
.
public static bool operator t r u e (_ )

{
// true false.

284

I. C#

public static bool operator f a l s e (_ )

{
// true false.

}
,
bool.
,
true false ThreeD.
: T h r e e D ,
, , .

.
// true false ThreeD.
using System;
// ,
class ThreeD {
int , , z; //
public T h r e e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j ; z = k;
// true.
public static bool operator true(ThreeD op) {
i f ((op.x != 0) M (op. != 0) || (op.z != 0))
return true; //
else
return false;

}
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op.y == 0) && (op.z == 0))
return true; //
else
return false;

}
// .
public static ThreeD operator (ThreeD op)

{
ThreeD result = new T h r e e D ();
// ,
result.x = o p .x - 1;
result. = op.y - 1;
result.z = op.z - 1;
return result;

9.
}
// X, Y, Z.
public void Show ()

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

}
}
class TrueFalseDemo {
static void Main() {
ThreeD a = new ThreeD (5, 6, 7);
ThreeD b = new T h r e e D (10, 10, 10);
ThreeD = new T h r e e D (0, 0, 0);
Console.Write(" a: ");
a .S h o w ();
Console.W r i t e (" b: ");
b .S h o w ();
Console.Write(" : ");
c .S h o w () ;
Console.WriteLine();
if(a) Console.WriteLine(" .");
else Console.Wr i t e L i n e (" .");
if(b) Console.Write L i n e (" b .");
else Console.WriteLine(" b .");
i f () Console.WriteLine(" .");
else Console.W r i teLine(" .");
Console.WriteLine();
Console.WriteLine("
ThreeD.") ;
do {
b .S h o w ();
b ;
} while(b);

}
}
.
: 5, 6, 7
: 10, 10, 10
: 0, 0, 0

b

ThreeD.
10, 10, 10

285

286
9,
8,
7,
,
5,
4,

I. C#

9, 9
8, 8
1, 7
6,
5, 5
4, 4

3, 3, 3
, 2, 2

,1 ,1

, T h r e e D
if do-while. , if
T h r e e D true.
, i f .
d o - w h i l e b . ,
, b , ..
. ,
b , true
.


, C#
: &, |, !, && | |. , ,
&, [ !. , ,
&& ||.
.


.
, & |
, bool.
, , !.
,
!, & | ThreeD. ,
ThreeD ,
. , .
//
// !, I & ThreeD.
using System;
// .
class ThreeD {
int , , z; //
public T h r e e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j ; z = k;

9.
// |.
public static bool operator |(ThreeD
opl, ThreeD op2)

{
if(

( (o p l .x != 0)
( (op2 .-x != 0)
return true;
else
return false;

M
||

(opl. != 0)
(op2. != 0)

M
||

(opl.z
(op2.z

!= 0))
!= 0))

I
)

}
// &.
public static bool operator & (ThreeD opl, ThreeD op2)

{
if ( ((opl.x != 0) &&
((op2.x != 0) &&
return true;
else
return false;

(opl. != 0) &&
(op2.y != 0) &&

(opl.z
(op2.z

!= 0))
!= 0))

}
// !.
public static bool operator ! (ThreeD op)

{
if ( (op.x != 0) ||
return false;
else return true;

(op.y != 0)

||

(op.z

!= 0))

}
// X, Y, Z.
public void Show()

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

class TrueFalseDemo {
static void Main() {
ThreeD a = new T h r e e D (5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD (0, 0, 0);
Console.W r i t e (" a: ");
a .Show ();
Console.W r i t e (" b: ");
b .S h o w ();
Console.W r i t e (" : ");
c .S h o w ();
Console.WriteLine();
if(!a) Console.WriteLine(" .")
if(!b) Console.WriteLine(" b .")
if(!c) Console.WriteLine(" .")
Console.WriteLine();

&
)

287

288

I. C#

i f ( & b) Console.WriteLine("a & b .");


else Console.W r i teLine("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.W r i teLine("a | .");

}
}
.
: 5, 6, 1
: 10, 10, 10
: 0, 0, 0
.

&
&
|
|

,
.
,
.

&, | !
b ool. ,
, .. ,
b o o l. , C#
bool.
b o o l
. , ,
, .



&& | |
, . -,
& |. -,
& | ,
, . -,
,
. -, tru e
f a l s e . ,
.
,
& | ThreeD,
&& ||.

9.
/*
!, | & ThreeD.
&& ||
. */
using System;
// ,
class ThreeD {
int , , z; //
public T h r e e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i ; = j ; z = k;

// | ,
public static ThreeD operator |(ThreeD opl, ThreeD op2)

{
i f ( ((opl.x
( (op2.x
return new
else
return new

!= 0) || (opl. != 0)
!= 0) || (op2. != 0)
T h r e e D (1, 1, 1) ;

||
||

(opl.z
(op2.z

!= 0))
!= 0))

|
)

T h r e e D (0, 0, 0) ;

}
// & ,
public static ThreeD operator & (ThreeD opl, ThreeD op2)

{
i f ( ((opl.x
((op2.x
return new
else
return new

!= 0) && (opl. != 0) &&


!= 0) && (op2.y != 0) &&
T h r e e D (1, 1, 1);

(opl.z
(op2.z

!= 0))
!= 0))

&
)

T h r e e D (0, 0, 0);

}
// !.
public static bool operator ! (ThreeD op)

{
if(op) return false;
else return true;

}
// true.
public static bool operator true(ThreeD op) {
i f ((op.x != 0) || (op.y != 0) || (op.z != 0))
return true; //
else
return false;

}
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op.y == 0) && (op.z == 0))
return true; //
else

289

290

I. C#
return false;

}
// X, Y, Z.
public void S h o w ()

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

}
class TrueFalseDemo {
static void Main() {
ThreeD a = new T h r e e D (5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new T h r e e D (0, 0, 0) ;
Console.W r i t e (" a: ");
a .S h o w ();
Console.Write(" b: ");
b .S h o w ();
Console.W r i t e (" : ");
c .S h o w ();
Console.WriteLine() ;
if (a) Console.WriteLine(" .");
if(b) Console.WriteLine(" b .");
i f () Console.WriteLine(" .");
if(!a)
if(!b)
if(!c)

Console.W r i teLine(" .");


Console.WriteLine(" b .");
Console.WriteLine(" .");

Console.WriteLine ();
Console.WriteLine(" &
i f ( & b) Console.WriteLine(" & b .");
else Console.WriteLine(" & b .");
i f ( & ) Console.WriteLine(" & .");
else Console.WriteLine(" & .");
i f ( | b) Console.WriteLine(" | b .");
else Console.Write L i n e (" | b .");
i f ( | ) Console.W r i teLine(" | .");
else Console.WriteLine(" | .");
Console.Wri t e L i n e ();
// .
Console.Write L i n e (" " +
" && ");
i f ( && b) Console.WriteLine(" && b .");
else Console.WriteLine(" && b .");

|");

9.

291

i f ( && ) Console.WriteLine(" && .");


else Console.WriteLine(" && .");
i f ( b) Console.WriteLine (" || b .");
else- Console.WriteLine(" || b .");
if ( | | ) Console.WriteLine(" | | .");
else Console.WriteLine(" || .");

}
}
.
: 5, 6, 7
: 10, 10, 10
: 0, 0, 0

b
.
& |
& b ,
& ,
| b ,
| .
&&
&& b ,
&& ,
,
.

||

,
& |. .
// | ,
public static ThreeD operator | (ThreeD opl, ThreeD op2)

{
if ( ( (o p l .x
( (op2.x
return new
else
return new

!= 0) M (opl. != 0)
!= 0) || (op2. != 0)
T h r e e D (1, 1, 1) ;

||
||

(opl.z
(op2.z

!= 0))
!= 0))

|
)

T h r e e D (0, 0, 0);

}
// & ,
public static ThreeD operator & (ThreeD opl, ThreeD op2)

{
if ( ((opl.x
((op2.x
return new
else
return new

!= 0) && (opl. != 0) &&


!= 0) && (op2.y != 0) &&
T h r e e D (1, 1 , 1 ) ;
ThreeD (0, 0, 0);

(opl.z
(op2.z

!= 0))
!= 0))

&
)

292

!. #

,
ThreeD.
, .
, ThreeD,
.
, . ,
& b :
i f ( & b) Console.WriteLine(" & b .");
else Console.WriteLine(" & b .");

ThreeD, .
t r u e f a l s e , T h r e e D
t r u e
bool. true, , if
.
,
ThreeD.
. o perator true
( ||) o p e r a t o r false (
&&). ,
(& |) .
(& |)
. , &&
I |, & | ,
.
.
i f (

) Console.WriteLine(" || .");

tr u e .
, |
. :
i f (

a) Console.WriteLine (" || .");

t r u e ,
. ,
|.

, , , ,
.
t r u e f a l s e
, .
. ,
& | , , ,
.


,
.

9.

2 93

,
. C#
,
. .

#,
, , .
: .
:
public static explicit operator _{_ v)
public static implicit operator _(_ v)

{return ;}
{return ;}

_ , ; _ , ; ,
.
, _ ,
.
(implicit),
, , ,
.
(explicit), ,
.
.
ThreeD,
. ,
T h r e e D , .
, ,
.
.
public static implicit operator int(ThreeD opl)

{
return opl.x * opl. * opl.z;

}
,
.
// ,
using System;
// ,
class ThreeD {
int , , z; //
public Thre e D () { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i ; = j ; z = k;
// +.
public static ThreeD operator + (ThreeD opl, ThreeD op2)

294

I. C#
ThreeD result = new T h r e e D ();
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) ;

}
class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new T h r e e D ();
int i;
Console.Write(" a: ");
a .S h o w ();
Console.Wr i t e L i n e () ;
Console.Write(" b: ");
b .S h o w ();
Console.Write L i n e ();
= a + b; // b
Console.Write(" a + b: ");
c .Show ();
Console.Wr i t e L i n e ();
i = a; // int
Console.WriteLine(" i = a: " + i) ;
Console.Wri t e L i n e ();
i = a * 2 - b ;
// int
Console.WriteLine(" a * 2 -

}
}
.
: 1 ,
: 10,

2,

10, 10

9.

+ :

11, 12,

295

13

i = : 6
* 2 - : -988

, ThreeD
, i = ,
.
6, ,
. int
, .
operator int() = + .
. ,
ThreeD double
.
.

: ; ;
.
, ,
, .
.
,
int.
// ,
using System;
// ,
class ThreeD {
int , , z; //
public Thr e e D () { = = 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 T h r e e D ();
result.x = opl.x + op2.x;
result. = opl. + op2.y;
result.z = opl.z + op2.z;
return result;

}
// ,
public static explicit operator int(ThreeD opl)

{
return opl.x * opl. * opl.z;

296

I. C#

// X, Y, Z.
public void Show ()

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

class ThreeDDemo {
static void Main() {
ThreeD a = new T h r e e D (1, 2, 3) ;
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new T h r e e D ();
int i;
Console.Write(" a: ");
a .S h o w ();
Console.Write L i n e () ;
Console.W r i t e (" b: ");
b .S h o w () ;
Console.WriteLine() ;
= a + b; // b
Console.Write(" a + b: ");
c .S h o w ();
Console.WriteLine() ;
i =

(int)

a; // int ,
//
Console.WriteLine(" i = : " + i) ;
Console.WriteLine();
i = (int)a * 2 - (int)b; //
Console.Wr i t e L i n e (" * 2 - b: " + i) ;

}
}
,
i n t . ,
, .
i =

(int) ; // int ,
//

.
,
. ,
in t,
double.
ob j e c t .

.

9.

297

. (
11.)
. (
12.)
, ,

. ,
, .

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


,
,
C# .
, ,
. , +
ThreeD
. , , +
,
/, .
: ,
,
.
. ,
,
, .
, , . ,
, ,
, , +=. ,
. ,
.
&&
??
=>
default
typeof

0
[]
->
is
unchecked

9
11
as
new

=
checked
sizeof

() ,

, .

298

!. #

, , , +=,
, . ,

, .
, +=
o p e ra t o r + ( ) . ,
o p e r a to r + () ThreeD,
b 11,12,13.
ThreeD = new T h r e e D (1, 2, 3) ;
ThreeD b = new ThreeD(10, 10, 10);
b += a; // b

: , [ ]
,
, .


, ,
ThreeD,
. ,
.
, ,
,
.
4-
. , , ,

4- , ,
,
,
! ,
- #.
.

Nybble. int,
0 15. N yb b l e
.
Nybble.
i n t Nybble.
Nybble int.
: (>) (<).
.
int Nybble.
Nybble int.

9.

299

, ,
N y b b l e #.
.
.
Nybble, N ybbleDemo,
.
// 4- Nybble.
using System;
// 4- .
class Nybble {
int val; //
public N y b b l e () { val = 0 ;

public Nybble(int i) {
val = i;
val = val & OxF; // 4

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

}
// +
// int Nybble,
public static Nybble operator +(int opl, Nybble op2)

{
Nybble result = new N y b b l e ();
result.val = opl + op2.val;

300

I. C#
result.val = result.val & OxF; // 4
return result;

}
// ++.
public static Nybble operator + + (Nybble op)

{
Nybble result = new N y b b l e ();
result.val = op.val + 1;
result.val = result.val & OxF; // 4
return result;

}
// >.
public static bool operator > (Nybble opl, Nybble op2)

{
if(opl.val > op2.val)
else return false;

return true;

}
// <.
public static bool operator < (Nybble opl, Nybble op2)

{
if(opl.val < op2.val)
else return false;

return true;

}
// 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 {
static void Main() {
Nybble a = new N y b b l e (1);
Nybble b = new N y b b l e (10);
Nybble = new N y b b l e ();
int t;
Console.WriteLine(" a : " + (int) a);
Console.WriteLine("b: " + (int) b ) ;
// Nybble if.

9.

301

i f ( < b) Console.WriteLine(" \");


// Nybble,
= + b;
Console.WriteLine(" = + b: " + (int)
// int Nybble,
+= 5;
Console.WriteLine(" += 5: " + (int)
Console.WriteLine() ;

);

);

// Nybble int.
t = * 2 + 3;
Console.WriteLine(" * 2 + 3: " + t ) ;
Console.WriteLine();
// int ,
= 19;
Console.WriteLine(" = 19: " + (int) );
Console.WriteLine() ;
// Nybble .
Console.WriteLine(" for " +
" Nybble.");
f o r ( = 0 ; < 10; ++)
Console.Write((int) + " ");
Console.WriteLine();

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

N y b b l e .
,
N y b b l e #. ,
Nybb l e
, i n t
. .
t = * 2 + 3;

302

I. C#

t 2 3 int,
Nybble.
N y b b l e int.
int, int
.
int N y b b l e int
Nybble. ,
:
= 19;

int Nybble.
Nybble, 4
19, , 3, 19
Nybble.
.
.
, Nybble Nybble for.
for
.

Nybble,
,
. .
( 13.)

____________________



:
. -
,
C# .
,
,

.
, C#
: .

,
[ ].
[ ],

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

304

I. C#


:
_ this[int ]

// ,
get {
// , .

}
I I ,
set {
// , .

}
}
_ . ,
, ,
_ . .
, .
int,
, , ,
.
(.. ): get
set. , ,
.
, : . ,
,
set , .
get ,
. , set value,
, .
, , ,
, .
, Fail So f tArray,
, ,
,
.
,
.
,
. FailSof tArray
, .
// .
using System;
class FailSoftArray {
i n t [] a; //
public int Length;

//

10.
public bool ErrFlag;

//

// ,
public FailSoftArray(int size) {
a = new irrt [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;

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

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

305

306

I. C#
Console.WriteLine ();

/ / .
Console.WriteLine(" .");
for (int i=0; i < (fs.Length * 2); i++) {
fs[i] = i * 10;
if(fs.ErrFlag)
Console.W r i te Line("f s [" + i + "] ");

for(int i=0; i < (fs.Length * 2); i++) { N


x = f s [i ] ;
i f (!f s .ErrFlag) Console.Write(x + " ");
else
Console.Writ e L i n e ("f s [" + i + "] ");

.
.
10 20 30 40
.
fs[5]
fs[6]
fs[7]
fs[8]
fs[9]
0 10 20 30 40 fs[5]
f s [6]
fs[7]
fs[8]
fs[9]

.
. .
public int this[int index]

, in t.
in d ex. ,
(p u b lic),
.
g e t.
get {
if (ok(index) ) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;

10.

307

get ,
, .
ok (), true,
, _ false. ,
,
. ,
, .
FailSof tArray E r r F l a g
.
. ( 13
C#
,
.)
s e t ,
.
set {
if(ok(index) ) {
a[index] = value;
ErrFlag = false;

}
else ErrFlag = true;

}
index ok () ,
,
value. true
ErrFlag. , value
, . ( )
.
, g e t s e t , .
, ,
g e t, s e t.


.
,
, . ,
FailSof t Array
double. d o uble
.
// FailSoftArray.
using System;
class FailSoftArray {
i n t [] a; //
public int Length;

//

308

I. C#

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.
.
public int this[double idx] {
// get.
get {
int index;
// .
i f ( (idx - (int) idx) < 0.5) index =
else index = (int) idx + 1;
if(ok(index)) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;

}
}
// set.
set {
int index;

(int)

idx;

*/

10.

// .
i f ( (idx - (int) idx) < 0.5) index =
else index = (int) idx + 1;

(int)

309

idx;

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 FSDemo {
static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// fs.
for(int i=0; i < fs.Length; i++)
fs[i] = i;
//
// int double .
Console.WriteLine("f s [1]: " + f s [1]);
Console.WriteLine("fs[2]: " + fs[2]);
Console.WriteLine("fs[1.1]:
Console.WriteLine("fs[1.6]:

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

}
}
.
f S [1 ] : 1
fs [2] : 2
f s [1 -1 ] : 1

fs [1. 6 ] : 2

, double
. , 1 .1 1,
1 .6 2.

, .
, ,
, - .

310

I. #


,
.
, .
,
, 2 0 15. ,
.
.
//
.
using System;
class PwrOfTwo

/* ,
2 0 15. */
public int this[int index] {
// 2.
get {
if((index >= 0) && (index < 16)) return pwr(index);
else return -1;

}
// set .

}
int pwr(int p) {
int result = 1;
for(int i=0; i < p; i++)
result *= 2;
return result;

}
}
class UsePwrOfTwo {
static void Main() {
PwrOfTwo pwr = new PwrOfTwo();
Console.W r i t e (" 8 2: ");
for(int i=0; i < 8; i++)
Console.Write(pwr[i] + " ");
Console.WriteLine();
Console.W r i t e (" : ");
Console.W rite(pwr[-1] + " " + p w r [17]);
Console.WriteLine();

10.

311

.
8 2: 1 2 4 8 16 32 64 128
: -1 -1

, PwrOf Two
get, set. ,
. , PwrOf Two
, . ,

.
pwr[0] = 1 1 ;

/ /


, set.
.
-, , ,
ref out,
. -,
static.


.
.
.
// .
using System;
class FailSoftArray2D {
int[,] a; //
int rows, cols; //
public int 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 {

312

I. C#
ErrFlag = true;
return 0;

}
}
// 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 {
static void Main() {
FailSoftArray2D fs = new FailSoftArray2D(3, 5);
int x;
// .
Console.Write L i n e (" .");
for (int i=0; i < 6; i++)
fs[i, i ] = i * 1 0 ;
for(int i=0; i < 6; i++) {
x = f s [i ,i ] ;
if(x != -1) Console.Write (x + " ");

}
Console.WriteLine ();
// .
Console.WriteLine("\ .");
for(int i=0; i < 6; i++) {
fs[i,i] = i *10;
i f (f s .ErrFlag)
Console.WriteLine(" f s [" + i + ", " + i + "]

}
for(int i=0; i < 6; i++) {
x = f s [i ,i ] ;
i f (!f s .ErrFlag) Console.Write(x + " ");

10.

313

else
Console.WriteLine(" f s [" + i + ", " + i + "] ");

}
}
}
:
.

0 10 20 0 0 0

fs[3,
fs[4,
fs[5,
0 10
fs[4,
fs[5,

.
3]
4]
5]
20 fs[3, 3]
4]
5]

. ,
.
, ,
, ,
, , ,
. , ,
, ,
.
. ,
g e t s e t .
. ,

,
g e t s e t.
g e t s e t .
:

get {
//

}
set {
//

}
, i n t ,
. ,
. ,
s e t v a lu e , ,
.

31 4

I. C#

, , ,
, . ,
, .
( ,
.)
,
M y Prop, prop.
.
// .
using System;
class SimpProp {
int prop; // ,

MyProp

public SimpProp() { prop = 0 ; }


/* prop.
. */
public int MyProp {
get {
return prop;

}
set {
if(value >= 0) prop = value;

}
}
}
// ,
class PropertyDemo {
static void Main() {
SimpProp ob = new SimpProp();
Console.WriteLine(" ob.MyProp:
ob.MyProp = 100; //
Console.Writ e L i n e (" ob.MyProp:

" + ob.MyProp);

" + ob.MyProp);

// prop .
Console.WriteLine(" " +
"-10 ob.MyProp");
ob.MyProp = -10;
Console.WriteLine(" ob.MyProp: " + ob.MyProp);

}
}
.
ob.MyProp: 0
ob.MyProp: 100
-10 ob.MyProp
ob.MyProp: 100

10.

315

.
p ro p , prop.
, ,
. , prop ,
, .
public, ,
. ,
prop, . get
prop, set
prop ,
. , ,
prop. , , .
, ,
.
. ,
, ,
get. , ,
set.

. ,
(Length). Fa il So ft Ar ra y
Length.
, ,
. (, , ,
.)
, Length " ",
, FailSoftArray.
// Length FailSoftArray.
using System;
class FailSoftArray {
i n t [] a; //
int len; // Length
public bool ErrFlag;

//

// ,
public FailSoftArray(int size) {
a = new int[size];
len = size;

}
// Length ,
public int Length {
get {
return len;

316

I. C#

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

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

}
}
//
// ,
class ImprovedFSDemo {
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 = f s [i ] ;
if(x != -1) Console.Write(x + " ");

}
Console.WriteLine ();
// fs.Length = 10; // ,

}
}
L en gth ,
1. -

10.

317

get, . ,
Length , . ,

.
// fs.Length = 1 0 ;

// ,

,
, Length , .
Lengt h Fa il So f t A r r a y
.
, ,
ErrFlag, .
FailSof tArray,
Error,
ErrFlag, .
// ErrFlag .
using System;
class FailSoftArray {
i n t [] a; //
int len; //
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 = false;
return a[index];

318

I. C#
} 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 {
static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// Error,
for(int i=0; i < fs.Length + 1; i++) {
fs[i] = i * 10;
i f (f s .Error)
tonsole.WriteLine(" " + i) ;

}
}
}
E r r o r
FailSoftArray. -, E r r F l a g ,
Error,
, . -,
Error " ". Error
, .
Main (),
, Error.


C# 3.0, _
, , .

.
:

10.
{ get;

set;

319

, .
, get set
, .
,
, .
. .
,
UserCount.
public int UserCount

{ get; set;

, .
, ,
. U se rC o u n t
.

.
get set.
(.. -
) , private
( " ").
,
,
. ,
. , ,
,
. ,
, .
,

,
.


8,
.
,
.
, .
8,
. , 8
, , Count
Str .
.
// .
using System;

320

!. C#

class MyClass {
1 1 ,
public int Count { get; set; }
public string Str { get; set; }

}
class ObjlnitDemo {
static void Main() {
// MyClass
.
MyClass obj =
new MyClass { Count = 100, Str = "" };
Console .WriteLine (obj .Cour^t + " " + obj.Str);

}
}
, Count Str
. ,
8, :
100

8,
, LINQ-.
.

,
. -,
,
ref out. -, .
, , ,
, . ,
get.
, .
get
.


set get ,
, . ,
public, set get
(public). set get
, private. ,
, ,
, .
,
. , ,

10.

321

.
private.
My Prop, set
private.
// .
using System;
class PropAccess {
int prop; // , MyProp
public PropAccess() { prop = 0; }
/* prop.
prop ,
. */
public int MyProp {
get {
return prop;

}
private set { //
prop = value;

}
}
// MyProp.
public void IncrPropO {
MyProp++; // . .

}
}
// ,
class PropAccessDemo {
static void Main() {
PropAccess ob = new PropAccess() ;
Console.WriteLine(" ob.MyProp:
//

ob.MyProp = 100;

" + ob.MyProp);

//

o b .IncrProp() ;
Console.WriteLine(" ob.MyProp :
ob.MyProp);

" +

}
}
PropAccess set private. ,
, IncrProp (),
PropAccess.
ob.MyProp PropAccessDemo .
,
. ,

322

!. C#


, , get set,
. ,
private.
Length
FailSoftArray,
.
public int Length { get; private set;

Leng th ,
set private. Lengt h
. , ,
, .
Error, .
public bool Error { get; private set;

Error ,
FailSoftArray.
Length Error
F a i l S o f tA rr ay len ErrFlag,
, len ErrFlag
L ength Error FailSoftArray.
F a i l S o f t A r r a y Ma i n ( ) ,
.
// '
// Length Error.
using System;
class FailSoftArray {
i n t [] a; //
// ,
public FailSoftArray(int size) {
a = new int [size];
Length = size;

}
// Length,
public int Length { get; private set; }
// Error,
public bool Error { get; private set; }
// FailSoftArray.
public int this[int index] {
// get.
get {

10.

323

if(ok(index) ) {
Error = false;
return a[index];
} else {
Error "= true;
return 0;

}
}
// set.
set {
if(ok(index)) {
a[index] = value;
Error = false;

}
else Error = true;

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

}
}
//
// ,
class FinalFSDemo {
static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// Error,
for(int i=0; i < fs.Length + 1; i++) {
fs[i] = i * 10;
if(fs.Error)
Console.WriteLine(" " + i) ;

}
}
}
Fa il SoftArray ,
, , .

. -,
: set get, . -,
,
. ,
, . (
12.)

324

I. C#



,
. RangeArray,

, .
, C#
.
: 1 ,
-5 5. RangeArray ,
.
RangeArray, .
RangeArray = new RangeArray(-5, 10); // ' -5 10
for(int i=-5; i <= 10; i++) ra[i] = i; // -5

10

,
R a n g e A r r a y -5 10 .
, .
,
-5 10.
R a n g eA rr ay RangeArrayDemo,
.
R a n g e A r r a y , int,
.
/* .
RangeArray ,
. RangeArray
. .
, , -5 5, 1 10
50 56. */
using System;
class RangeArray {
// .
int[] ; //
int lowerBound; //
int upperBound; //
// Length,
public int Length { get; private set; }
// Error,
public bool Error { get; private set; }
// ,
public RangeArray(int low, int high) {
high++;

10.
if (high <= low) {
Console.WriteLine(" ");
high = 1 ; //
low = 0;

}
= new int[high - low];
Length = high - low;
lowerBound = low;
upperBound = --high;

// RangeArray.
public int this[int index] {
// get.
get {
if(ok(index)) {
Error = false;
return a[index - lowerBound];
} else {
Error = true;
return 0;

}
}
// set.
set {
if(ok(index)) {
a[index - lowerBound]
Error = false;

= value;

}
else Error = true;

}
}
// true,
// ,
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return false;

return true;

}
}
//
// ,
class RangeArrayDemo {
static void Main() {
RangeArray ra = new RangeArray(-5, 5);
RangeArray ra2 = new RangeArray(1, 10);
RangeArray ra3 = new RangeArray(-20, -12);
// .
Console.WriteLine(" : " + .Length);
for(int i = -5; i <= 5; i++)

325

326

!. C#
[i ] = i ;
Console.Write(" : ");
for(int i = -5; i <= 5; i++)
Console.Write ( r a [i ] + " ");
Console.WriteLine("\n");
// ra2 .
Console.WriteLine(" 2 : " + ra2.Length);
for(int i = 1; i <= 10; i++)
ra2[i] = i;
Console.W r i t e (" r a 2 : ");
for(int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " ") ;
Console.WriteLine("\n") ;
// .
Console.Wr i t e L i n e (" : " + .Length);
for(int i = -20; i <= -12; i++)
ra3[i] = i;
>
Console.Write(" : ");
for (int i = -20; i <= -12; i++)
Console.Write(ra3[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 1 0
: 9
: -20 -19 -18 -17 -16 -15 -14 -13 -12

,
R a n g e A r r a y ,

, .
RangeArray.

R a n g e A r r a y
.
// .
int[] ; //
int lowerBound; //
int upperBound; //

10.

327

.
RangeArray.
lower Bound,
upperBound.
Length Error.
// Length,
public int Length { get; private set; }
// Error,
public bool Error { get; private set; }

, set private.
, ,
, .
RangeArray.
// ,
public RangeArray(int low, int high) {
high++;
if(high <= low) {
Console.WriteLine(" ");
high = 1; //
low = 0;

}
= new int[high - low];
Length = high - low;
lowerBound = low;
upperBound = high;

}
R a n g e A r r a y
low, high.
high ,
low high .
: . ,
, .
,
. Lengt h .
, lowerBound upperBound.
R an geArray , .
// RangeArray.
public int this[int index] {
// get.
get {
if(ok(index) ) {
Error = false;
return a[index - lowerBound];
} else {
Error = true;
return 0;

328

I. C#

// set.
set {
if(ok(index)) {
a[index - lowerBound]
Error = false;

= value;

}
else Error = true;

}
}
, FailSof tArray,
. ,
.
index - lowerBound

, index,
, .
lowerBound: ,
.
ok ().
// true,
// ,
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return false;

return true;

}
FailSof tArray,
,
l owerBound upperBound.
RangeArray
, .
, , . , ,
, ,
.
.


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


C# ,
.

. .
TwoDShape,
, ,
, ..
// ,
class TwoDShape {
public double Width;

330

I. C#

public double Height;


public void S h o w D i m O {
Console.Writ e L i n e (" " +
Width + " " + Height);

}
}
TwoDShape , .. ,
. ,
TwoDShape Triangle.
Triangle.
// ,
using System;
// .
class TwoDShape {
public double Width;
public double Height;
public void Sh o w D i m O {
Console.WriteLine(" " +
Width + " " + Height);

}
}
// Triangle, TwoDShape.
class Triangle : TwoDShape {
public string Style; //
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void S howStyleO {
Console.WriteLine(" " + Style);

}
class Shapes {
static void Main() {
Triangle tl = new T r iangle();
Triangle t2 = new Tria n g l e ();
tl.Width = 4.0;
tl.Height = 4.0;
tl.Style = "";
t2.Width = 8.0;
t2.Height = 12.0;
t2.Style = "";
Console.WriteLine(" tl:

");

11.

331

t l .ShowStyle ();
t l .ShowDim();
Console .WriteLine (" " + tl.Ar e a O ) ;
Console.WriteLine();
Console.WriteLine(" t 2 : ");
t 2 .ShowStyle();
t 2 .ShowDim();
Console.WriteLine(" " + t2.Area());

}
}
.
t l :

4 4
8
t 2 :

8 12
48

Triangle TwoDShape (
). , Triangle TwoDShape,
, , Are a () S ho wS ty le (). ,
Style, Area ()
, ShowStyle () .
, Triangle
TwoDShape.
class Triangle

: TwoDShape

. ,
, ,
. C#
.
T r i a n g l e TwoDShape,
Width Height Area (). ,
tl t2 Main () W id t h
Height, Triangle. . 11.1
, TwoDShape Triangle.
Width
TwoDShape

<

|\

Height
Show Dim ()

\ Triangle

Style
A re a ()
ShowStyle()

\J

. 11.1. T ria n g le

332

I. #

TwoDShape Triangle,
.
, ,
. ,
.
TwoDShape shape = new TwoDShape ();
shape.Width = 10;
shape.Height = 20;
s hape.S h o w D i m ();

, TwoDShape ,
TwoDShape, .
, .
class _ _
//

: _ _

}
. C#

. ( C# C++,
.
C++ #.) ,
. (,
,
.)
, , , .
:
,
,
.
. ,
TwoDShape .
// , TwoDShape.
class Rectangle : TwoDShape {
// true,
// ,
public bool IsSquare() {
if(Width == Height) return true;
return false;

}
// ,
public double Area() {
return Width * Height;

}
}
Rectangle TwoDShape,
Is Square (), , ,
Area (), .

11.

333


8, ,
.
, .
,
,
. , TwoDShape,
Triangle, .
// .
// .
using System;
// ,
class TwoDShape {
double Width;
//
double Height; //
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);

}
}
// Triangle, TwoDShape.
class Triangle : TwoDShape {
public string Style; //
// ,
public double Area() {
return Width * Height / 2 ; // ,
//

}
// ,
public void ShowStyle() {
Console.WriteLine(" " + Style);

}
}
T r i a n g l e ,
Width Height Area () . Width
Height ,
, .

.
, .

334

!. #

,
,
.
. C# .
(protected) ,
,
.
,
. ,
. ,
, ,
,
.
TwoDShape, Width Height
. :
Width Height. , ,
Wi dt h Height
, .
//
// . .
using System;
// ,
class TwoDShape {
double pri_width;
//
double pri_height; //
// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value : value;

}
public double Height {
get { return pri_height; }
set { pri_height = value < 0 ? -value

: value;

}
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);

}
}
// ,
// TwoDShape.
class Triangle : TwoDShape {
public string Style; //

11.

335

// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void ShowStyleO {
Console.WriteLine(" " + Style);

}
class Shapes2 {
static void Main() {
Triangle tl = new Triangle ();
Triangle t2 = new Triangle ();
tl.Width = 4.0;
tl.Height = 4.0;
tl.Style = "";
t2.Width = 8.0;
t2.Height = 12.0;
t2.Style = "";
Console.WriteLine(" tl: ");
t l .ShowStyle();
t l .ShowDim();
Console .WriteLine (" " + tl.Ar e a O ) ;
Console.WriteLine ();
Console.WriteLine(" t 2 : ");
t 2 .ShowStyle();
t 2 .ShowDim();
Console.WriteLine(" " + t2.Area());

}
}
Wi dth Height
p r i _ w i d t h p r i _ h e i g h t TwoDShape,
. ,
pri_ wi dt h p r i _ h e i g h t TwoDShape
, , .

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

336

I. #


,
. ,
.
, ,
. , ,
C# .
, .
p ro te c te d .
p r o te c te d , ,
, .
, ,
. ,
p r o t e c t e d , , ,
.
p ro te c te d .
// protected,
using System;
class {
protected int i, j; // , ,
// D
public void Set (int a, int b) {
i = a;
j = b;

}
public void Show() {
Console.WriteLine (i + " " + j);

}
}
class D : {
int k; //
// i j D
public void Setk() {
k = i * j;

}
public void Showk() {
Console.WriteLine(k) ;

}'
}
class ProtectedDemo {
static void Main() {
D ob = new D ();
ob.Set(2, 3); // ,

11.

337

ob.Show(); // , D
ob.Setk();
// , D
ob.ShowkO; // , D

}
}
D, i j
protected, Setk (). i j
private, D,
.
publ ic private, p r o t e c t e d
.
,
,
, .
,
. , TwoDShape ,
W i d t h H ei gh t ,
, ,
, protected.
, ,
. , p r o t ec te d
, ,
, .
.


,
. :
:
, ?
: ,
.
,
, , .
,
, C# .
. ,
.
,
: ,
, .
Triangle,
, Style ,
.
// Triangle,
using System;

338

I. C#

1 1 .
class TwoDShape {
double pri_width;
double pr.i_height;

// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value

: value;

}
public double Height {
get { return pri_height; }
set { pri_height = value < 0 ? -value

: value;

}
public void ShowDim() {
C onsole.W r i teLine(" " +
Width + " " + Height);

}
}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
// .
public Triangle(string s, double w , double h) {
Width = w;
//
Height = h; //
Style = s; //

}
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void ShowStyle() {
Console.W r i teLine(" " + Style);

class Shapes3 {
static void Main() {
Triangle tl = new T r iangle("", 4.0, 4.0);
Triangle t2 = new Tria n g l e ("", 8.0, 12.0);
Console.Wri t e L i n e (" t l : ");
t l .ShowStyle();
t l .S h o w D i m ();
Console .WriteLine (" " + t l . AreaO);

11.

339

Console.WriteLine ();
Console.WriteLine(" t 2 : ");
t 2 .ShowStyle();
t2 .-ShowDim () ;
Console.W r i teLine (" " + t2.Area());

}
}
T r i a n g l e
TwoDShape Style.
, ,
,
.
#: base, : -,
; -, ,
.
base.



base ,
.
:
__{_)

: base (_)

//

}
_ ,
. .
b a s e
, T w o D S h a p e
. ,
Width Height.
Triangle.
// TwoDShape.
using System;
// ,
class TwoDShape {
double pri_width;
double pri_height;
// TwoDShape.
public TwoDShape(double w, double h)
Width = w;
Height = h;

}
// .

340

I. C#

public double Width {


get { return pri_width; }
set { pri_width = value < 0 ? -value

: value;

}
public double Height {
get { return pri_height; }
set { pri_height = value < 0 ? -value

: value;

}
public void ShowDim() {
C onsole.Write L i n e (" " +
Width + " " + Height);

}
}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
// .
public Triangle(string s, double w, double h)
Style = s;

: base(w,

h)

}
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void S howStyleO {
Console.WriteLine(" " + Style);

}
class Shapes4 {
static void Main() {
Triangle tl = new Triangle("", 4.0, 4.0);
Triangle t2 = new Triangle("", 8.0, 12.0);
Console.WriteLine(" t l : ");
t l .ShowStyle();
t l .S h o w D i m ();
C onsole.Writ e L i n e (" " + tl.Ar e a O ) ;
Console.WriteLine();
Console.WriteLine(" t 2 : ");
t 2 .S howStyle();
t 2 .S h o w D i m ();
Console.WriteLine(" " + t2.Area());

11.

341

Triangle .
public Triangle(
string s, double w, double h)

: base(w,

h)

Triangle () base
w h. , , T w o D S h a p e (),
W i d t h Height w h.
Triangle,
Style, .
T w o D S h a p e . , T w o D Sh ap e
, ,
.
b as e ,
, ,
.
TwoDShape Triangle,
, ,
.
// 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 ) {
Width = Height = x;

}
'// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value

}
public double Height {
get { return pri_height;

: value;

342

I. C#
set { pri_height = value < 0 ? -value

: value;

}
public void S h o w D i m O {
Console.WriteLine(" " +
Width + " " + Height);

}
}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
/* , .
,
TwoDShape. */
public Tria n g l e () {
Style = "null";

}
// , ,
public Tr i a n g l e (
string s, double w, double h) : base(w,
Style = s;

h)

}
// ,
public Triangle(double x) : base(x) {
Style = "";

}
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void S howStyleO {
Console.WriteLine(" " + Style);

}
class Shapes5 {
static void M a i n () {
Triangle tl = new T r i angle();
Triangle t2 = new Tria n g l e ("", 8.0,
Triangle t3 = new Tria n g l e (4.0);
tl = t2;
Console.WriteLine(" t l : ");
t l .ShowStyle();
t l .S h o w D i m ();
Console.WriteLine(" " + t l . AreaO);

12.0);

11.

343

Console.W riteLine();
Console.WriteLine(" t 2 : ");
t 2 .ShowStyle ();
t 2 .ShowDim();
Console.WriteLine(" " + t2.Area());
Console.W r i teLine();
Console.WriteLine(" t 3 : ");
t 3 .ShowStyle();
t 3 .ShowDim();
Console.WriteLine(" " + t3.Area());
Console.WriteLine();

}
}
.
t l :

8 12
48
t 2 :

8 12
48
t 3 :

4 4
8

base.
base,
. , b ase
,
. .
b ase ().
, ,
.


,
.
. C# ,
, , .
,
new, . ,

344

I. #

, , new,
.
.
// .
using System;
class {
public int i = 0;

}
// .
j
class : A {
*
new int i; // i
public (int b) {
i = ; // i

}
public void S h o w () {
Console.W r i teLine(" i :

" + i) ;

}
}
class NameHiding {
static void Main()
ob = new (2);

o b .S h o w () ;

}
}
n e w
.
new int i; // i

, , ,
i i
. n e w
, .
.
i : 2

i,
i . S h o w ()
i, , ,
.

b ase
base,
this, ,

11.

345

, .
:
b a s e .

.
base ,
.
.
// base
// , .
using System;
class {
public int i = 0;

}
// ,
class : {
new int i; // i
public (int a, int b) {
base.i = ; //
i = ; // i

public void S h o w () {
// i .
Console.WriteLine(" i : " + base.i);
// i .
Console.WriteLine(" i : " + i) ;

}
}
class UncoverName {
static void Main() {
ob = new (1, 2) ;
o b .Show ();

}
}
.
i : 1
i :

i
i , base
i, .
b a s e .
,
Show (). Show ()
base Show (), .

346

I. C#

// .
using System;
class {
public int i = 0;
// S h o w () A
public void Show() {
Console.WriteLine(" i :

" + i);

}
// ,
class : {
new int i; // i
public (int a, int b) {
b a s e .i = ; //
i = ; // i

}
// S h o w () .
// new.
new public void Show() {
base.Show (); // S h o w ()
// i
Console.WriteLine(" i : " + i);

}
}
class UncoverName {
static void Main() {
ob = new (1, 2);
o b .Show ();

}
}
.
i : 1
i : 2

, b a s e .Show () Show ()
.
: new
, Show (),
, Sh ow (),
.



, . C#

11.

347

, .
,
. ,
, , , , ,
, .
. ,
.
,
, .
Triangle
ColorTriangle. ColorTriangle
, , Triangle TwoDShape,
color, .
// .
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 ) {
Width = Height = x;

}
// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value

: value;

}
public double Height {
get { return pri_height; }
set { pri_height = value < 0 ? -value

: value;

}
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);

348

I. C#

// , TwoDShape.
class Triangle : TwoDShape {
string Style; //
/* , .
,
TwoDShape. */
public Triangle () {
Style = "null";

}
// .
public Triangle(string s, double w, double h)
Style = s;

: base(w,

h)

}
// ,
public Triangle(double x) : base(x) {
Style = "";

}
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void ShowStyle() {
C onsole.Writ e L i n e (" " + Style);

}
// Triangle,
class ColorTriangle : Triangle
string color;

fc

public ColorTriangle(string c, string s,


double w, double h)
color = c;

: base(s,

w, h)

}
// ,
public void ShowColor() {
Console.Write L i n e (" " + color);

}
class Shapes6 {
static void Main() {
ColorTriangle tl =
new ColorTriangle("", "",
ColorTriangle t2 =

8.0,

12.0);

11.
new ColorTriangle("",

"",

2.0,

349

2.0);

Console.WriteLine(" t l : ");
t l .ShowStyle();
t l .ShowDinv() ;
t l .ShowColor ();
Console .WriteLine (" " + tl . A r e a O ) ;
Console.WriteLine () ;
Console.W riteLine(" t 2 : ");
t 2 .ShowStyle();
t 2 .ShowDim();
t 2 .ShowColor() ;
Console.WriteLine(" " + t2.Area());

}
}
.
t l :

8 12

48
t 2 :

2 2

2

Co l o r T r i a n g l e
Triangle TwoDShape,
, .
,
.
:
base
. , base C ol or Tr ia ng le
Triangle, base Triangle
TwoDShape.
,
, ,
.



:
,
, , ? ,

350

I. C#

,
? ,
: . ,
b ase.
, b ase ,
, .. .
.
// .
using System;
// ,
class {
public () {
Console.Writ e L i n e (" .");

}
}
// , .
class : {
public () {
Console.WriteLine(" .");

}
}

// , .
class : {
public () {
Console.WriteLine(" .");

}
}
class OrderOfConstruction
static void Main() {
= new ();

}
}
.
.
.
.

, .
,
.
, ,
,
, , .
, .

11.

351


, C#
.
,
. , ,
, .
,
.
// .
class X {
int ;
public X(int i)

{ a = i;

class Y {
int a;
public Y(int i)

{ a = i;

}
class IncompatibleRef {
static void Main() {
X x = new X (10);
X x2;
Y = new Y (5);
x2 = x; // ,
2 = ; // ,

}
}
X Y
, Y
X, .
-
.
2 = ; // ,

,
.
C#
:
.
,
. ,
.
.

352

I. C#

//
// .
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)
b = i;

: base(j)

}
}
class BaseRef
static void
X x = new
X x2;
Y = new

{
Main()
X (10);

Y (5, 6);

x2 = x; // ,
Console.WriteLine("2.: " + 2.);
2 = ; // , Y X
Console.WriteLine (" 2 . : " + 2.);
// X X
2. = 19; //
2. = 27; // , b X

//

}
}
Y X.
:
2 = ; // ,

Y X

. (
2 X)
, .. , .
,
, , .
,
,
, . 2
b Y, .
, , -

11.

353

.
.
, .
, ,
.

,
. ,
, .
.
, .
T w o D S h a p e Triangle.
, .
//
// .
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 ) {
Width = Height = x;

}
// TwoDShape.
public TwoDShape(TwoDShape ob) {
Width = ob.Width;
Height = ob.Height;

}
// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value

}
public double Height

: value;

354

I. C#
get { return pri_height; }
set { pri_height = value < 0 ? -value

: value

}
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);

}
}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
// , ,
public Trian g l e () {
Style = "null";

}
// Triangle,
public Triangle(string s, double w, double h)
Style = s;

: base(w,

h)

}
// ,
public Triangle(double x) : base(x) {
Style = "";

}
// Triangle,
public Triangle(Triangle ob) : base (ob) {
Style = ob.Style;

}
// ,
public double Area() {
return Width * Height / 2;

}
// ,
public void ShowStyle() {
Console.WriteLine(" " + Style);

}
class Shapes7 {
static void Ma^n() {
Triangle tl = new T r iangle("", 8 . 0 ,
// t l .
Triangle t2 = new Triangle (t*L) ;
Console.WriteLine(" t l : " )
t l .ShowStyle();

1 2 . 0 );

11.

355

t l .ShowDim();
Console.WriteLine (" " + tl.Ar e a O ) ;
Console.WriteLine ();
Console.WriteLine(" t 2 : ");
t 2 .ShowStyle();
t 2 .ShowDim();
Console.WriteLine(" " + t2.Area());

}
}
t2 t i n
. ' .
t l :

8 12
48
t 2 :

8 12
48

Triangle:
public Triangle(Triangle ob)
Style = ob.Style;

: base(ob)

}
Triangle
( base) TwoDShape.
public TwoDShape(TwoDShape ob)
Width = ob.Width;
Height = ob.Height;

}
, TwoDShape ()
TwoDShape, T r i a n g l e ()
Triangle. , ,
.
, TwoDShape ()
, TwoDShape.
TwoDShape () ,
TwoDShape, ,
, .


, virtual
. ,
. ,

356

!. #

. ,
, .
C# ,
, ,
, .
. ,
,
. ,
,
.

virtual, .
, override.

. ,
,
, . ,
s t a t i c a b s t r a c t (
).

C# : ,
, .
,
C# .
,
.
// .
using System;
class Base {
// ,
public virtual void W h o () {
Console.Wr i t e L i n e (" W h o () Base");

}
}
class Derivedl : Base {
// Who() ,
public override void W h o () {
Console.WriteLine(" W h o () Derivedl");

}
}
class Derived2 : Base {
// Who() ,
public override void W h o () {
Console.Wri t e L i n e (" Who() Derived2");

11.

357

class OverrideDemo {
static void Main() {
Base baseOb = new Base();
Derivedl dObl = new DerivedlO;
Deri'ved2 dOb2 = new Derived2();
Base baseRef;

//

baseRef = baseOb;
baseRef.W h o () ;
baseRef = dObl;
baseRef.W h o ();
baseRef = d0b2;
baseRef.Who();

}
}
.
W h o () Base.
W h o () Derivedl
W h o () Derived2

Base
Derivedl Derived2. Base
Who (), .
Main () Base, Derivedl Derived2. ,
baseRef Base.
b aseRef
Who (). ,
Who () ,
,
baseRef.

.
,
, .
/* ,
. */
using System;
class Base {
// .
public virtual void W h o () {
Console.WriteLine(" W h o () Base");

}
}
class Derivedl : Base {
// W h o () .

358

I. C#

public override void W h o () {


Console.WriteLine(" W h o () Derivedl");

}
}
class Derived2 : Base {
// Who()

}
class NoOverrideDemo {
static void Main() {
Base baseOb = new B a s e ();
Derivedl dObl = new Derivedl();
Derived2 d0b2 = new Derived2();
Base baseRef;

//

baseRef = baseOb;
base R e f .W h o ();
baseRef = dObl ;
baseRef.Who() ;
baseRef = d0b2;
ba s e R e f .W h o (); // W h o () Base

}
}
.
W h o () Base.
W h o () Derivedl
W h o () Base

Who () Derived2.
Derived2 Who () Base.

, ,
, .
/*
,

. */
using System;
class Base {
// ,
public virtual void W h o () {
Console.Write L i n e (" Who() Base");

}
}
class Derivedl

: Base

11.

359

// W h o () .
public override void Who() {
Console.WriteLine(" W h o () Derivedl");

}
}
class Derived2 : Derivedl {
// Who()

}
class Derived3 : Derived2 {
/ / Who()

}
class No0verrideDemo2 {
static void Main() {
Derived3 dOb = new Derived3();
Base baseRef; //
baseRef = dOb;
baseRef.W h o (); // Who() Derivedl

}
}
.
W h o () Derivedl

Derived3 Derived2,
Derivedl, , , Base.
, Who (), Derivedl,
,
Derived3 Derived2, Who ()
, Derivedl.
:
virtual override.
.


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

, ,
.
,
.

360

!. #

,
. , ,
,
.


,
TwoDShape. ,
TwoDShape, Area (). , -, Area ()
TwoDShape

, .
.
TwoDShape.
// -.
using System;
class TwoDShape {
double pri_width;
double pri_height;
// ,
public T woDShape() {
Width = Height = 0.0;
name = "null";

}
// .'
public TwoDShape(double w, double h, string n)
Width = w;
Height = h;
name = n;

}
// ,
public TwoDShape(double , string n) {
Width = Height = x;
name = n;

}
// TwoDShape.
public TwoDShape(TwoDShape ob) {
Width = ob.Width;
Height = ob.Height;
name = ob.name;

}
// ,
public double Width {
get { return pri_width; }

11.
set { pri_width = value < 0 ? -value

: value;

}
public double Height {
get { return pri_height; }
set -{ pri_height = value < 0 ? -value

: value;

}
public string name

{ get; set;

public void ShowDim() {


Console.WriteLine(" " +
Width + " " + Height);

}
public virtual double Area() {
Console.WriteLine(" Area()
return 0.0;

");

}
}
// , 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 = "";

}
// Triangle,
public Triangle(Triangle ob) : base(ob) {
Style = ob.Style;

}
// A r e a () Triangle,
public override double Area() {
return Width * Height / 2;

}
// ,
public void ShowStyle() {
Console.WriteLine(" " + Style);

361

362

I. C#

1 1 , TwoDShape.
class Rectangle : TwoDShape {
/ / Rectangle,
public Rectangle(double w , double h) :
base (w, h, "") { }
// ,
public Rectangle(double x) :
base(x, "") { }

// Rectangle,
public Rectangle(Rectangle ob) : base(ob) { }
// true,
// ,
public bool IsSquareO {
if(Width == Height) return true;
return false;

}
// Area() Rectangle,
public override double Area() {
return Width * Height;

class DynShapes {
static void Main() {
TwoDShape[] shapes = new TwoDShape[5];
s h a p e s [0]
s h a p e s [1]
s hap e s [2]
s hap e s [3]
s hap e s [4]

=
=
=
=
=

new
new
new
new
new

Triangle("", 8.0, 12.0);


Rectangle(10);
Rectangle(10, 4);
Triangle(7.0);
TwoDShape(10, 20, " ");

for (int i=0; i < shapes.Length; i++) {


Console.Wr i t e L i n e (" " + sha p e s [i ].name);
Console.WriteLine(" " + shapes[i ].A r e a ());
Console.Write L i n e ();

}
}
}
.

48

100

11.

363

40

24.5

A r e a ()
0

. ,
Area () v i r t u a l Tw oD Sh ap e
Triangle Rectangle . TwoDShape
Area () , ,

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

. , M ai n ()
TwoDShape,
Triangle, Rectangle TwoDShape.
,
.
.
,
. ,
,
. , TwoDShape,
Area ().

.


,
,
. ,
,
. , ,
.
T w o D S h a p e ,
Area () .
.
, ,

. . ,
, ,
. ,
, .

364

!. C#

,
, .
Triangle. , Area ().
- , ,
.
C# . .

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
, ( s t a t i c ) .
.
, ,
, c l a s s
a b s t r a c t .
, . ,
new .
,
.
a b s t r a c t . , a b s t r a c t
, .
,
TwoDShape.
, TwoDShape
Area () TwoDShape abstract. , ,
, , TwoDShape,
Area ().
// ,
using System;
abstract class TwoDShape
double pri_width;
double pri_height;

// , ,
public T woDShape() {
Width = Height = 0 . 0 ;
name = "null";

}
// .

11.
public TwoDShape(double w, double h, string n)
Width = w;
Height = h;
name = n;

}
// ,
public TwoDShape(double , string n) {
Width = Height = x;
name = n;

}
// TwoDShape.
public TwoDShape(TwoDShape ob) {
Width = ob.Width;
Height = ob.Height;
name = ob.name;

}
// ,
public double Width {
get { return pri_width; }
set { pri_width = value < 0 ? -value

: value;

}
public double Height {
get { return pri_height; }
set { pri_height = value < 0 ? -value : value;

}
public string name { get; set; }
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);

}
// () ,
public abstract double Area ();

}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
// , ,
public Triangle() {
Style = "null";

}
// Triangle,
public Triangle(string s, double w, double h)
base(w, h, "") {
Style = s;

365

366

I. C#

I / ,
public Triangle(double x) : base(x, "")
Style = "";

}
// Triangle,
public Triangle(Triangle ob) : base(ob) {
Style = ob.Style;

}
// Area() Triangle,
public override double A r e a () {
return Width * Height / 2;

}
// ,
public void ShowStyleO {
Console.WriteLine(" " + Style);

}
// , TwoDShape
class Rectangle : TwoDShape {
// Rectangle,
public Rectangle(double w , double h) :
base(w, h, ""){ }
// ,
public Rectangle(double x) :
base (x, "")- { }
// Rectangle,
public Rectangle(Rectangle ob) : base(ob) { }
// true,
// ,
public bool IsSquare() {
if(Width == Height) return true;
return false;

}
// A r e a () Rectangle,
public override double Area() {
return Width * Height;

}
class AbsShape {
static void Main() {
TwoDShape[] shapes = new TwoDShape[4];
s h a p e s [0] = new T r i angle("", 8.0,
s h a p e s [1] = new R e c tangle(10) ;

12.0);

11.

367

shapes[2] = new Rectangle(10, 4);


shapes[3] = new Triangle(7.0);
for(int i=0; i < shapes.Length; i++) {
Console.WriteLine(" " + shapes[i].name);
Console.WriteLine(" " + shapes[i].A r e a ());
Console.WriteLine() ;

}
}

>

,
Area () ,
. , ,
Area ().
. , TwoDShape , ,
Two DS ha pe . shapes
Main () 4 , TwoDShape
.
, TwoDShape -
ShowDim () abstract.
( ) ,
.
,
abstract.


s e a le d
,
. , ,
,
. ,
,
. C#
s e a le d .
,
s e a le d . ,
a b s t r a c t s e a le d ,

, .
se a le d .
sealed class {

// . . .
}
// .

368

I. C#

class : A { // !
/ /

...

}
,
, se a le d .
: s e a l e d
.
, D. ,
virtual, D sealed.
, %
. ,
class {
public virtual void MyMet h o d O

{ /* ... */ }

}
class D : {
// M y M e t h o d O
// ,
sealed public override void My M e t h o d O { /* */ }

}
class X : D {
// ! M y M e t h o d O !
public override void MyMet h o d O { /* */ }

}
MyMethod () D,
X.

o b je c t
C# o b je c t,
, .
, obj e c t. , , ,
o b j e c t
. , o b j e c t ,
C# . o b j e c t
C# System . O b ject,
.NET Framework.
obj e c t , . 11.1. ,
.
.
E q u als ( o b j e c t ) ,
, , , ..
, . E q u als ( o b je c t)
tr u e , ,
f a l s e .
. ,
. , E q u als (o b je c t) ,
.

11.

369

11.1. o b j e c t

public virtual bool


Equals(object o b )
public static bool
Equals(object o b j A ,
object o b j B )
protected F i n a l i z e ()

public virtual int


G e t H a s h C o d e ()
public Type G e t T y p e O
protected object
M e m b e r w i s e C l o n e ()
public static bool
ReferenceEquals(obj o b j A ,
object o b j )
public virtual string
T o S t r i n g ()

, ,
,
, ,
o b j A , , ,
obj


". C# Finalize ()

-,


, ..
, ,

, o b j A o b j B

,

GetHashCode () -, .
- ,
. , ,
, GetHas hC od e ()
.
9, ==,
E quals (o b je c t) GetHashCode (),
, Equals (o b je 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 te L in e ().
,
, .
.
// ToStringO
using System;
class MyClass {
static int count = 0;
int id;
public My C l a s s O

370

I. C#
id = count;
count++;

}
public override string ToStringO {
return " #" + id + " MyClass";

}
}
class Test {
static void Main() {
MyClass obi = new M y C l a s s (),
MyClass ob2 = new M y C l a s s (),
MyClass ob3 = new MyClass (),
Console.WriteLine(obi);
Console.WriteLine(ob2);
Console.WriteLine(ob3);

}
.
#0 MyClass
#1 MyClass
#2 MyClass


, #, ,
o b j e c t . , o b j e c t
, .
ob j e c t ,
. ,
, .. "" ,
.
.
o b je c t, #.

.
obj e c t .
.
, .
// .
using System;
class BoxingDemo {
static void Main()
int x;
object obj;

11.

371

X = 10;

obj = ; //
int =

(int)obj;

// ,
// obj, int
Console.WriteLine();

}
}
10. ,

obj, . ,
obj, int.
, .
in t S q r (), ,
, object.
// .
using System;
class BoxingDemo {
static void Main()
int x;
x = 10;

Console.WriteLine(" x :

" + x);

// x
// Sqr().
= BoxingDemo.S q r () ;
Console.WriteLine(" x : " + ) ;

}
static int Sqr(object ) {
return (int) * (int);

}
}
.
: 10
:

100


Sqr ().
#.
o bject,

object, . ,
o b j e c t ,
.
.

372

I. C#

// !
using System;

/
class MethOnValue {
static void Main() {
Console.W r i teLine(10.T oString() ) ;

}
}
10. ,
T o S trin g () ,
. 10
10!

o b je c t
ob j e c t
, o b je c t
"" .
, o b j e c t,
.
// object "" .
using System;
class GenericDemo {
static void Main() {
o b j e c t [] ga. = new obj e c t [10];
// ,
for (int i=0; i < 3; i++)
g a [i ] = i ;
// double,
for (int i=3; i < 6; i++)
ga[i] = (double) i / 2;
// ,
ga[6] = "";
ga[7] = true;
g a [8] = 'X';
ga[9] = "";

bool char.

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


Console.Wr i t e L i n e (" g a [" + i + "]: " + ga[i]

+ " ");

}
}
.
[0] : 0
[1] : 1

11.
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]

:
:
:
:
:
:
:
:

373

2
1.5
2
2.5

True
X

, o b j e c t
, o b j e c t
. ,
o b je c t
. , ,
o b je c t.
.
o b j e c t
, ,
C# .
, in t,
s t r i n g ..
, 2.0 C#
(
18).
, ,
.
o b j e c t ..

.

,


C# : ,
.
,
,

.
,
#: .
, ,
, .
.

#.

-
,
, .
.

, .

,
. ,
, .
,
,

376

I. C#

. C#
i n t e r f a c e .
.
. ,
. ,
, . ,
. ,
.
(..
) , .

. ,
-.
. , ,
,
. C#
:
.
in t e r f a c e .
.
interface {
_ _1 (_ ) ;
_ _2 [_) ;

//

...

_ _(_) ;

}
.
_ . , ,
. ,
.
, .
, .
,
.
public interface ISeries {
int G e t N e x t O ; //
void R e s e t (); //
void SetStart(int ) ; //

}
I S e r i e s . I
, ,
- . I S e r i e s p u b lic
.
, ,
. 15, -
, .
. ,
. ,
s t a t i c .

12. ,

377


,
.
, .
.
class _
//

: _ {

}
_ .
, . ,
.
.
.
.
,
.
, , p u b l i c .
, ,
. ,

, .
,
I S e r i e s . ByTwos,
,
.
// ISeries,
class ByTwos : ISeries {
int start;
int val;
public ByTwos () {
start = 0;
val = 0;

}
public int GetNext()
val += 2;
return val;

}
public void R e s e t () {
val = start;

}
public void SetStart(int x)
start = x;
val = start;

}
}

378

I. C#

, ByTwos ,
, ,
.
, ByTwos,
I S e r i e s .
ISeries.

// ByTwos, ,
using System;
class SeriesDemo {
static void Main() {
ByTwos ob = new B y T w o s ();

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


Console .WriteLine (" " + o b .GetNext () ) ;
Console.WriteLine("") ;
o b .R e s e t ();
for(int i=0; i < 5; i++)
Console.W r i teLine(" " + o b .G etNext());
Console.WriteLine(" 100");
ob.SetStart(100);
for(int i=0; i < 5; i++)
Console.Write L i n e (" " + o b .GetN e x t ());

}
}
SeriesD em o,
, I S e r i e s , ByTwos
SeriesDemo.
. , I S e r ie s .
cs, ByTwos . cs SeriesD em o. cs ,
:
>csc SeriesDemo.cs ISeries.cs ByTwos.cs

Visual Studio
#. ,
( ) .
.

2
4
6
8
10

2
4
6
8
10

12. ,
100.




379

102
104
106
108
110

, ,
.
ByTwos, G e t P r e v i o u s (),
.
// ISeries
// ByTwos GetPrevious().
class
int
int
int

ByTwos
start;
val;
prev;

: ISeries

public B y T w o s () {
start = 0;
val = 0;
prev = -2;

}
public int Ge t N e x t O
prev = val;
val += 2;
return val;

}
public void R e s e t () {
val = start;
prev = start - 2;

}
public void SetStart(int x)
start = x;
val = start;
prev = val - 2;

}
// , ISeries.
public int GetPrevious() {
return prev;

}
}
, G e t P r e v i o u s (),
, ISeries.
,
.
.

380

!. C#

,
. Primes,
. , ISeries
, By Two s.
// ISeries
// ,
class Primes : ISeries {
int start;
int val;
public P r i m e s () {
start = 2;
val = 2;

}
public int G e t N e x t O
int i, j;
bool isprime;

val++;
for(i = val; i < 1000000; i++)
isprime = true;
f o r (j = 2; j <= i/j; j++) {
if ( (i%j ) ==0) {
isprime = false;
break;

}
}
if (isprime)
val = i;
break;

}
}
return val;

}
public void R e s e t () {
val = start;

}
public void SetStart(int x)
start = x;
val = start;

}
}
, , By Twos Primes,
, ,
. , - ,
,
.

12. ,

381


, C#
, .. .
, .
,
.
, 11.

.
By Two s Primes.
, .
// ,
using System;
// ,
public interface ISeries {
int GetNe x t O ; //
void R e s e t (); //
void SetStart(int ) ; //

}
// ISeries
// ,
// ,
class ByTwos : ISeries {
int start;
int val;
public B y T w o s () {
start = 0;
val = 0;

}
public int GetN e x t O
val += 2;
return val;

}
public void R e s e t () {
val = start;

}
public void SetStart(int x)
start = x;
val = start;

}
}
// ISeries
// .

382

I. #

class Primes
int start;
int val;

: ISeries

public P r i m e s () {
start = 2;
val = 2;

}
public int G e t N e x t O
int i, j;
bool isprime;

val++;
for(i = val; i < 1000000; i++)
isprime = true;
for (j = 2; j <= i/j; j++) {
if ( (i % j )==0) {
isprime = false;
break;

}
}
if (isprime)
val = i;
break;

}
}
return val;

}
public void R e s e t () {
val = start;

}
public void SetStart(int x)
start = x;
val = start;

}
}
class SeriesDemo2 {
static void Main() {
ByTwos twoOb = new B y T w o s ();
Primes primeOb = new Prim e s ();
ISeries ob;
for(int i=0; i < 5; i++) {
ob = twoOb;
Console.WriteLine(" " + o b .GetNext()) ;
ob = primeOb;
Console.WriteLine(" " + " " + o b .GetNext())

12. ,

383

2
- 3
4
- 5
6
7
8
11
10
13

Main () ob ISeries.
, ,
ISeries. twoOb
primeOb ByTwos Primes ,
ISeries.

: ,
.
,
, .


, .
.
//
{

get;
set;

}
, ,
, : get set
.

, .
.
,
. ,
. ,
set private.
ISeries
ByTwos, Nex t
, .
// .
using System;

384

I. C#

public interface ISeries {


// ,
int Next {
get; //
set; //

}
}
// ISeries,
class ByTwos : ISeries {
int val;
public B y T w o s () {
val = 0;

}
// ,
public int Next {
get {
val += 2;
return val;

}
set {
val = value;

}
}
}
// ,
class SeriesDemo3 {
static void Main() {
ByTwos ob = new B y T w o s ();
// ,
for(int i=0; i < 5; i++)
Console.Write L i n e (" " + ob.Next);
Console.WriteLine(" 21");
ob.Next = 21;
for (int i=0; i < 5 ; i++)
Console.WriteLine(" " + ob.Next);

}.
}
.

2
4
6
8
10

21
23
25

12. ,

385

27
2 9
31


.
.
//
_ this[int ] {

get;
set;

}
, ,
, : get
set .

ISeries, , i-u
.
// ,
using System;
public interface ISeries {
// ,
int Next {
get; //
set; //

}
// ,
int this[int index] {
get; //

}
}
// ISeries,
class ByTwos : ISeries {
int val;
public B y T w o s () {
val = 0;

}
// ,
public int Next {
get {
val += 2;
return val;

386

I. C#
set {
val = value;

}
}
/ / ,
public int this[int index] {
get {
val = 0;
for(int i=0; i < index; i++)
val += 2;
return val;

}
}

// ,
class SeriesDemo4 {
static void Main() {
ByTwos ob = new B y T w o s ();
// ,
for (int i=0; i < 5; i++)
Console.W r i teLine(" " + ob.Next);
C onsole.Writ e L i n e (" 21");
ob.Next = 21;
for (int i=0; i < 5; i++)
Console.WriteLine(" " + ob.Next);
Console.WriteLine(" 0");
o b .Next = 0;
//
for (int i=0; i < 5; i++)
Console.W r i teLine(" " + ob[i]);

}
}
.

2
4
6
8
10

21




23
25
27
29
31

12. ,





387

2
4
6
8


.
, . ,
, ,
, .
// ,
using System;
public interface IA {
void M e t h l ();
void M e t h 2 () ;

}
// M e t h l () Meth2(),
// Meth 3 ( ) .
public interface IB : IA {
void M e t h 3 ();

}
// IA IB.
class MyClass : IB {
public void M e t h l () {
Console.WriteLine(" Methl().");

}
public void Meth2() {
Console.WriteLine(" M e t h 2 ().");

}
public void Meth3() {
Console.WriteLine(" M e t h 3 ().");

}
}
class IFExtend {
static void Main() {
MyClass ob = new M y C l a s s ();
ob.Methl() ;
ob.Meth2 ();
ob.M^th3();

388

I. #

Methl () MyClass.
. , ,
, ,
, , .


,
, .
,
, .
new,
.



.
, . , IMylF
interface IMylF {
int MyMeth(int x) ;

}
:
class MyClass : IMylF {
int IMylF.M y M e t h (int x)
return x / 3;

}
}
, MyMeth () IMylF
, .
. -,
,
,
, . ,
,
, . -,
,
.
.
.
IEven,
: IsEven () IsOdd ().
, . IEven
MyClass. IsOdd () .

12. ,

389

// ,
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 !.IsO d d ();

}
class Demo {
static void Main() {
MyClass ob = new M y C l a s s ();
bool result;
result = o b .IsEven (4);
if(result) Console.WriteLine("4 .");
// result = ob.IsOdd(4);

// , IsOdd IEven

// ,
// IEven MyClass,
// I s O d d ().
IEven iRef = (IEven) ob;
result = iRef.I s O d d (3);
if(result) Console.WriteLine("3 .");

}
}
IsOdd () , ,
MyClass. ,
.
IEven IsEven ().
, ,
Meth ().
, .
// .
using System;

390

I. C#

interface IMyIF_A {
int M e t h (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 _ o b ;
b_ob = this;
return b_ob.Meth(x); // IMyIF_B

}
}
class FQIFNames {
static void Main() {
MyClass ob = new M y C l a s s ();
Console.W r i t e (" IMyIF_A.M e t h (): ");
Console.WriteLine(ob.MethA(3));
Console.Write(" IMyIF_B.Meth(): ");
Console.WriteLine(ob.MethB(3));

}
}
.
IMyIF_A.Meth(): 6
IMyIF_B.Meth(): 9

,
M e t h () , I M y I F _ A
IMyIF_B. MyClass,
, .. Meth ().

12. ,

391

, M y C l a s s :
IMyIF_A, IMyIF_B.

, .


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

.NET Framework
.NET Framework ,
#. , S y s t e m .IComparable
Com p a r e T o (), ,
.
, ,
, . , System.
Collections .ICollection ,
System.Collections .IEnumerator
.
II .

, .
, ,
, .
, ,
. ( )

. C#
, , ,
.
struct
. :
struct : {
I I

}
.

392

!. #


. (, ,
#, obj e c t.)
,
. ,
: , , , , .
, .
, (..
). , , ,
.
, .
,
a b s t r a c t , v i r t u a l p r o te c te 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;

}
}
// Book,
class StructDemo {
static void Main() {
Book bookl = new B o o k (" ",
" ho C# 4.0",
2010); //
Book book2 = new Book(); //
Book ; //
Console.WriteLine(bookl.Author + ", " +
bookl.Title + ", (c) " + b o o k l .Copyright);
Console.WriteLine();
if (book2.Title == null)

12. ,

393

Console.WriteLine(" b o o k 2 .Title .");


// 2 .
book2.Title = " ";
book2.Author = " ";
b ook2.Copyright = 1932;
Console.Write(" book2 :\n");
Console.WriteLine(book2.Author + ", " +
book2.Title + ", (c) " + b o o k 2 .Copyright);
Console.WriteLine();
// Console.W riteLine(.Title); // ,
//
.Title = " ";
Console.WriteLine(.Title); //

}
}
.
,

C# 4.0,

book2.Title .
2 :
, ,

() 2010

() 1932

,
new
. , new,
, (
), ,
. new ,
, ,
, .
, .
.
, ,
,
.
,
. .
// .
using System;
// ,
struct MyStruct {
public int x;

394

I. C#

1 1 ,
class StructAssignment {
static void Main() {
MyStruct a;
MyStruct b;

a .x = 10;
b .x = 20;
Console.W r i teLine(" 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);

}
}
.
. 10, b.x 20
. 20, b.x 30

,
= ;

b - ,
.. b , ,
. ,
b ,
. ,
.
// ,
using System;
// ,
class MyClass {
public int x;

}
// ,
class ClassAssignment {
static void Main() {
MyClass a = new M y C l a s s ();
MyClass b = new M y C l a s s ();

a.x = 10;
b.x = 20;
Console.WriteLine(" a .x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;

12. ,

395

Console.WriteLine(" . {0}, b.x {1}", ., .);

}
}
.
. 10, . 20

. 30, . 30

, b ,
, .. ,
.


: C#
, , ?

. ,
, . ,
,
. ,
, .
, ,
.

,
. , ,
,
.
,
.
. ,
. .
,
,
.
// ,
using System;
// ,
struct PacketHeader {
public uint PackNum; //
public ushort PackLen; //

}
// PacketHeader
// ,
class Transaction {
static uint transacNum = 0;

396

I. #

PacketHeader ph; // PacketHeader Transaction


string accountNum;
double amount;
public Transaction(string acc, double val)
//
ph.PackNum = transacNum++;
ph.PackLen = 5 1 2 ; //

accountNum = acc;
amount = val;

}
// ,
public void sendTransaction()
Console.WriteLine(" #:
", :
",\n
", :

{
" + ph.PackNum +
" + ph.PackLen +
#: " + accountNum +
{0:C}\n", amount);

// ,
class PacketDemo {
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 ();
t 2 .sendTransaction ();
t 3 .sendTransaction ();

.
#: 0, : 512,
#: 31243, : ($100.12)
#: 1, : 512,
#: 4655, : $345.25
#: 2 , : 512,
#: 8475-091, : $9,800.00

PacketHeader
,
, . ,
PacketHe a d e r ,
, . ,
PacketHeader ,
.

12. ,

397

, C++
struct. , #. , C++

, ,
,
. C#
, .

.
enum.
:
enum { _ };

, _
, .
Apple
.
enum Apple { Jonathan,
Cortland,

GoldenDel, RedDel, Winesap,


McIntosh };

,
.
C# ,
, . ,
.
, , ,
switch for.

, , .

. , Apple
Jonathan , G o l d e n D e l 1, R e d D e l 2
..
,
-. ,
Console.WriteLine(Apple.RedDel + " " +
(int)Apple.RedDel) ;

.
RedDel 2

,
.
int.
,,
Apple.

398

I. C#

1 1 .

using System;
class EnumDemo {
enum Apple { Jonathan, GoldenDel, RedDel, Winesap,
Cortland, McIntosh };
static void Main() {
s t r i n g [] color = {
"",
"",
"",
"",
"",
"-"

};
Apple i; 1 1
// i
// .
for(i = A p p l e .Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " " + (int)i);
Console.WriteLine ();
// .
for(i = A p p l e .Jonathan; i <= Apple.McIntosh; i++)
Console.Writ e L i n e (" " + i + " " +
c o l o r [ (int)i]);

}
}
.
Jonathan
GoldenDel 1
RedDel 2
Winsap - 3
Cortland 4
McIntosh 5

Jonathan -
GoldenDel -
RedDel -
Winsap -
Cortland -
McIntosh - -

, Apple f o r .
Apple
, ,
.
,

12. ,

399

. , C#
,
.
: S y s t e m .Enum,
System. ValueType, , ,
object.



.
.
,
. ,
RedDel 10.
enum Apple { Jonathan, GoldenDel, RedDel = 10, Winesap,
Cortland, McIntosh };

0
1
10
11
12
13

Jonathan
GoldenDel
RedDel
Winesap
Cortland
McIntosh


int,
,
char. , int,
, .
byte Apple.
enum Apple

: byte { Jonathan, GoldenDel, RedDel,


Winesap, Cortland, McIntosh };

Apple .Winesap, ,
byte.


,
#, . ,

. ,
. Conveyor (),
: "", "", "" "".
Conveyor () , , 1

400

!. #

"", 2 "" , ,
,
. .
// ,
using System;
class ConveyorControl {
// .
public enum Action { Start, Stop,

Forward,

Reverse

};

public void Conveyor(Action com) {


switch(com) {
case A c t i o n .Start:
Console.Writ e L i n e (" .");
break;
case Action.Stop:
Console.Writ e L i n e (" .");
break;
case A c t i o n .Forward:
*
Console.WriteLine(" .");
break;
case A c t i o n .Reverse:
Console.WriteLine (" .");
break;

}
}
}
class ConveyorDemo {
static void Main() {
ConveyorControl = new ConveyorControl();
.Conveyor(ConveyorControl.A c t i o n .Start);
.Conveyor(ConveyorControl.Act i o n .Forward);
.Conveyor(ConveyorControl.Action.Reverse);
.Conveyor(ConveyorControl.Action.Stop);

}
}
.
.
.
.
.

Conveyor () Action,
, Action. ,
Conveyor () 22.
.C o n v e y o r (22); // !

,
int Action.
C o n v e y o r (). ,

12. ,

401

,
, .
,
Conveyor () ,
.

: sw itch .
, ,
sw itch .

, ,
.
#,

,
.
,
,

. ,

,
,
.
,
.
,
,
,
.
,
. ,

.

, C#
,
.

404

!. C#

.
C#
.

S ys te m . E x c e p tio n
C# .
C# Exception,
System. ,
Exception.

E x c e ption SystemException.
,
C# (.. CLR). SystemException
Exception, .
.NET Framework ,
SystemException. ,
DivideByZeroException.
, C# ,
Exception.


C#
: try, catch, throw finally. ,
.

.

. .
,
, try. try
, .
- ,
catch. , ,
.
throw. ,
try, finally.

t r y c a tc h
C#
try catch.
. try/catch

:
try {
// ,

13.

405

catch (E x ce p T y p e l exOb) {
// E x c e p T y p e l.

}
catch ( 2 exOb) {
// 2 .

.
try,
catch, .
catch. ,
, catch, ,
, .
, e x O b .
e x O b . ,
, ,
. .
, , e x O b
.
, , , ,
try , catch .
,
catch. , catch ,
.


,
. ,
. , CLR
IndexOutOfRangeException,
.NET Framework.
.
// .
using System;
class ExcDemol {
static void Main() {
i n t [] nums = new int [4];
try {
Console.W riteLine(" .");
// .
for(int i=0; i < 10; i++) {
n u m s [i ] = i ;

406

I. C#
Console.WriteLine("nums[{0}]:

{1}", i, nums[i]);

}
Console.W r i teLine("He ");

}
catch (IndexOutOfRangeException) {
// .
Console.W r i teLine(" !");

}
Console.Writ e L i n e (" .");

}
}
.
.
n u m s [0]:
n u m s [1]: 1
n u m s [2]: 2
n u m s [3]: 3
!
.

nums int .
0 9,
I n d e x O u t O f R a n g e E x c e p t i o n ,
4.
,
.
-, , ,
try. -, (
n u m s for),
t r y , catch.
t r y
catch. , c a t c h ,
. , ,
W r i t e L i n e O for,
, .
, ,
.
, c a t c h
( I n d e x O u t O f R a n g e E x c e p t i o n ) ,
. ,
, .

,
, .
,
.
, try, catch
, ,
for

13.

407

catch. ,

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


for(int i=0; i < nums.Length;

i++)

for.
, catch .


, , try,
, ,
try. ,
try, , , ,
.
, try
Main (). GenException (),
IndexOutOfRangeException.
GenException (). GenException ()
try Main (), catch,
try.
/*
. */
using System;
class ExcTest {
// ,
public static void GenException() {
i n t [] nums = new int [4];
Console.WriteLine(" .");
//
.
for(int i=0; i < 10; i++) {
n u m s [i ] = i ;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);

}
Console.WriteLine("He ");

}
}
class ExcDemo2 {
static void Main()

try {
ExcTest.GenException() ;

408

!. C#
}
catch (IndexOutOfRangeException) {
// .
9
Console.Wr i t e L i n e (" !");

}
Console.Write L i n e (" .");

}
}
,
.
.
n u m s [0]:
n u m s [1]: 1
n u m s [2]: 2
n u m s [3]: 3
!
.

, GenException () try,
, catch
Main (). GenException (),
Main ().


, ,
: .
, -
. ,
, .
,
. ,
.
// C# .
using System;
class NotHandled {
static void Main() {
i n t [] nums = new i n t [4];
Console.Writ e L i n e (" .");
// ,
for (int i=0; i < 10; i++) {
n u m s [i ] = i ;
Console.Wr i t e L i n e (" nums[{0}] : {1}", i, nums[i]);

13.

409

,
.
: System.IndexOutOfRangeException:
,
NotHandled.Main() <_> : 16

N o t H a n d l e d .Main ()
System. IndexOutOfRangeException,
.
, ,
, !
.
,
, catch.
. ,
catch,
DivideByZeroException,
. ,
IndexOutOfRangeException,
catch, .
// !
using System;
class ExcTypeMismatch {
static void Main() {
i n t [] nums = new int [4];
try {
Console.WriteLine(" .");
// ,
for(int i=0; i < 10; i++) {
n u m s [i ] = i ;
Console.W r i teLine(" nums[{0}]: {1}", i, nums[i]);

}
Console.WriteLine("He ");

}
/* DivideByZeroException,
. */
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");

}
Console.WriteLine(" .");

}
}
.

410

I. C#

.
n u m s [0]:
n u m s [1]: 1
n u m s [2]: 2
n u m s [3]: 3
: System.IndexOutOfRangeException:

ExcTypeMismatch.Main() <_>: 18

, catch,
D i v i d e B y Z e r o E x c e p t i o n ,
IndexOutOfRangeException.

-


,
. ,
.
, DivideByZeroException.
,
. ,
-
. "",
.
// .
using System;
class ExcDemo3 {
static 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 < n u m e r .Length; i++) {
try {
Console.WriteLine(numer[i] + " / M +
denom[i] + M +
n u m e r [i ]/denom[i ]);

}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");

}
}
}
}
.

13.

411

4 / 2 2
!
1 6 / 4 4
3 2 / 4 8
-!
128 / 8 16

:
, .
t r y fo r, ,
.
.

c a tc h
t r y c a tc h .
. c a tc h
. ,
.
// catch.
using System;
class ExcDemo4 {
static void Main() {
// numer denom.
i n t [] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < n u m e r .Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
n u m e r [i ]/denom[i ]) ;

}
catch (DivideByZeroException) {
Console.WriteLine(" !");

}
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");

}
}
}
}
.
4 / 2 2
!
1 6 / 4 4
3 2 / 4 8
!

412

I. C#

128 / 8 16
.
.

, catch
.
, c a t c h
. c a tc h ,
. c a t c h
.



. catch,
. .
catch {
//

}
""
, .
"" .
, ,
IndexOutOfRangeException DivideByZeroException, . .
// "" .
using System;
class ExcDemo5 {
static 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 < num e r .Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
nu m e r [i ]/ denom[i ]);

}
catch { // "" .
Console.WriteLine (" .");

}
}
}
}
.
4 / 2 2
.

13.

413

1 6 / 4 4
3 2 / 4 8
.
128 / 8 16
.
' .

"" , ,
' catch.


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

t r y
try . ,
try catch,
try. ,
IndexOutOfRangeException ,
try.
// try.
using System;
class NestTrys {
static 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 };

};

try { // try
for(int i=0; i < n u m e r .Length; i++) {
try { // try
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
num e r [i ]/denom[i ]);

}
catch (DivideByZeroException) {
Console.W r i teLine(" !");

41 4

I. C#
catch (IndexOutOfRangeException) {
Console.W r i teLine(" .");
Console.WriteLine(" - .");

}
}
}
.
4 / 2 2
!
1 6 / 4 4
3 2 / 4 8
!
128 / 8 16
.
- .

, t r y
- ,
. , t r y ,
.
,
tr y ,
. t r y
. ,
,
. , t r y
, t r y
. , t r y ""
, .


,
.
throw.
:
throw e x c e p t O b ;

e x c e p t O b ,
Exception.
,
throw DivideByZeroException.
// .
using System;
class ThrowDemo {
static void Main()
try {

13.

4 15

Console.WriteLine(" .");
throw new DivideByZeroException();

}
catch (DivideByZeroException) {
Console.W r i teLine(" .");

}
Console.WriteLine(" try/catch.");

}
}
.
.
.
try/catch.

, D i v i d e B y Z e r o E x c e p t i o n
n ew throw.
, , ,
. ,
.
DivideByZeroException ,
, .


, catch,
, catch.

. ,
- ,
.
throw , .
throw ;

, , , ,
catch,
catch.


.
IndexOutOfRangeException.
// .
using System;
class Rethrow {
public static 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; icnumer.Length;

i++)

};

I. C#

416

try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
n u m e r [i ]/denom[i ]);

}
catch (DivideByZeroException) {
Console.Writ e L i n e (" !");

}
catch (IndexOutOfRangeException) {
Console.W r i teLine(" .");
throw; //

}
}
}
}
class RethrowDemo {
static void Main() {
try {
R ethrow.GenException ();

}
catch(IndexOutOfRangeException) {
//
Console.Writ e L i n e (" - .");

}
}
}
-
G e n E x c e p t i o n (),
. IndexOutOfRangeException
Main ().

f i n a l l y
,
try/catch. ,
, .
, ,
, .
, C# :
finally.
,
try/catch, finally
try/catch. try/
catch finally.
try {
// ,

}
catch (E x c e p T y p e l exOb) {
// E x c e p T y p e l.

13.

417

}
catch ( 2 ) {
// 2 .

finally {
// .

}
fin a lly , t r y /
c a tc h , , . ,
t r y ,
, fin a lly . f in a lly ,
t r y c a t c h
.
fin ally .
// finally.
using System;
class UseFinally {
public static void GenException(int what)
int t;
i n t [] nums = new int [2];

Console.WriteLine(" " + what);


try {
switch(what) {
case 0:
t = 10 / what; // -
break;
case 1:
n u m s [4] = 4 ; //
break;
case 2:
return; // try

}
}
catch (DivideByZeroException) {
Console.W riteLine(" !");
return; // catch

}
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");

}
finally {
Console.W riteLine(" try.");

}
}
}

418

I. C#

class FinallyDemo {
static void Main()

for(int i=0; i < 3; i++) {


UseFinally.GenException(i);
Console.WriteLine() ;

}
}
}
.


try.
1
.
try.
2
try.

, finally
try.
: finally
try, catch . , finally
try, catch.
finally try,
.

E x c e p tio n
,
. ,
catch .
. ,
Exception,
.
Exception
.
E x c e p t i o n .
: Message, StackTrace Targetsite.
. M e s s a g e ,
; StackTrace ,
, get Site ,
, .
, Exception .
ToString (),
. , ,
WriteLine ().

13.

419

E x c e p tio n
.
// Exception.
using System;
class ExcTest {
public static void GenException() {
int[] nums = new int [4];
Console.WriteLine(" .");
// ,
for(int i=0; i < 10; i++) {
n u m s [i ] = i ;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);

}
Console.WriteLine("He ");

}
}
class UseExcept {
static void Main() {
try {
ExcTest.GenException();

}
catch (IndexOutOfRangeException exc) {
Console.WriteLine(" : ");
Console.WriteLine(exc); // T o S tringO
Console.WriteLine(" StackTrace: " + e x c .StackTrace);
Console.WriteLine(" Message: " + exc.Message);
Console.WriteLine(" TargetSite: " + e x c .TargetSite);

}
Console.WriteLine(" .");

}
}
.
.
n u m s [0]: 0
n u m s [1]: 1
v
n u m s [2]: 2
n u m s [3]: 3
: System.IndexOutOfRangeException:
.
ExcTest.genException() <_> : 15
UseExcept.Main() <_> : 2 9
StackTrace: ExcTest.genException() <_> : 15
UseExcept.Main() <_> : 2 9
Message:
.
TargetSite:
Void genException ()
.

420

I. C#

Exception .
public Exception ()
public Exception(string )
public Exception(string , Exception _)
protected Exception(System.Runtime.Serialization.Serializationlnfo ,
System.Runtime.Serialization.StreamingContext )

.
, Message,
.
. ,
, _
, , .
( ,
InnerException, Exception.)
, ,
.
, E x c e p t i o n
Se rializationlnfo S t reamingContext System.
R u n t i m e .Serialization.


Sys t e m ,
. SystemException,
CLR
. . 13.1
.

13.1. ,
System

A rrayTypeMismatchEx c e p t i o n





. ,
, ,
new

, .. , ___________

D ivideByZeroException
I ndexOutOfRangeException
InvalidCastException
O utOfMemoryException

OverflowException
NullReferenceExcept i o n

, . 13.1, ,
NullReferenceException.

13.

421

, ,
. ,
. , , ,
,
null. ,
. ,
NullReferenceException.
// 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 {
static void Main() {
X p = new X (10);
X q = null; // q
int val;
try {
val = p.Add(q); //
} catch (NullReferenceException) {
Console.WriteLine(" NullReferenceException!");
Console.W r i teLine(" ...\n");
// ,
q = new X (9);
val = p .Add(q);

}
Console.WriteLine(" val {0}", val);

}
}
.
NullReferenceException!
...
val 19

X,
Ad d (),

422

I. C#

, .
X Main (). ( )
, ( q) . q
. . A d d () q
. q ,
q. NullReferenceException.



, C#
.
C# ,
, , .. ,
#. ,
, .
, Exception.
-
, .



. Microsoft
, , Exception.
.

Application.Exception,


, Exception . ,
Exception .
, , , ,
, Exception.
,

Exception, base.
, .
,
. , 10 RangeArray,
,
. , , ,
-5 27. ,
Ran g e A rr a y .

, RangeArray. ,
"" .
RangeArray

13.

423


.
//
// - RangeArray.
using System;
// RangeArray.
class RangeArrayException : Exception {
/* Exception.
.
RangeArrayException Exception,
. */
public RangeArrayException() : base() { }
public RangeArrayException(string str) : base(str) { }
public RangeArrayException(
string str, Exception inner) : base(str, inner) { }
protected RangeArrayException(
System.Runtime.Serialization.SerializationInf si,
System.Runtime.Serialization.StreamingContext sc) :
base(si, sc) { }
// ToStringO RangeArrayException.
public override string ToSt r i n g O {
return Message;

// RangeArray.
class RangeArray {
// .
i n t [] a; //
int lowerBound; //
int upperBound; //
// Length,
public int Length { get; private set; }
//
public RangeArray(int low, int high) {
high++;
if(high <= low) {
throw new RangeArrayException(" .");

}
= new int[high - low];
Length = high - low;
lowerBound = low;
upperBound = high;

}
// RangeArray.
public int this[int index] {

424

I. C#
// get.
get {
if(ok(index)) {
return a[index - lowerBound];
} else {
throw new RangeArrayException(" .")

}
}
// set.
set {
if(ok(index)) {
a[index - lowerBound]

= value;

}
else throw new RangeArrayException("

}
}
// true,
// ,
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return false;

return true;

}
}
//
// ,
class RangeArrayDemo {
static void Main() {
try {
RangeArray ra = new RangeArray(-5, 5);
RangeArray ra2 = new RangeArray(1, 10);
i

// .
Console.WriteLine(" : - + .Length);
for(int i = -5; i <= 5; i++)
r a [i ] = i;
Console.W r i t e (" ra:
for (int i = -5; i <= 5; i++)
Console.Write(ra[i] + " ");

");

Console.W r i teLine("\n");
// ra2 .
Console.Wri t e L i n e (" 2 : " + ra2.Length);
for (int i = 1; i <= 10; i++)
r a 2 [i ] = i;
Console.W r i t e (" r a 2 : ");
for (int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " ");

13.

425

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++)
ra3[i] = i;
Console.Write(" : ");
for (int i = -2; i <= 10; i++) //
Console.Write([i] + " ");
} 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 1 0
.
.
: - 2 - 1 0 1 2 .

RangeArray,
RangeArrayException. RangeArray
: get , set
RangeArray.
, R a n g e A r r a y
try, .
, R a n g e A r r a y
C# ,
, .

426

I. C#

,
RangeArrayException - ,
Exception, base.

, ,
,
Exception.
- , Exception.
,
. ,
ToString () . ,
, , ,
, #.


, ,
,
catch,
. ,
Exception ,
Exception
. ,
catch
.
, .
,
catch,
. ,

. , :
catch, ,
.
:
E x c e p t A ExceptB. E x c e p t A Exception,
ExceptB ExceptA.
.
, ,
.
,
Exception.
//
// .
using System;
// ,
class ExceptA : Exception {
public ExceptA(string str)

: base(str)

{ }

13.
public override string ToStringO
return Message;

427

}
}
// , ExceptA.
class ExceptB : ExceptA {
public ExceptB(string str) : base(str) { }
public override string ToStringO {
return Message;

}
}
class OrderMatters {
static void M a i n () {
for(int x = 0; x < 3; x++) {
try {
if (x==0) throw new Exc e p t A (" ExceptA");
else if(x==l) throw new ExceptB("
ExceptB");
else throw new Exce p t i o n ();

}
catch (ExceptB exc) {
Console.WriteLine(exc);

}
catch (ExceptA exc) {
Console.WriteLine(exc);

}
catch (Exception exc) {
Console.WriteLine(exc);

}
}
}
}
.
ExceptA.
ExceptB.
System.Exception: "System.Exception".
OrderMatters.Main() <_> : 3 6

catch.
. E x c e p t B
ExceptA, ExceptB
ExceptA. , Exception (..
) . ,
catch.
.
c a tc h ,
, . ,
.
, ,
,
.

428

I. C#

checked unchecked
C# , ,
.
,
, .
.
.
byte a, b, result;
= 127;
= 127;
result =

(byte)( * b ) ;

b
b y te . ,
,
re s u lt.
C# ,
, checked unchecked. ,
, ,
ch eck ed ,
unchecked. ,
.
ch eck ed .
, .
, .
:
checked

()

checked {
//

}
.
,
OverflowException.
unchecked . ,
.
, :
unchecked

()

unchecked {
// ,

}
,
. ,
.

13.

429

,
checked unchecked.
// checked unchecked.
using System;"
class CheckedDemo {
static void Main()
byte a, b;
byte result;

a = 127;
b = 127;
try {
result = unchecked((byte) (a * b ) );
Console.WriteLine(" : " +
result);
result = checked((byte)(a * b ) ); //
//
Console.WriteLine(" : " +
result); / /

}
catch (OverflowException exc)
Console.WriteLine(exc);

}
}
}
.
: 1
System.OverflowException:
.
CheckedDemo.Main() <_> : 2 0

, .
.

checked unchecked .
,
.
// checked
// unchecked .
using System;
class CheckedBlocks {
static void Main() {
byte a, b;
byte result;
a = 127;
b = 127;

430

I. C#
try {
unchecked {
a = 127;
b = 127;
result = unchecked((byte)(a * b ) );
Console.WriteLine(" :
result);
= 125;
b = 5;
result = u nchecked((byte)(a * b ) );
C onsole.W riteLine(" :
result);

" +

" +

}
checked {
a = 2;
b = 7;
result = chec k e d ((byte)(a * b ) ); //
Console.W r i teLine(" :
result);

" +

= 127;
b = 127;
result = c h e c k e d ((byte)(a * b ) ); //
//
Console.WriteLine(" : " +
result); / /

.}
catch (OverflowException exc)
Console.WriteLine(exc);

}
}
}
.
: 1
: 113
: 14
System.OverflowException:
.
CheckedDemo.Main() <_> : 41

,
.
, .
ch ecked unchecked
, , ,

.
.


-
,
,
- #, C o n s o l e .
W r i t e L i n e (), -
. - C#
,
,
, .
-. C# -
, .NET Framework,
-
- .NET .

-. , ,
, - C# .

.

C#
- C#
.
.
-.

.
-
. ,
.

432

!. C#


- C# .
, -
. . , C#
char 16-, byte 8-. , ASCII, char
byte char.
(Unicode), ,
. ,
- .
.NET Framework ,
byte
char .


, System,
, Console. In, Console.Out
Console.Error. , C o n s o l e . O u t
. . ,
C onsole .WriteLine (), C o n s o l e .
Out. Console. In ,
. C o n s o l e . E r r o r
,
.
-. .
.


.NET Framework ,
.
,
. ,
, .
System. 10.
, ,
.
using System.10;

System. 10 -
, Console System.

S tream

'

S y s t e m .10. Stream.
. ,

14. -

433

, ,
Stream . S t ream
, . . 14.1
, Stream.

14.1. , stream

void Close ()


, .
-1
c o u n t
b u f f e r , b u f f e r [ o f f s e t ] .


o f f s e t
o r i g i n .


c o u n t
b u f f e r , b u f f e r ' i o f f s e t ] .

void F l u s h ()
int R e a d B y t e ()

int R e a d ( b y t e [] b u f f e r ,
int o f f s e t , int c o u n t )
long Seek(long o f f s e t ,
SeekOrigin o r i g i n )

void WriteByte(byte

value)

void W r i t e ( b y t e []b u f f e r ,
int o f f s e t ,
int c o u n t )

, . 14.1,
IOException -.

, ,
, N o t S u p p o r t e d E x c e p t i o n .
,
.
, Stream ( )
( ) . ,
.
,
Seek (). ,
, Stream.
. 14.2 Length Position,
.

14.2. , Stream

bool CanRead

true, .

true, . ______________

bool CanSeek

434

I. C#
. 14.2

bool CanWrite
long Length
long Position
int ReadTimeout
int' WriteTimeout

true, .

.
. ,


. ,

. ,


Stream
. System. 10 .


BufferedStream
FileStream
M emoryStream
UnmanagedMemoryStream


. , ,
,
,
,

NET Framework
, - , . ,
,
.

-

- .
T e x t R e a d e r TextWriter. ,
T e x t R e a d e r , T e x t W r i t e r . ,
, .
-, .
. 14.3 , TextReader.
, IO E x c e p t i o n
, .
ReadL i n e (), ,
string. ,
. T e x t R e a d e r Close (),
.
void Close()

14. -

435

14.3. , T e x t R e a d e r

int P e e k ()

int R e a d ()

int R e a d (c h a r []b u f f e r ,
int i n d e x , int c o u n t )

int R e a d B l o c k ( c h a r []b u f f e r ,
int i n d e x ,
int c o u n t)
string R e a d L i n e O

string R e a d T o E n d O

,
. -1,



.
-1
c o u n t
b u f f e r ,
b u f f e r [ i n d e x ] ,

c o u n t
b u f f e r ,
b u f f e r [ i n d e x ],


string.

, , string_____________

TextWriter Write () WriteLine (),


.
.

int
double
void Write (bool v a l u e )
bool
void WriteLine (string v a l u e ) s t r i n g

void WriteLine (uint v a l u e )
uint

void WriteLine (char v a l u e )

________________________________ ______________________________________
void Write (int v a l u e )

void Write (double v a l u e )

I O E x c e p t i o n
.
, T e x tWriter Close () Flush (),
.

436

I. C#

virtual void Close()


virtual void Flush()

F l u s h () ,
. Close ()
.
T ex tR ea de r T extWriter
, , . ,
, T e x t R e a d e r
TextWriter.

StreamReader

.

.


________

StreamWriter
StringReader
StringWriter


,
,
BinaryReader BinaryWriter.
, -.
, - #,

, -.

- ,
C on so le .In, Con so le .Out Co ns ol e.Error.
- 2, .
, .
,
C# - ,
,
, .
-, , .
, -,
,
, .


C o n s o l e .In TextReader,
,

14. -

437

Text Reader. ,
Console,
C o n s o l e .In. Console . ,
Read () Re ad L i n e ( ) , .NET Framework 1.0.
, ReadKey (), 2.0 .
Read ().
static int Rea d ()

Re ad () , .
, , .
int
char. , R e a d () -1.
IOException
. Rea d () ,
<Enter>,
, .
, R e a d ()
, .
// , .
using System;
class {
static void Main()
char ch;

Console.Write(" , <ENTER>: ");


ch = (char) Console.Read(); // char
Console.WriteLine(" : " + ch) ;

}
}
, , .
, <ENTER>: t
: t

, ^
Read (), .
<Enter>
. ,
, . ,
( ),
. ,
, ReadKey ( ) .
ReadLine ().
static string ReadLine()

R e a d L i n e () ,
<Enter>,

438

I. C#

string. , IOException
.
,
Console .In ReadLine ().
// ReadLine().
using System;
class ReadString {
static void Main()
string str;

Console.WriteLine(" .");
str = Console.ReadLine();
Console.WriteLine(" : " + str);

}
}
, , .
.
.
: .

, Console. In
Console.
TextReader.
, Rea.dLine (),
TextReader.
//
// Console.In.
using System;
class ReadChars2 {
static void Main()
string str;

Console.WriteLine(" .");
str = Console.In.ReadLine(); // ReadLine() TextReader
Console.WriteLine(" : " + str);

}
}
, ReadLine ()
Console .In. ,
TextReader, C o n s o l e .In,
, .

ReadKey ()
.NET Framework , Console

. ReadKey ().

14. -

439

ReadKey ()
.
<Enter>. , Rea dK ey ()
.
ReadKey ().
static ConsoleKeylnfo ReadKey()
static ConsoleKeylnfo ReadKey(bool in t e r c e p t )

.
, .
,
. i n t e r c e p t true,
. i n t e r c e p t false,
.
R e a d K e y ()
ConsoleKeylnfo, ,
, .
char KeyChar
ConsoleKey Key
ConsoleModifiers Modifiers

K ey Ch ar char ,
Key C o n s o l e K e y ,
Modifiers (<Alt>, <Ctrl>
<Shift>), , ,
.
Co nsoleModifiers : Control, Shift Alt.
Mo di fi er s
.
ReadKey () ,
,
.
, .
// , , ReadKey().
using System;
class ReadKeys {
static void Main() {
ConsoleKeylnfo keypress;
Console.WriteLine(" , " +
" - <Q>.");
do {
keypress = Console.ReadKey(); //
Console.WriteLine(" : " + keypress.KeyChar);
// .
i f ((ConsoleModifiers.Alt & keypress.Modifiers) != 0)
Console.WriteLine(" <Alt>.");
i f ((ConsoleModifiers.Control & keypress.Modifiers) != 0)

440

I. C#
Console.WriteLine(" <Control>.");
i f ((ConsoleModifiers.Shift & keypress.Modifiers) != 0)
Console.WriteLine(" <Shift>.");
} while(keypress.KeyChar != 'Q');

}
}
, , .
, - <Q>.
:
b : b
d : d
:
<Shift>.
:
<Shift>.
:
<Shift>.
:
<Control>.
Q : Q
<Shift>.

, ,
, Rea dK ey () .*
Read (),
.
, ReadKey ().


C on so le .Out Console .Error TextWriter.
W r i t e ()
WriteLine (), .
. Console
Write() n W r i t e L i n e ( ) , n
Console,
.
TextWriter, Console .Out Console .Error.
,
C on s o l e .Out C o n s ol e .Error.
.
// Console.Out Console.Error.
using System;
class ErrOut {
static void Main()
int a=10, b=0;
int result;

Console.Out.WriteLine(" " +
" .");

14. -

441

try {
result = / b; //
} catch(DivideByZeroException exc) {
Console.Error.WriteLine(exc.Message);

}
}
}
.
.
.


Console.Error. : ,
Console .Out Console .Error, ,
? ,
. ,
Console .Error , . ,
, ,
, . , , ,
, .
-.

F ile S tre a m -
.NET Framework -
. , .
. , ,
.
. ,

. -
. ,
-.
, , FileStream.
Stream .
, , FileStream,
System. 10.
.
using System.10;


, ,
FileStream. .
:
FileStream(string , FileMode )

442

I. #

, ;
. ,
F i l e M o d e . 14.4. ,
.
FileM od e .Append,
.

14.4. FileM ode

F i l e M o d e .Appen d


.

.


, .

,

F i l e M o d e .Create
F i l e M o d e .CreateNew
F i l e M o d e .Open
F i l e M o d e .OpenOrCreate
F i l e M o d e .Truncate

,
. - ,
F i l e N o t F o u n d E x c e p t i o n . - -, IOException.
,
, : A r g u m e n t N u l l E x c e p t i o n ( ),
ArgumentException ( ), ArgumentOutOfRangeException
( ), S e a u r i t y E x c e p t i o n (
), P a t h T o o L o n g E x c e p t i o n ( ),
No tS up po rt ed Ex ce pt io n ( ,
), D ir ec to ryNotFoundException ( ).
P a t h T o o L o n g E x c e p t i o n , D i r e c t o r y N o t F o u n d E x c e p t i o n
FileNotFoundException IOException.
,

IOException.

t e s t .dat
.
FileStream fin;
try {
fin = new FileStream("test", FileMode.Open);

}
catch(IOException exc) { // , -
Console.WriteLine(exc.Message);
// .

}
catch(Exception exc { // .
Console.WriteLine(exc.Message);
// , .

14. -

443

// .

}
c a tc h ,
, , ,
, -. c a tc h ,
"7' ,
(, ).
, ,
.
, ,
IOException, , ,
, -,
. , ,
, ,
, .
, ,
. , .
, F i l e S t r e a m ,
.
, .
FileStream(string , FileMode , FileAccess )

, ,
, .
. ,
F i l e A c c e s s .
F i l e A c c e s s .R e a d .

F i l e A c c e s s .W r i t e

F i l e A c c e s s .R e a d W r i t e

, t e s t .d a t
.
FileStream fin = new FileStream("test.dat", FileMode.Open, FileAccess.Read);

, C l o s e ().
.
void Close()

,
, . ,
C l o s e () , , D i s p o s e (), , ,
.

using, 20,
, .
,
. ,
, , ,
, Close ().

444

I. C#

-
F i l e S t r e a m :
R e a d B y t e () R e a d (). ,
ReadByte (), .
int ReadByte()

, , ,
. ,
, N o t S u p p o r t e d E x c e p t i o n (
) O bj ec tD isp osedException ( ).
Read (),
.
int Read(byte[ ] a r r a y , int o f f s e t ,

int count)

R e a d () c o u n t
a r r a y , a r r a y [ o f f s e t ] .
, . -,
IOException. ,
, NotSupportedException.
, .
R e a d B y t e ()
,
. ,
, , .
/* .
, ,
. ,
TEST.CS :
ShowFile TEST.CS

*/
using System;
using System.10;
class ShowFile {
static void Main(string[] args)
int i;
FileStream fin;

if(args.Length != 1) {
Console.WriteLine(": ShowFile ");
return;

}
try {
fin = new FileStream(args[0], FileMode.Open);
} catch(IOException exc) {
Console!WriteLine("He ");
Console.WriteLine(exc.Message);
return; // ,

14. -

445

}
// ,
try {
do {
i = fin.ReadByte();
if(i != -1) Console.Write((char) i);
} while(i != -1);
} catch(IOException exc) {
Console.WriteLine(" ");
Console.WriteLine(exc.Message) ;
} finally {
fin.Close() ;

}
}
}
,
t r y . , .
-, .
t r y , . , t r y ,
f i n . ,
f i n a l l y , t r y .
, , d o -w h ile (
- ), .
, ,
, , ,
f i n a l l y
- - .
,
, tr y ,
. ,
ShowFile.
// .
using System;
using System.10;
class ShowFile {
static void Main(string[] args)
int i;
FileStream fin = null;

if (args.Length != 1)' {
Console.WriteLine(": ShowFile File");
return;

}
// try

446

I. C#
try {
fin = new FileStream(args[0], FileMode.Open);
// ,
do {
i = fin.ReadByte();
if(i != -1) Console.Write((char) i);
} while (i != -1);
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
if(fin != null) fin.Close();

}
}
}
, f i n
F i l e S t r e a m .
F ile S tr e a m ,
f in , . ,
C lo se () f i n a l l y ,
f i n .
lo s e () fin ,
.
-, .
, , , , ,
, . ,
, , ,
, t r y ,
.
, ,
. , ,
.
.


W r i t e B y t e ( ) .
.

void WriteByte(byte valu e)

, v a l u e .
,
N o t S u p p o r t e d E x c e p t i o n . ,
O b jectD isp o se d E x ce p tio n .
W rite .
.
void Write(byte[] array, int o f f s e t , int count)

W rite () c o u n t
a r r a y , a r r a y [ o f f s e t ] .

14. -

447

, . ,
IOException.
, NotSupportedException. ,
.
, , ,
.
,
, .
. ,
128 . ,
.
.

, Flush.
void Flush()

IOException.
, ObjectDisposedException.
C lo se ().
, ,
, .
Flush () .
,
.
// .
using System;
using System.10;
class WriteToFile {
static void Main(string[] args)
FileStream fout = null;

try {
// .
fout = new FileStream("test.txt", FileMode.CreateNew);
// ,
for(char = ' ' ; <= ' Z ' ; C++)
fout.WriteByte((byte) );
} catch(IOException exc) {
Console .WriteLine (." -:\n" + exc .Message) ;
} finally {
if(fout != null) fout.Close();

}
}
}
t e s t .txt
FileMode .CreateNew. ,
. (
IOException.)

448

I. C#

.
t e s t . t x t .
ABCDEFGHIJKLMNOPQRSTUVWXYZ

F ile S tre a m
- F ile S tream
, , , ,
. ,
, .
.
/* .
,
. , FIR'ST.DAT SECOND.DAT
:
CopyFile FIRST.DAT SECOND.DAT

*/
using System;
using System.10;
class CopyFile {
static void Main(string[] args)
int i;
FileStream fin = null;
FileStream fout = null;

if(args.Length != 2) {
Console.WriteLine(": CopyFile ");
return;

}
try {
1
// .
fin = new FileStream(args[0], FileMode.Open) ;
fout = new FileStream(args[1] , FileMode.Create);
// ,
do {
i = fin.ReadByte();
if(i != -1) fout.WriteByte((byte)i);
} while (i != -1);
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
if(fin != null) fin.Close ();
if(fout != null) fout.Close ();

14. -

449

-
,
.
, . ,
,
. , -
FileStream StreamReader
StreamWriter.
.
, , ,
. S t r e a m R e a d e r S t r e a m W r i t e r
.
S t r e a m W r i t e r tW r i t e ,
S t r e a m R e a d e r Te xtReader. ,
StreamReader Str ea mW ri te r ,
.

S tre a m W rite r

Stream, F i l e S t r e a m , S t r e a m W r i t e r .
Stre am Wr it er .
:
StreamWriter(Stream )

.
ArgumentException, ,
ArgumentNullException, .
StreamWriter .

, t e s t .txt.
, "".
FileStream,
StreamWriter.
// ,
// StreamWriter.
using System;
using System.10;
class KtoD {
static void Main()
string str;
FileStream fout;

// -,
try {
fout = new FileStreamC'test.txt", FileMode.Create) ;

450

I. C#
catch(IOException exc) {
Console.WriteLine(" :\" + exc.Message);
return ;

}
// - StreamWriter.
StreamWriter fstr_out = new StreamWriter(fout) ;
try {
Console.WriteLine(" , ''.");
do {
Console.Write (": ");
str = Console.ReadLine();
if(str != "") {
str = str + "\r\n"; //
fstr_out.Write(str);

}
} while(str != "");
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
fstr_out.Close();

}
}
}

StreamWriter. :
StreamWriter(string )
StreamWriter(string , bool append)

, .
a p p e n d true,
.
.
, . IOException. ,
.

, ,
StreamWriter.
// StreamWriter.
using System;
using System.10;
class KtoD {
static void Main() {
string str;
StreamWriter fstr_out = null;
try {
// , StreamWriter.

14. -

451

fstr_out = new StreamWriter("test.txt");


Console.WriteLine(" , ''.");
do {
-Console.Write (": ");
str = Console.ReadLine ();
if(str != "") {
str = str + "\r\n"; //
fstr_out.Write(str);

}
} while(str != "");
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
if(fstr_out != null) fstr_out.Close() ;

}
}
}

Stream R eader

StreamReader. S t r ea mR ea de r
. :
StreamReader(Stream )

.
ArgumentNullException, ,
ArgumentException, .
StreamReader .
StreamReader .
.

t e s t .txt.

.
// ,
// StreamReader.
using System;
using System.10;
class DtoS {
static void Main()
FileStream fin;
string s;

try {
fin = new FileStream("test.txt", FileMode.Open);

452

I. C#
catch(IOException exc) {
Console.WriteLine(" :\" + exc.Message);
return;

}
StreamReader fstr_in = new StreamReader(fin);
try {
whi l e ((s = fstr_in.ReadLine())
Console.WriteLine(s);

!= null)

}
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
fstr_in.Close();

}
}
}
, .
R e a d L i n e () , ,
. , S t r e a m R e a d e r
EndOfStream.
true,
, false. ,
EndOf Stream .
while .
while(!fstr_in.EndOfStream)
s = fstr_in.ReadLine();
Console.WriteLine(s);

}
EndOf Stream,
.
En dO f Stre am ,
.
, StreamReader,
StreamWriter. :
StreamReader(string )

, .
.
FileNotFoundException. ,
ArgumentNullException. ,
ArgumentException. ,
IOException DirectoryNotFoundException.


, , Console. In,
. .

14. -

453

,
, .

,
.
. ,

< >, Console .In Console .Out .
, .
using System;
class Test {
static void Main() {
Console.WriteLine(" .") ;

}
}

Test > log

" ." log.


.
, "".
< >, ,
#, .
-, , , Windows,
,
. ,
.
Setln (), SetOut () Se tE rr or (),
Console.
static void Setln(TextReader __)
static void SetOut(TextWriter __)
static void SetError(TextWriter ____)

, Setln ()
. ,
, TextReader.
SetOut () ,
TextReader. ,
FileStream,
StreamWriter. .
// Console.Out.
using System;
using System.10;
class Redirect {
static void Main() {
StreamWriter log_out = null;

454

I. C#
try {
log_out = new StreamWriter("logfile.txt");
// logfile.txt.
Console.SetOut(log_out);
Console.WriteLine(" .");
for(int i=0; i<10; i++) Console.WriteLine(i);
Console.WriteLine(" .");
} catch(IOException exc) {
Console.WriteLine(" -\" + exc.Message);
} finally {
if(log_out != null) log_out.Close();

}
}
}
,
l o g f i l e . t x t .
.
0
1
2

3
4
5

6
7
8

9
.



. ( )
. , ,
int, double short.
C# B i n a r y R e a d e r n B i n a r y W r i t e r .
, ,
, .

B in a r y W r i t e r
Bi n a r y W r i t e r , ,
.
:

14. -

455

BinaryWriter(Stream ou tp u t)

o u t p u t , .
o u t p u t ,
FileStream. o u t p u t ,
ArgumentNullException. ,
o u t p u t , ,
ArgumentException. B in ar yW ri te r
. .
BinaryWriter ,
C# . . 14.5.
, string
. , BinaryWriter
Close() Flush (), .

14.5. , B in a r y W r it e r

void Write(sbyte v a l u e )

sbyte
byte
byte
short
( )
ushort
( )
int
ui n t
( )
long
( )
ulong
( )
float (
)
double (
)
decimal (
)


string,
__________________________

void Write(byte v a l u e )
void W r i t e ( b y t e [] b u f f e r )
void Write(short v a l u e )
void Write(ushort v a l u e )
void Write(int v a l u e )
void Write(uint v a l u e )
void Write(long v a l u e )
void Write(ulong v a l u e )
void Write(float v a l u e )
void Write(double v a l u e )
void Write(decimal

v alu e)

void Write(char ch)


void W r i t e ( c h a r [] b u f f e r )
void Write(string v a l u e )

B in a ryR e a d e r
BinaryReader , ,
.
:

456

I. C#

BinaryReader(Stream in pu t)

i n p u t , .
i n p u t ,
FileStream. ,
i n p u t ,
, ArgumentException.
B i n a r y R e a d e r .
.
B i n a r y R e a d e r ,
C# . . 14.6.
, , , R e a d s t r i n g ()
, .
IOException, .
, .

14.6. , B in a ryR ea d e r

bool R ea dBoolean ()

bool
byte
sbyte
c o u n t

char
c o u n t

decimal
double
float
short
int
long
ushort
uint
ulong
string,

.
,
BinaryWriter

byte R e a d B y t e O
sbyte R e a d S B y t e O
b y t e [] R ea dB ytes(int

c o u n t)

char R e a d C h a r O
char[]

ReadCha rs (i nt

decimal R e a d D e c i m a l ()
double R e a d D o u b l e O
float R e a d S i n g l e O
short Readlntl6()
int Readlnt32()
long Readlnt64()
ushort ReadUIntl6()
uint ReadUInt32()
ulong ReadUInt64()
string R e a d S t r i n g O

c o u n t)

BinaryWriter
Read ().


IOException. , B i n a r y R e a d e r
Close ().

14. -

457

R e a d ()

.
-1
R e a d ( b y t e [; b u f f e r , c o u n t
o f f s e t , int c o u n t )
b u f f e r , b u f f e r [ o f f s e t ],

R e a d (c h a r []b u f f e r ,
c o u n t
o f f s e t , int c o u n t )
b u f f e r , b u f f e r [ o f f s e t ] ,

int

int
int
int
int

-
,
B in ar yR ea der B i n a r y W r i t e r -.
.
// , .
using System;
using System.10;
class RWData {
static void Main() {
BinaryWriter dataOut;
BinaryReader dataln;
int i = 10;
double d = 1023.56;
bool b = true;
string str = " ";
// ,
try {
dataOut = new
'BinaryWriter(new FileStream("testdata", FileMode.Create));

}
catch(IOException exc) {
Console.WriteLine(" :\" + exc.Message);
return;

}
// ,
try {
Console.WriteLine(" " + i) ;
dataOut.Write(i);
Console.WriteLine(" " + d) ;
dataOut.Write(d);
Console.WriteLine(" " + b);
dataOut.Write(b);

458

I. C#

Console.WriteLine(" " + 12.2 * 7.4);


dataOut.Wri t e (12.2 * 7.4);
Console.WriteLine(" " + str);
dataOut.Write(str);

}
catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
dataOut.Close();

}
Console.WriteLine();
/ / ,
try {
dataln = new
BinaryReader(new FileStream("testdata",

FileMode.Open));

}
catch(IOException exc) {
Console.WriteLine(" :\" + exc.Message)
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);
str = dataln.ReadString();
Console.WriteLine(" " + str);

}
catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
dataln.Close ();

10
1023.56
True
90.28

14. -

459

10
1023.56
True
90.28

testdata,
, , ,
.

, ,
-.

, , ,
, . ,
.
/* BinaryReader BinaryWriter
. */
using System;
using System.10;
class Inventory {
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("He " +
" ");
Console.WriteLine(": " + exc.Message);
return;

}
// ,
try {
dataOut.Write("");
dataOut.Write(10);
dataOut.Write(3.95);
dataOut.Write("");
dataOut.Write(18);
dataOut.Write(1.50);
dataOut.Write("");
dataOut.Write(5);

460

!. C#
dataOut.Write (4.95);
dataOut.W rite("");
dataOut.Write (8);
dataOut.Write(8.95);

}
catch(IOException exc) {
Console.WriteLine(" ");
Console.WriteLine(": " + exc.Message);
} finally {
dataOut.Close();

}
Console.WriteLine() ;
// ,
try {
dataln = new
BinaryReader(new FileStream("inventory.dat", FileMode.Open));

}
catch(IOException exc) {
Console.WriteLine("He " +
" ");
Console.WriteLine(": " + exc.Message);
return;

}
// , .
Console.Write(" : ");
string what = Console.ReadLine();
Console.WriteLine();
try {
for (;;) {
// ,
item = dataln.ReadString() ;
onhand = dataln.Readlnt32() ;
cost = dataln.ReadDouble();
// , .
// , .
if(item.Equals(what, StringComparison.OrdinallgnoreCase)) {
Console.WriteLine(item + ": " + onhand + " . " +
": {0: } ", cost);
Console.WriteLine(" <{0}>: {1:}.",
item, cost * onhand);
break;

}
}
}
catch(EndOfStreamException) {
Console.WriteLine(" .");

14. -

461

catch(IOException exc) {
Console.WriteLine(" ");
Console.WriteLine(": " + exc.Message);
} finally {
dataln.Glose();

'

}
}
, , .
:
: 18 . : $1.50 .
<>: $27.00.

,
, .

.
,
. EndOf S tr eamException
, ,
. ,
.


, ..
, .
. , , Seek () ,
F ile S tr e a m . ,
, .
Seek ():
long Seek(long o f f s e t , SeekOrigin o r ig in )

o f f s e t
( o r i g i n ) . o r i g i n
, SeekOrigin.

S e e k O r i g i n .Begin
S e e k O r i g i n .Current
Se e k O r i g i n .End

Seek ()
, , .
, IOException.
,
NotSupportedException. ,
.

462

!. #

-
.
, .
// .
using System;
using System.10;
class RandomAccessDemo {
static void Main() {
FileStream f = null;
char ch;
try {
f = new FileStream("random.dat", FileMode.Create);
// ,
for(int i=0; i < 26; i++)
f.WriteByte((byte)('A'+i));
/ / .
f.Seek(0, SeekOrigin.Begin); //
ch = (char) f .ReadByte () ;
Console.WriteLine(" : " + ch) ;
f.Seek(l, SeekOrigin.Begin); //
ch = (char) f .ReadByte () ;
Console.WriteLine(" : " + ch);
f.Seek(4, SeekOrigin.Begin); //
ch = (char) f .ReadByte() ;
Console.WriteLine(" : " + ch) ;
Console.WriteLine();
/ / .
Console.WriteLine(" : ");
for(int i=0; i < 26; i += 2) {
f.Seek(i, SeekOrigin.Begin); // i-
ch = (char) f .ReadByte() ;
Console.Write(ch + " ") ;

}
}
catch(IOException exc) {
Console.WriteLine(" -\" + exc.Message) ;
' } finally {
if(f != null) f.Close();

}
Console.WriteLine();

}
}
.

14. -

463

:
:
:
, :
G I K M O Q S U W Y

Seek ()
,
Position. . 14.2, P o s i t i o n
, .
.

random.dat,
Position.
Console.WriteLine(" : ");
for(int i=0; i < 26; i += 2) {
f.Position = i; // i- Position
ch = (char) f .ReadByte();
Console.Write(ch + " ");

M em oryStream

,
. MemoryStream.
Stream,
. M e m o r y S t r e a m .
:
MemoryStream(byte[ ] b u f fe r )

b u f f e r ,
-. , ,
b u f f e r
.
,
MemoryStream -.
// MemoryStream.
using System;
using System.10;
class MemStrDemo {
static void Main() {
byte[] storage = new b y t e [255];
// .
MemoryStream memsttm = new MemoryStream(storage);
// memstrm

464

I. C#
// .
StreamWriter memwtr = new StreamWriter(memstrm);
StreamReader memrdr = new StreamReader(memstrm);
try {
// , memwtr.
for(int i=0; i < 10; i++)
memwtr.WriteLine("byte [" + i + "]: " + i);
// ,
memwtr.WriteLine(".");
memwtr.Flush() ;
Console.WriteLine(" storage: ") ;
// storage .
foreach(char ch in storage) {
if (ch == '.') break;
Console.Write(ch);

}
Console.WriteLine(" memrdr:
// memstrm ,
memstrm.Seek(0, SeekOrigin.Begin); //
//
string str = memrdr.ReadLine();
while(str != null) {
str = memrdr.ReadLine();
if(str[0] == '.') break;
Console.WriteLine(str) ;

}
} catch(IOException exc) {
Console.WriteLine(" -\" + exc.Message);
} finally {
// ,
memwtr.Close();
memrdr.Close() ;

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

");

14. -

465

memrdr:
byte [1]
byte [ 2 ]
byte [3]
byte [4]
byte [5]
byte [ 6 ]
byte [7]
byte [ 8 ]
byte [9]

, storage.
m e m s t r m
MemoryStream. memstrm, , memrdr
StreamReader memwtr StreamWriter. memwtr
. ,
memwtr Flush ().
,
.
for each.
Seek () ,
memrdr.
.
, ,
, .

, Windows. ,
. , ,
.

S trin g R e a d e r S t r i n g W r i t e r
-
string,
byte. StringReader
StringWriter. , StringReader TextReader,
S t r i n g W r i t e r TextWriter. ,
, ,
, , , R e a d L i n e ()
StringReader, WriteLine () StringWriter.
StringReader:
StringReader(string s )

s , .
String Wr it er .
.
StringWriter()

466

I. C#

,
.
T o S t r i n g ().

, StringReader
StringWriter.
// // StringReader StringWriter.
using System;
using System.10;
class StrRdrWtrDemo {
static void Main() {
StringWriter strwtr = null;
StringReader strrdr = null;
try {
// StringWriter.
strwtr = new StringWriter();
// StringWriter.
for (int i=0; i < 10; i++)
strwtr.WriteLine(" i : " + i);
// StringReader.
strrdr = new StringReader(strwtr.ToString());
/ / StringReader.
string str = strrdr.ReadLine();
while(str != null) {
str = strrdr.ReadLine();
Console.WriteLine(str);

}
} catch(IOException exc) {
Console.WriteLine(" -\" + exc.Message);
} finally {
// ,
if(strrdr != null) strrdr.Close();
if(strwtr != null) strwtr.Close ();

}
}
}
.

i
i
i
i
i
i
i
i
i

:
:
:
:
:
:
:
:
:

1
2
3
4
5
6
7
8
9

14. -

467

strwtr StringWriter,B
WriteLine().
StringReader , strwtr.
T o S t r i n g () strwtr.
, Re ad Li ne ().

F i l e
.NET Framework File,
, ,
. , File
, ,
, ,
, ,
( , .). , File
,
FileStream . File
, .
(), Exists () GetLastAccessTime ( ) .
,
, File. , File
.

Filelnfo.
File , :
, .
Filelnfo.

()
,
.
,
(), File.
.
static void Copy (string __ , string __)
static void Copy (string __ , string __,
boolean o v e r w r ite )

C o p y () , _ _ ,
, _ _ .
, , _ _ , .
, o v e r w r i t e
true.
, IOException FileNotFoundException.

468

!. C#

()
. .
, .
, .
/* , File.CopyO.
,
. , FIRST.DAT SECOND.DAT,
:
CopyFile FIRST.DAT SECOND.DAT

*/
using System;
using System.10;
class CopyFile {
static void Main(string[] args) {
if (args.Length != 2) {
Console.WriteLine(": CopyFile ");
return;

}
// ,
try {
File.Copy(args[0], args[l]);
} catch(IOException exc) {
Console.WriteLine(" \" + exc.Message);

}
}
}
^ , F i l e S t r e a m
. () .
,
. , *
().

E x i s t s () G e tL a s tA c c e s s T im e ()
File .
: Exists () GetLas tA cc es sT im e (). Exists ()
, , GetLastAccessTime ()
. .
static bool Exists(string )
static DateTime GetLastAccessTime(string )

, .
Exists () true,
. GetLastAccessTime ()
DateTime, . (

14. -

469

DateTime , ToString ()
.)

,
IOException.
Exists () GetLastAccessTime ()
. ,
t e s t .txt. ,
.
// Exists () GetLastAccessTime() .
using System;
using System.10;
class ExistsDemo {
static void Main() {
if(File.Exists("test.txt"))
Console.WriteLine(" . " +
File.GetLastAccessTime("test.txt"));
else
Console.WriteLine(" ");

}
}
, , GetCreationTime (),
, G e t L as tW ri te Ti me ().

(UTC). .


-,
, .
, W r i t e L i n e ()
, ,
int double.
W r i t e L i n e () .

. ,
Re ad () "100",
,
, int.
.
Parse (), .
: C#
, int double,
(.. ) , .NET Framework.
C# .NET
Framework, . C#

470

I. C#

,
.
.NET C#
.

.NET

C#

Decimal
Double
Single
In 1 16
Int32
Int64
Ulntl6
UInt32
U I n t 64
Byte
Sbyte

decimal
double
float
short
int
long
ushort
uint
ulong
byte
sbyte

System. ,
I nt 32 System. Int32.
,
#. ,
Parse ( ),
.
Parse ().
.
. ,
, .

Decimal
Double
Single
Int 64
Int32
I n 1 16
U I n t 64
UInt32
Ulntl6
Byte
Sbyte

static
static
static
static
static
static
static
static
static
static
static

decimal Parse(string s)
double Parse(string s)
float Parse(string s)
long Parse(string s)
int Parse(string s)
short Parse(string s)
ulong Parse(string s)
uint Parse(string s)
ushort Parse(string s)
byte Parse (string s)
sbyte Parse(string s)

P a r s e ()
FormatException, s ,
. ,
ArgumentNullException. s
,
OverflowException.

14. -

471


,
, .
, , .
,
R ea dL in e ()
Int32 . Parse (). ,
D o u b l e .Parse () double.
// , .
using System;
using System.10;
class AvgNums {
static void Main() {
string str;
int n;
double sum = 0.0;
double avg, t;
Console.Write(" :
str = Console.ReadLine ();
try {
n = Int32.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
} catch(OverflowException exc) {
Console.WriteLine(exc.Message);
return;

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

}
}

");

472

I. #

, ,
.
: 5
5 .
: 1. 1
: 2. 2

: 3.3
: 4.4
: 5.5
3 .3

,
. ,
, , Int32 .
Parse (), , .. ,
.
, Parse ()
.
, TryParse (),
.
T r y P a r s e O , Int 32:
static bool TryParse(string s ,

out int )

s , ,

. (

.) , ,
s , TryParse ()
false.
true. , , ,
, ( )
.

,
-
#:
, -.
,
,
. ,
.
,
#. -
,
,
,
. -
,
-. ( , -
LINQ, 19.)
,
,
.

.
, ,
. , ,
, .
, .
, ,
. ,
.

474

I. C#

,
,
, . , ,
, , . ,
, .

C/C++, ,
C# C/C++.
d e le g a te .
:
delegate _ (_) ;

_ , ,
; ; _
, , .
, ,
.
,
. ,
, , ,
. :
,
.
,
.
// .
using System;
// ,
delegate string StrMod(string str);
class DelegateTest {
// .
static string ReplaceSpaces(string s) {
Console.Writ e L i n e (" .");
return s.Replace(' ', '-');

}
// .
static string RemoveSpaces(string s)
string temp = "";
int i;

Console.Wr i t e L i n e (" .");


for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s[i];

15. , -

475

return temp;

}
// ^.
static string Reverse(string s)
string temp = "";
int i, j;

Console.W riteLine (" .") ;


for(j=0, i = s .Length-1; i >= 0; i , j++)
temp += s [i ];
return temp;

}
static void Main() {
// .
StrMod strOp = new StrMod(ReplaceSpaces) ;
string str;
// ,
str = str O p (" .");
Console.WriteLine(" :
Console.WriteLine();
strOp = new StrMod(RemoveSpaces);
str = s t r O p (" .");
Console.WriteLine(" :
Console.WriteLine();
strOp = new StrMod(Reverse);
str = s t r O p (" .");
Console.WriteLine(" :

" + str);

" + str);

" + str);

}
}
.
.
: --.
.
: .
.
:

.
StrMod string, .
delegate string StrMod(string str);

, StrMod string
.

476

I. C#

D e le g a te T e s t
s t r i n g . ,
StrMod.
. , Rep l a S paces ()
s t r i n g R ep lace ().
Main () strOp StrMod
ReplaceSpaces ().
.
StrMod strOp = new StrMod(ReplaceSpaces);

ReplaceSpaces () .
, . :
,
. , ,
.
.
ReplaceSpaces () strOp,
.
str = s t r O p (" .");

strOp Re pl ac eS pa ce s (),
.
strOp RemoveSpaces (),
RemoveSpaces ().
, strOp Reverse ( ) .
.
: ,
strOp, ,
. , ,
.


C# 2.0 ,
.
, ,
new .
Main () ,
.
static void Main() {
// , .
StrMod strOp = ReplaceSpaces; //
string str;
// ,
str = s t r O p (" .");
Console.WriteLine(" :
Console.WriteLine();

" + str);

15. , -

477

strOp = RemoveSpaces; //
str = s t r O p (" .");
Console.WriteLine(" : " + str);
Console.WriteLine() ;
strOp -= Reverse; //
str = str O p (" .");
Console.WriteLine(" : " + str);
Console.WriteLine() ;

}
, strOp
Rep la Spaces .
strOp = RemoveSpaces;

//


strOp,
"" #.
, .

,
.


,
, . ,
,
StringOps. ,
.
// .
using System;
// ,
delegate string StrMod(string str);
class StringOps {
// .
public string ReplaceSpaces(string s) {
Console.WriteLine(" .");
return s.Replace('
'-');

}
// .
public string RemoveSpaces(string s) {
string temp = "";
int i;
Console.WriteLine(" .");
for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s [i ] ;

478

I. C#
return temp;

}
// ,
public string Reverse(string s) {
string temp = "";
int i, j;
Console.W r i teLine(" .");
for(j=0, i = s .Length-1; i >= 0; i , j++)
temp += s [i];
return temp;

}
}
class DelegateTest {
static void Main() {
StringOps so = new StringOpsO;

//
// StringOps

// .
StrMod strOp = s o .ReplaceSpaces;
string str;
// ,
str = s t r O p (" .");
Console.WriteLine(" :
Console.WriteLine();
strOp = s o .RemoveSpaces;
str = s t r O p (" .");
Console.Write L i n e (" :
Console.WriteLine();
strOp = so.Reverse;
str = s t r O p (" .");
Console.W r i teLine(" :

" + str);

" + str);

" + str);

}
}
,
,
StringO ps.



. , ,
, ,
. .
, + +=.
- -=.
, ,
. , ,
void .

15. , -

479

.
, ,
, void,
r e f .
.
// .
using System;
// .
delegate void StrMod(ref string str);
class MultiCastDemo {
// .
static void ReplaceSpaces(ref string s) {
Console.WriteLine(" .");
s = s.Replace(' ', '-');

}
// .
static void RemoveSpaces(ref string s)
string temp = "";
int i;

Console.WriteLine(" .");
for(i=0; i < s.Length; i++)
if(s[i] != ' ') temp += s[i];
s = temp;

}
// .
static void Reverse(ref string s)
string temp = "";
int i , j;

Console.WriteLine(" .");
for(j=0, i = s .Length-1; i >= 0; i , j++)
temp += s[i];
s = temp;

}
static void Main() {
// .
StrMod strOp;
StrMod replaceSp = ReplaceSpaces;
StrMod removeSp = RemoveSpaces;
StrMod reverseStr = Reverse;
string str = " .";
// .
strOp = replaceSp;

480

!. C#
strOp += reverseStr;
// .
strOp(ref str);
Console.WriteLine(" : " + str);
Console.Writ e L i n e ();
// .
strOp -= replaceSp;
strOp += removeSp;
str = " ."; //
// .
strOp(ref str);
Console.WriteLine(" : " + str);
Console.Writ e L i n e () ;

}
}
.
.
.
: .--
.
.
:

Main ()
. , strOp, ,
.
RemoveSpaces () Reverse ().
.
strOp = replaceSp;
strOp += reverseStr

strOp replaceSp,
+= reverseStr. strOp
, ,
.
replaceSp :
strOp -= replaceSp;

removeSp .
strOp += removeSp;

strOp.
.
,
, .
. ,
, .

15. , -

481



: . , ,
,- , .

. ,
, ,
, .
, ,
, .
,
.
// .
using System;
class X {
public int Val;

}
// Y, X.
class Y : X { }
// X
// Y ,
delegate X ChangeIt(Y obj);
class CoContraVariance

// X
// X ,
static X IncrA(X obj) {
X temp = new X () ;
temp.Val = obj.Val + 1;
return temp;

}
// Y
// Y ,
static Y IncrB(Y obj) {
Y temp = new Y ();
temp.Val = obj.Val + 1;
return temp;

}
static void Main() {
Y Yob = new Y ();
// IncrA X,
// Changelt Y .
// .
Changelt change = IncrA;

482

!. C#

X Xob = change(Yob);
Console.WriteLine("Xob: " + Xob.Val);
// IncrB Y,
// Changelt X.
// ,
change = IncrB;
Yob =

(Y) change(Yob);

Console.W r i teLine("Yob: " + Yob.Val);

}
}
.
Xob: 1
Yob: 1

Y X. Changelt
.
delegate X Changelt(Y obj) ;

X
Y. IncrA () IncrB () .
static X I n c r A (X obj)
static Y IncrB(Y ob j )

I n c r A () X
. IncrB ()
Y . Changelt,
.
,
Changelt change = IncrA;

IncrA () ,
X I ncrA (), Y
Changelt.
, ,
, , ,
.
,
.
change = IncrB;

IncrB () Y,
X.
,
.

15. , -

483

S ys te m . D e le g a te

System. Delegate. ,
, . System.
Delegate .



, .
, . -,
, . -,
,
. ,
.
,
Windows Paint.
.
,
. ,
.


, , .
,
, ,
. ,
. , ,
, .
, , .
, ,
.
3.0, C#
: -. C#
2.0, - 3.0. -

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

484

I. C#


,
.
delegate. , ,
.
0 5.
// .
using System;
// ,
delegate void C o u n t l t ();
class AnonMethDemo {
static void Main() {
// ,
// .
Countlt count = delegate {
// ,
for (int i=0; i <= 5; i++)
Console.WriteLine(i) ;
}; //
c o u n t ();

}
}
C ou nt lt
void. Main () count
Countlt, ,
delegate. ,
count. ,
,
. .
0

1
2

3
4
5


.
delegate,

. ,
.

15. , -
// ,

485

using System;
// , Countlt ,
delegate void Countlt(int end);
class AnonMethDemo2
static void Main()

{
{

// .
Countlt count = delegate (int end) {
for(int i=0; i <= end; i++)
Console.WriteLine(i);

};
count (3);
Console.WriteLine ();
count (5);

}
}
C ou n tlt .
,
d e le g a te . end
,
. .
0
1
2

3
0

1
2

3
4
5


.
re tu rn , ,
. ,
, .
,
.
// ,
using System;

486

I. C#

// ,
delegate int Countlt(int end);
class AnonMethDemo3
static void Main()
int result;

{
{

// .
/ / .
Countlt count = delegate (int end) {
int sum = 0;
for(int i=0; i <= end; i++)
Console.WriteLine (i);
sum += i;

}
return sum;

//

};
result = count (3);
Console.WriteLine(" 3 " + result);
Console.WriteLine ();
result = count (5);
Console.WriteLine(" 5 " + result);

}
}
,
cou n t. , r e tu r n
, .
.
0
1
2

3
3 6

0
1
2

3
4
5
5 15


, ,
.
. .
,

15. , -

4 87

"". ,
, ,
, ,
.
.

. Countlt
Counter (). sum,
Counter (), .
sum . Counter ()
Main () Countlt, , sum
.
// ,
using System;
// int int.
delegate int Countlt(int end);
class VarCapture {
static Countlt Counter () {
int sum = 0;
// sum.
Countlt ctObj = delegate (int end) {
for(int i=0; i <= end; i++) {
Console.WriteLine(i);
sum += i;

}
return sum;

};
return ctObj;

}
static void Main() {
// .
Countlt count = Counter ();
int result;
result = c o u n t (3);
Console.WriteLine(" 3 " + result);
Console.WriteLine();
result = c o u n t (5);
Console.WriteLine(" 5 " + result);

}
}
.
.

488

!. #

1
2

3
3 6

0
1
2
3
4
5
5 21

, - .
, 5 21, 15! , sum
ctOb j Counter (). ,
count "
" . ,
Counter () ,
count Main ().

, ,
. ,
, .
,
.

-
,
: -. , #,
1.0 . -

. -
LINQ ( 19),
. -
.
- . (
, , .) ,
- . -
, ,
.

-
- - =>,
- .
( ), -.
=> , "" "".

15. , -

489

C# -
-. , -
, -.
. -
, , -.
- ,
, i f . .

-
- , =>,
( ), .
.
-,
.
=>

, .
(_ ) =>

, ,
. ,
.
-.
count- => count + 2

co u n t ,
count + 2. count 2.
-.
n => % 2 ==

tr u e ,
, f a l s e .
- . ,
-, ,
-. -
. .

-.
. , In c , i n t
. , IsEven, i n t,
b o o l.
-. , -
.
// -.
using System;

490

I. C#

1 1 ,

int
// int.
delegate int Incr(int v ) ;

'

// , int
// bool,
delegate bool IsEven(int v ) ;
class SimpleLambdaDemo {
static void Main()

// Incr, -,
// 2.
Incr incr = count => count + 2;
// - incr.
Console.W r i teLine(" - incr:
int x = -10;
while(x <= 0) {
Console.Write(x + " ");
x = incr(x); // x 2

");

}
Console.WriteLine ("\n");
// IsEven, -,
// true,
// , false.
IsEven isEven = n => n % 2 == 0;
// - isEven.
Console.WriteLine(" - isEven:
for (int i=l; i <= 10; i++)
if(isEven (i)) Console.W riteLine(i + " .");

");

}
}
.
- incr:
-10 -8 -6 -4 -2 0
- isEven:
2 .
4 .
6 .
8 .
10 .

.
Incr incr = count => count + 2 ;
IsEven isEven = n => n % 2 == 0;

15. , -

491

i n c r
-, 2
count. Incr,
. ,
incr, count,
-. isEven
, true,
, false.
, - IsEven.
:
, , , int count -,
i n c r ? :

. ,
.
,
-.
.
incr.
Incr incr =

(int count)

=> count + 2;

, count int.
. . (
, ,
.)
-
, - ,
. - ,
. , .
(low, high, val) => val >= low && val <= high;

, -.
delegate bool InRange(int lower,

int upper,

int v ) ;

, InRange
.
InRange rangeOK =

(low, high, val) => val >= low && val <= high;

- ,
.
if(rangeOK(1, 5, 3)) Console.WriteLine(
" 3 1 5.");

:
- , .

492

I. C#

-
, -.
, -, .
- .
-. -
,
. , -
i f , ..
- .
.
, -,
-.
-
.
// -,
using System;
// IntOp int
// int.
delegate int IntOp(int end);
class StatementLambdaDemo
static void Main()

// -
// .
IntOp fact = n => {
int = 1;
for (int i=l; i <= n; i++)
r = i * r;
return r;

};
Console.W r i teLine(" 3 " + fact(3));
Console.Wr i t e L i n e (" 5 " + f a c t (5));

}
}
.
3 6
5 120

,
- , f o r
re tu rn . -.
. ,
-
. : re tu rn , , .

15. , -

493

, . ,
-
.
// ,
// -.
using System;
// ,
delegate string StrMod(string s) ;
class UseStatementLambdas
static void Main()

// , - ,
// .
// .
StrMod ReplaceSpaces = s => {
Console.WriteLine(" .");
return s.Replace('
'-');

};
%

// .
StrMod RemoveSpaces = s => {
string temp = "";
int i;
Console.Wr i t e L i n e (" .");
for(i=0; i < s.Length; i++)
if(s[i] != 1 ') temp += s[i];
return temp;

};
// .
StrMod Reverse = s => {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i = s .Length-1; i >= 0; i , j++)
temp += s [i];
reburn temp;

};
string str;
// - .
StrMod strOp = ReplaceSpaces;

494

I. #
str = s t r O p (" .");
Console.W r i teLine(" :
Console.WriteLine() ;
strOp = RemoveSpaces;
str = s t r O p (" .");
Console.WriteLine(" :
Console.W r i teLine();
strOp = Reverse;
str = s t r O p (" .");
Console.WriteLine(" :

" + str);

" + str);

" + str);

}
}
,
.
.
: --.
.
: .
.
:

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

ev en t. :
event _ _;

_ ,
, _ .
.
// , ,
using System;
// ,
delegate void MyEventHandler();
// , ,
class MyEvent {
public event MyEventHandler SomeEvent;

15. , -

495

// ,
public void OnSomeEvent() {
if (SomeEvent != null)
SomeEvent();

}
}
class EventDemo {
// ,
static void Handler () {
Console.WriteLine(" ");

}
static void Main() {
MyEvent evt = new MyEvent ();
// H a n d l e r () ,
e v t .SomeEvent += Handler;
// ,
e v t .OnSomeEvent();

}
}
.

,
, .
, .
delegate void MyEventHandler();

.
.
, .
MyEvent.
SomeEvent .
public event MyEventHandler SomeEvent;

. event
, .
, MyEvent OnSomeEvent (),
. , ,
. OnSomeEvent ()
SomeEvent.
if(SomeEvent != null)
SomeEvent();

, , SomeEvent
.
, , OnSomeE ve nt ()
.

496

!. C#

,
, .
Event Demo Handler ().
,
. Main ()
MyEvent, a H a n d le r ()
, .
MyEvent evt = new MyEvent ();
// Ha n d l e r () ,
e v t .SomeEvent += Handler;

,
+=. += -= .
H a n d l e r () ,
.
, , .
// ,
e v t .OnSomeEvent();

OnSome Ev en t () ,
. ,
, .


, .
.
.
// ,
using System;
// ,
delegate void MyEventHandler() ;
// , ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();

}
}
class X {
public void Xh a n d l e r O {
C onsole.Write L i n e (" X");

15. , -

497

}
class Y {
public void Y h a ndlerO {
Console.WriteLine(" Y") ;

}
}
class EventDemo2 {
static void Handler() {
Console.WriteLine(" EventDemo");

}
static void Main() {
MyEvent evt = new MyEvent ();
X xOb = new X ();
Y yOb = new Y ();
// .
e v t .SomeEvent += Handler;
e v t .SomeEvent += x O b .Xhandler;
e v t .SomeEvent += y O b .Yhandler;
// ,
e v t .OnSomeEvent() ;
Console.WriteLine () ;
// .
e v t .SomeEvent -= x O b .Xhandler;
e v t .OnSomeEvent() ;

}
}
.
EventDemo
X
Y
EventDemo
Y

, X Y,
, M yEventH andler.
.
, X Y .
, ,
, .

.




, .

498

!. #

,
.
, . ,
,
, .
, , ,
.
.
X,
. ,
X , .

X.
/* ,
. */
using System;
// ,
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.W r i teLine(" " + id);

}
class EventDemo3 {
static void Main() {
MyEvent evt = new M y E v e n t ();
X ol = new X (1);
X o2 = new X (2);
X o3 = new X(3);
e v t .SomeEvent += ol.Xhandler;
e v t .SomeEvent += o2.Xhandler;
e v t .SomeEvent += o3.Xhandler;

15. , -

499

// ,
e v t .OnSomeEvent() ;

}
}
.
1
2
3

,
,
.
,
, - ,
.
/* ,
. */
using System;
// ,
delegate void MyEventHandler();
// , ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent() {
if (SomeEvent != null)
SomeEvent() ;

}
}
class X {
/*
. */
public static void Xhandler() {
Console.WriteLine(" .");

}
}
class EventDemo4 {
static void Main() {
MyEvent evt = new M y E v e n t ();
e v t .SomeEvent += X.Xhandler;
// ,
e v t .OnSomeEvent();

}
}

500

I. C#

.
.

, X
. X h a n d l e r () X,
S o m e E v e n t
O n S o m e E v e n t ().


,
,
.
.
.
, , ,
.

event, .

.
event _ _ {
add {
// .

}
remove {
// .

}
}
: add remove. add ,
+=.
remove ,
-=.
a dd remove,
. ,
value. add remove,
. ,
, .
,
. .
,
.
//
// .
using System;
// .
delegate void MyEventHandler();

15. , -

// ,
class MyEvent {
MyEventHandler[] evnt = new MyEventHandler[3];
public event MyEventHandler SomeEvent {
// ,
add {
int i;
for(i=0; i < 3; i++)
if(evnt[i] == null) {
evnt[i] = value;
break;

}
if (i == 3) Console.W r i teLine(" .");

}
// ,
remove {
int i;
for(i=0; i < 3; i++)
if(evnt[i] == value)
evnt[i] = null;
break;

}
if

(i == 3) Console.W r i teLine(" .");

}
}
// . ,
public void OnSomeEvent() {
for(int i=0; i < 3; i++)
if(evnt[i] != null) evnt[i]();

}
}
// , MyEventHandler.
class W {
public void Whandler() {
Console.WriteLine(" W " ) ;

}
}
class X {
public void Xhandler() {
Console.WriteLine(" X " ) ;

}
}
class Y {
public void Yhandler() {
Console.WriteLine(" Y");

}
}

501

502

I. C#

class Z {
public void Zhandler() {
Console.WriteLine(" Z");

}
}
class EventDemo5 {
static void Main() {
MyEvent evt = new M y E v e n t ();
W wOb = new W ();
X xOb = new X ();
Y yOb = new Y ();
Z zOb = new Z ();
// .
Console.W riteLine(" .");
e v t .SomeEvent += w O b .Whandler;
e v t .SomeEvent += x O b .Xhandler;
e v t .SomeEvent += y O b .Yhandler;
// - ,
e v t .SomeEvent += zO b .Zhandler;
Console.WriteLine();
// ,
e v t .OnSomeEvent();
Console.WriteLine();
// .
Console.Write L i n e (" x O b .Xhandler."
e v t .SomeEvent -= x O b .Xhandler;
e v t .OnSomeEvent();
Console.WriteLine();
// .
Console.WriteLine(" " +
"xOb.Xhandler .");
e v t .SomeEvent -= x O b .Xhandler;
e v t .OnSomeEvent();
Console.WriteLine();
/ / Zhandler.
Console.WriteLine(" zOb.Zhandler
e v t .SomeEvent += z Ob.Zhandler;
e v t .OnSomeEvent();

}
}
:
.
.

15. , -

503

W
X
Y
x O b .Xhandler.
W
Y
xOb.Xhandler .
.
W
Y
z O b .Zhandler.
W
X
Y

.
MyEventHandler. MyEvent.
evnt,
.
MyEventHandler[] evnt = new MyEventHandler[3];

,
. evnt
(null).
SomeEvent.
event.
public event MyEventHandler SomeEvent {
// ,
add {
int i;
for(i=0; i < 3; i++)
if(evnt[i] == null) {
evnt[i] = value;
break;

}
if

(i == 3) Console.W r i teLine(" .");

}
// ,
remove {
int i;
for(i=0; i < 3; i++)
if(evnt[i] == value) {
evnt[i] = null;
break;

}
if

(i == 3) Console.WriteLine(" .");

504

I. #

,
add, (.. ) evnt
, value.

, . (
,
.) evnt ,
.
, remove evnt
, value.
,
(null), , .
OnSomeEvent ().
evnt
.
,
, .

, event
. event
. ,
, , ,
.

. 23.


.
, .
(abstract).
.
. ,
(sealed). , , ..
.


-
, ,
. , ,
, . -
.

15. , -

505

, -
, .
, -
.
// - ,
using System;
// ,
delegate void MyEventHandler(int n) ;
// , ,
class MyEvent {
public event MyEventHandler SomeEvent;
// ,
public void OnSomeEvent(int n) {
if(SomeEvent != null)
SomeEvent(n);

}
}
class LambdaEventDemo {
static void Main() {
MyEvent evt = new M y E v e n t ();
// - ,
e v t .SomeEvent += (n) =>
Console.WriteLine(" . " + ) ;
// ,
e v t .OnSomeEvent(1);
e v t .OnSomeEvent(2);

}
}
.
. 1
. 2

, -
.
e v t .SomeEvent += (n) =>
Console.WriteLine(" . " + ) ;

-
, .

-, .
,
.

506

I. C#

1 1 ,
e v t .SomeEvent += delegate(int n) {
Console.WriteLine(" . " + n ) ;

};
,
,
.

.NET Framework
C# .
.NET Framework
, Microsoft.
, , :
. ,
, EventArgs,
, . , .NET .
void (object , EventArgs )

//

...

}
, ,
this. EventArgs
, .
E v e n t A r g s ,
. , Event A r g s
, ,
. E v entArgs E m pty
static, EventArgs .
, .NET-
.
//

.NET- ,

using System;
// , EventArgs.
class MyEventArgs : EventArgs {
public int EventNum;

}
// .
delegate void MyEventHandler(object source, MyEventArgs arg);
// , ,
class MyEvent {
static int count = 0;
public event MyEventHandler SomeEvent;

15. , -
// SomeEvent.
public void OnSomeEvent() {
MyEventArgs arg = new MyEventArgs();
if(SomeEvent != null) {
arg.EventNum = count++;
SomeEvent(this, arg);

}
}
}
class X {
public void Handler(object source, MyEventArgs arg) {
Console.WriteLine(" " + arg.EventNum +
" 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 EventDemo6 {
static void Main() {
X obi = new X ();
Y ob2 = new Y ();
MyEvent evt - new* MyEvent ();
// H a ndler() ,
evt ..SomeEvent += obi. Handler;
e v t .SomeEvent += ob2.Handler;
// ,
e v t .OnSomeEvent();
e v t .OnSomeEvent();

}
}
.
0 X
: MyEvent
0 Y
: MyEvent
1 X
: MyEvent

507

508

!. C#

1 Y
: MyEvent

MyEventArgs, EventArgs.
MyEventArgs : EventNum.
MyEventHandler, ,
.NET Framework. ,
, ,
EventArgs . Handler (),
X Y, .
M y E v e n t S o m e E v e n t MyEventHandler.
O n S o m e E v e n t () SomeEvent,
this,
M yEventArgs. ,
MyEventHandler
.NET.

E v e n tH a n d le r< T E v e n tA rg s >
E v e n tH a n d le r

. , , .NET
Framework
EventHandler<TEventArgs>. (
18.) TEventArgs ,
EventArgs . ,
SomeEvent MyEvent .
public event EventHandler<MyEventArgs> SomeEvent;

, ,
.
E v e n t A r g s
. .NET
Framework EventHandler.
,
.
EventHandler.
// EventHandler.
using System;
// , ,
class MyEvent {
public event EventHandler SomeEvent;

// EventHandler

// .
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent(this, EventArgs.Empty);

15. , -

509

}
}
class EventDemo7 {
static void handler(object source, EventArgs arg)
Console.W r i teLine (" ");
Console.WriteLine(": " + source);

}
static void Main() {
MyEvent evt = new M y E v e n t ();
// H andler() ,
e v t .SomeEvent += Handler;
// ,
e v t .OnSomeEvent() ;

}
}
EventArgs ,
- EventArgs .Empty.
.

: MyEvent



, Windows. ,
,
.
#,

. ,
LButtonClick.
OnLButtonClick (),
.
Windows, ,
, , ,
, .
, . ,
, K e y P r e s s
O n K e y P r e s s ( ) . , .NET -.
// ,

using System;
// , EventArgs
// .

5 10

I. #

class KeyEventArgs
public char ch;

: EventArgs

}
/ / , ,
class KeyEvent {
public event EventHandler <KeyEventArgs> KeyPress;

// ,
public void OnKeyPress(char key) {
KeyEventArgs k = new KeyEventArgs();
if(KeyPress != null) {
k.ch = key;
KeyPress(this, k) ;

}
}
}
// KeyEvent.
class KeyEventDemo {
static void Main() {
KeyEvent kevt = new KeyEv e n t ();
ConsoleKeylnfo key;
int count = 0;
// - ,
ke v t .KeyPress += (sender, ) =>
Console.WriteLine(" : " + e.ch);
// - .
k e v t .KeyPress += (sender, ) =>
count++; // count
Console.WriteLine(" . " +
" .");
do {
key = Console.R e a d K e y ();
ke v t .OnKeyPress(key.KeyChar);
} while(key.KeyChar != '.');
Console.WriteLine(" " + count + " .");

}
}
, , .
.
t

s
t
.
5 .

,
: t
:
: s
: t
:
.

15. , -

511

KeyEventArgs,
EventArgs
. EventHandler,
, .
KeyEvent, KeyPress.
M a i n () kevt KeyEvent.
k e v t .Ke y P r e s s , . ,
.
kevt.KeyPress += (sender, ) =>
Console.WriteLine (" :

" + e.ch);

kevt .KeyPress ,
-.
, .
kevt.KeyPress += (sender, ) =>
count++; // count

, count ,
Main () .
, k e v t .OnKeyPress ()
.
.
. ,
#.
. ,
,
.

______________

,

#,

.
, .


2
, #.

#.

, C#

. ,
, ,
.


.
.
,

. , ,
,
,
. , .NET Framework,
#,
System.

514

I. C#

using System;

#. 14,
- System. 10,
System. ,
#.
,
"" , ,
, , .

, . ,
Finder, Finder,
, . ,
, ,
.


namespace.
:
namespace {
1 1

}
.
. ,
, .
, , , ,
.
n a m e space
Counter. ,
CountDown.
// .
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

}
public void Reset(int n)
val = n;

}
public int C o u n t () {
if(val > 0) return val ;
else return 0;

16. ,

5 15

}
} // Counter.

, C o u n t D o w n
Counter.
, Counter, cs.
,
Counter.
// Counter.
using System;
class NSDemo {
static void Main()

// , CountDown
// Counter.
Counter.CountDown cdl = new Counter.CountDown(10);
int i;
do {
i = c d l .C o u n t ();
Console.Write(i + " ");
} while (i > 0);
Console.WriteLine ();
// , CountDown
// Counter.
Counter.CountDown cd2 = new Counter.CountDown(20);
do {
i = c d 2 .C o u n t ();
Console.Write(i + " ");
} while (i > 0);
Console.WriteLine ();
cd2.Reset (4) ;
do {
i = c d 2 .Count ();
Console.Write(i + " ");
} while (i > 0);
Console.WriteLine () ;

}
}
.
10 9 8 7 6 5 4 3 2 1 0
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
4 3 2 1 0

,

, Counter.

516

I. C#

N S D e m o .cs, Counter
C o u n t e r .cs,
.
csc NSDemo.cs counter.cs


. -, C o u n t D o w n
Counter,
. CountDown Counter.
Counter.CountDown cdl = new Counter.CountDown(10);

: ,
,
. .
-, C o u nter ,
. ,
c d l .Count ()
, .
i = c d l .C o u n t ();

-,
.
Counter, NSDemo.
. ,

.
, Counter
.
, ,
. , , ,
, .


,
, . ,
.
Counter, Counter2.
CountDown,
, C o u n t D o w n
. ,
. , . ,
,
.
// .
using System;

16. ,
// 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 val ;
else return 0;

}
}
}
// Counter2.
namespace Counter2 {
/* CountDown
Counter2
Counter.

*/
class CountDown {
public void C o u n t () {
Console.WriteLine(" C o u n t () " +
" Counter2.");

}
}

class NSDemo2 {
static void Main()

// CountDown Counter.
Counter.CountDown cdl = new Counter.CountDown(10);
// CountDown Counter2.
Counter2.CountDown cd2 = new Counter2.CountDown();
int i;
do {
i = c d l .C o u n t ();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
c d 2 .C o u n t () ;

}
}

517

518

I. C#

.
10 9 8 7 6 5 4 3 . 2 1 0
Count () Counter2.

, Count D o w n
Counter
Counter2, .
, ,
, ,
.

u s in g

, , ,
. using.

C# System,
. , using
.
using. :
using ;

,
. , ,
, .
using
.
,
using,
.
// using,
using System;
// Counter,
using Counter;
,
// ,
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

}
public void Reset(int n)
val = n;

16. ,

519

}
public int Count () {
if(val > 0) return val ;
else return 0;

}
}
}
class NSDemo3 {
static void Main()

// CountDown .
CountDown cdl = new CountDown(10);
int i;
do {
i = c d l .Count ();
Console.Write (i + " ") ;
} while (i > 0);
Console.WriteLine ();
CountDown cd2 = new CountDown (20);
do {
i = c d 2 .Count ();
Console.Write (i + " ");
} while (i > 0);
Console.WriteLine ();
c d 2 .R e s e t (4);
do {
i = c d 2 .Count ();
Console.Write(i + " ");
} while (i > 0);
Console.WriteLine ();

}
}
.
u s i n g ,
.
using Counter;

Counter.
, CountDown
Counter,
Main ().
CountDown cdl = new CountDown(10);

C o u n t e r ,
CountDown .
-

520

!. #

:
.
,
. ,
, System Counter, .

u s in g
using (
) . :
using = ;

(, )
, . ,
.
,
MyCounter
C o u n t e r .CountDown.
// ,
using System;
// Counter.CountDown.
using MyCounter = Counter.CountDown;
// ,
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

}
public void Reset(int n)
val = n;

} '
public int C o u n t () {
if(val > 0) return val ;
else return 0;

}
}
}
class NSDemo4 {
static void Main()

// MyCounter
// Counter.CountDown.

16. ,

521

MyCounter cdl = new MyCounter(10);


int i;
do {
i = cdl... Count () ;
Console.Write(i + " ");
} while (i > 0);
Console.WriteLine () ;
MyCounter cd2 = new MyCounter (20);
do {
i = c d 2 .Count () ;
Console.Write (i + " ");
} while (i > 0);
Console.WriteLine ();
c d 2 .Reset (4);
do {
i = c d 2 .Count ();
Console.Write (i + " ");
} while (i > 0);
Console.WriteLine ();

}
}
MyCounter .
using MyCounter = Counter.CountDown;


C o u n t e r .CountDown,

. ,
CountDown.
MyCounter cdl = new MyCounter (10);


0 4 .

. ,

Counter. CountDown, CountUp.
Counter .
// ,
using System;
// Counter,
using Counter;
// Counter.

522

I. C#

namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

}
public void Reset(int n)
val = n;

}
public int C o u n t () {
if(val > 0) return val ;
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 C o u n t () {
if(val < target) return val++;
else return target;

}
}
}
class NSDemo5 {
static void Main() {
CountDown cd = new CountDown(10);
CountUp cu = new C o u n t U p (8);

16. ,

5 23

int i;
do {
i = cd.Count ();
Console^.Write (i + "
} -while (i > 0) ;
Console.WriteLine ();

do {
i = c u .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

,
using Counter;

Counter.
CountDown CountUp , ..
. Counter
.


.
.
// .
using System;
namespace NS1 {
class ClassA {
public Clas s A () {
Console.WriteLine(" ClassA");

}
}
namespace NS2 { //
class ClassB {
public ClassB () {
Console.WriteLine(" ClassB");

}
}
}
}
class NestedNSDemo {
static void Main() { .

524

I. C#
NSl.ClassA a = new N S 1 .C l a s s A ();

// NS2.ClassB b = new N S 2 .ClassB (); // !!!

NS2

N S 1 .N S 2 .ClassB b = new N S 1 .N S 2 .C l a s s B (); // !

}
}
.
ClassA
ClassB

NS2 NS1.
ClassB
NS1 NS2. NS2
. ,
. , ClassB
Main () NSl.NS2.ClassB.
, .

.
namespace,
. ,
namespace OuterNS {
namespace InnerNS {

//

...

}
}
.
namespace OuterNS.InnerNS

...


,
. ,
,
namespace. ,
,
.
.
,
.

: :
,
. , , ,

16. ,

525


. ,
MyClass.
sing, MyClass
MyClass ,
.
: :.
: :.
__: :

_ _
, .

, ,
, Counter AnotherCounter,
CountDown.
using. , Ma i n ()
CountDown.
//

::.

using System;
// Counter AnotherCounter.
using Counter;
using AnotherCounter;
// ,
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n) {
val = n;

}
//

. . .

}
}
// ,
namespace AnotherCounter {
// CountDown,
// AnotherCounter.
class CountDown {
int val;
public CountDown(int n)
val = n;

// ...

526

!. #

}
}
class WhyAliasQualifier
static void Main() {
int i;

// , , !
// , CountDown
// Counter AnotherCounter?
CountDown cdl = new CountDown(10); // ! ! !

//

...

}
}
,
,
Main ().
CountDown cdl = new CountDown(10);

// !

! !

,
, C o u n t e r AnotherCounter, C o u n t D o w n
. , C o u n t D o w n
. .
: :.
: :,
, ,
.
, - ,
.
//

::.

using System;
using Counter;
using AnotherCounter;
// Counter Ctr.
using Ctr = Counter;
// ,
namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

// ...

16. ,

527

}
}
// ,
namespace AnotherCounter {
// CountDown,
// AnotherCounter.
class CountDown {
int val;
public CountDown(int n)
val = n;

}
//

...

}
}
class AliasQualifierDemo {
static void Main() {
// :: ,
// CountDown Counter.
C t r ::CountDown cdl = new C t r ::CountDown(10);

//

. . .

}
}
C o u nter
Ctr .
using Ctr = Counter;

Main ()
CountDown, .
C t r ::CountDown cdl = new C t r ::CountDown(10);

: : , ,
CountDown Ctr, Counter.
.
: :
global . ,
CountDown Counter,
. CountDown
global.
// ,
using System;
// Counter Ctr.
using Ctr = Counter;
// .

528

I. C#

namespace Counter {
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

...

}
}
// CountDown,
// ,
class CountDown {
int val;
public CountDown(int n)
val = n;

}
//

...

}
class GlobalAliasQualifierDemo
static void Main() {

// ::
// CountDown Counter.
C t r ::CountDown cdl = new C t r ::CountDown(10);
// CountDown
// .
global::CountDown cd2 = new global::CountDown(10) ;

...

}
}
, global
CountDown .
g lobal::CountDown cd2 = new global::CountDown(10) ;

,
.
:
extern, 20.

C# ,
.

16. ,

529


, .
,
, .
,
.
, #.
#define
#endregion
#pragma

# e lif
# e rro r
# reg io n

# e ls e
# if
#undef

# en d if
# lin e
#warning

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

#define
#define ,
.
# i f # e l i f
. #define.
#define

.
#define ,
. ,
E X P E R I M E N T A L .
#define EXPERIMENTAL

C/C++ #define ,
, ,
. C# #define .
#define .

# i f # e n d if
, # i f #en d if,
,
. ,
, . ,
#define, . # if .

530

!. C#

#if _

#endif

_ , # if, ,
( ),
#endif. .
#endif #if.
,
. : !, ==,
! =, && ||, .
.
//
// #if, #endif #define.
#define EXPERIMENTAL
using System;
class Test {
static void Main() {
#if EXPERIMENTAL
Console.WriteLine(" .");
#endif
Console.WriteLine(" .");

}
}
.
.
.

EXPERIMENTAL.
# i f,
,
WriteLine (). EXPERIMENTAL
, ,
W riteLine (), ,
#i f . ,
W riteLine (), ,
#if.
, # i f
. .
// .
#define EXPERIMENTAL
#define TRIAL
using System;

16. ,

531

class Test {
static void Main() {
#if EXPERIMENTAL
Console.W r i teLine(" .");
#endif
#if EXPERIMENTAL && TRIAL
Console.Err o r .W r i t e L i n e ("
.");
#endif
Console.WriteLine(" .");

}
}
.
.
.
.

: E X P E R I M E N T A L TRIAL.
, W r i t e L i n e (),
, .
, ,
!, .
#if !EXPERIMENTAL
Console.WriteLine(" !");
#endif

,
.

EXPERIMENTAL

# e ls e # e l i f
#else e l s e #,
,
# i f . #else
.
// #else.
#define EXPERIMENTAL
using System;
class Test {
static void Main() {
#if EXPERIMENTAL
Console.WriteLine(" .");
#else
Console.W r i teLine(" .");
#endif

532

I. C#

#if EXPERIMENTAL && TRIAL


Console.E r r o r .WriteLine("
.");
#else
Console.E r r o r .WriteLine(" .");
#endif
Console.WriteLine(" .");

}
}
.
.
.
.

TRIAL , # else
.
, # e ls e
# i f # e ls e .
, # i f
# en d if. , # i f
# e ls e .
# e l i f " ", # e l i f
i f - e l s e - i f .
# e l i f .
, ,
# e l i f .
. # e l i f ,
# e ls e ,
, # i f .
# e l i f .
#if _

#elif _

#elif _

// . .
#endif

# e lif .
// #elif.
#define RELEASE
using System;
class Test {
static void Main()

16. ,

5 33

#if EXPERIMENTAL
Console.W r i teLine(" .");
#elif RELEASE
Console.W r i teLine(" .");
#else
Console.W r i teLine(" .");
#endif
#if TRIAL && !RELEASE
Console.Write L i n e (" .");
#endif
Console.WriteLine(" .");

}
}
.
.
.

# u n d e f
#undef .
, , , "".
#undef.
#undef

.
#define SMALL
#if SMALL
// . . .
#undef SMALL
// SMALL .

# u n d e f SMALL
.
#undef
, .

#
#e r r o r .
. #.
# __

t e r r o r , .
,
# !

" ! ".

534

I. C#

# w a rn in g
#w arn in g t e r r o r ,
, , . ,
. #warning.
#warning _

# lin e
# lin e , .

. # lin e .
#line _"

#l i n e .
d e f a u l t ,
, .
#line default

# lin e hidden.
,
#line hidden

# lin e hidden, .

# re g io n # e n d re g io n
# reg io n #en d region ,

Visual Studio. :
#region
//
#endregion

#pragma
#pragma .
:
#pragma

, .
C# #pragma.
, warning,
. :
#pragma warning disable
#pragma warning restore

16. ,

535


. d is a b le ,
r e s t o r e .
, #pragma
168, , , .
#pragma warning disable 168

#pragma checksum.
ASP.NET. :
#pragma checksum "_" "{ GUID}" "_"

_ ; GUID
, _ ; _
, .
.

i n t e r n a l
#.
,
. .NET.
,
. ,
.
.
. .
, , , ,
( ).
, .. ,
.
.
MSIL (Microsoft Intermediate Language
Microsoft). ,
.
, C# ,
. ,
, #,
, ,
. , #,
.
,
, , ,
.
.NET, #.
C# , .
i n t e r n a l , .

536

I. C#

i n t e r n a l
public, p r i v a t e protected,
, C#
internal.
. , ,
internal, , .
internal
.
internal ,
. , i n ternal
.
p r o t e c t e d internal
p ro t e c t e d internal. p r o t e c t e d internal
. , p r o t e c t e d internal,
.
internal.
// internal.
using System;
class InternalTest
internal int x;

}
class InternalDemo {
static void Main() {
InternalTest ob = new InternalTest();
ob.x = 10; // ,

Console.WriteLine(" ob.x:

" + ob.x);

}
}
InternalTest internal. ,
, , InternalDemo,
.


,
I


: ,
.
,
.
.
,
. ,

, .. .

#. , ,
, .

.
.


(RTTI)
.
.
,
, .

,
,
. ,

.

538

!. C#

C#
: i s , as ty p e o f.
.

i s
i s .
:
i s

, ,
. ,
, ,
. , ,
. i s ,
,
.
i s .
// is.
using System;
class A {}
class : A {}
class Usels {
static void Main() {
A a = new A ();
b = new ();
if (a is A)
Console.WriteLine(" A");
if(b is A)
Console.WriteLine ("b , ");
if(a is )
Console.Writ e L i n e (" , ");
if(b is )
Console.Writ e L i n e (" ");
if(a is object)
Console.Writ e L i n e (" object");

}
}
.

b
b

object

i s ,
. ,
.

17. ,

539

if (b is )
Console.WriteLine("b , ");

if , b ,
-. . ,
if(a is )
Console.WriteLine(" ,

");

i f , ,
. .

as
,
, ,
. as,
:
as

, .
,
, . as
, , , .
as
is. , is
.
// is .
using System;
class {}
class : {}
class CheckCast {
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 =

}
}

() HE .");
() .");

540

I. C#

.
b =

() .

,
,
if.

. ,
.
as, .
// as.
using System;
class A {}
class : A {}
class CheckCast {
,
static void Main() {
A a = new A ();
b = new ();
b = a as ; // ,
if(b==null)
Console.WriteLine(" b = () .");
else
Console.WriteLine(" b = () .");

}
}
.
b =

() .

as
,
, .

t y p e o f
, as is
. .
C# typeof. System.
.
. typeof:
t y p e o f ()

. , ,
.
,
, , , .
,
, .
,

17. ,

541

: FullName, IsClass IsAbstract.


FullName. IsClass
true, . IsAbstract
true, .
// typeof.
using System;
using System.10;
class UseTypeof {
static void Main() {
Type t = typeof(StreamReader);
Console.WriteLine(t.FullName);
if (t.IsClass) Console.WriteLine(" .");
if (t.IsAbstract) C o nsole.WriteLine(" .");
else Console.WriteLine(" .");

}
}
.
System.10.StreamReader
.
.

,
StreamReader.
, .

, .
, , :
, .
, (
) , .
,
, .
, ,
.NET Reflection API, S y s t e m .Reflection.

.
using System.Reflection;

S ystem . T yp e -
System. ,
. ,

542

I. C#

.
System. Re flection.
Member Inf .
M e mber Inf ,

Type DeclaringType

,

. ,
, , ,
,
Module, (
),

___________________________

MemberTypes MemberType
int MetadataToken
M odule Module
string Name
Type ReflectedType

, M e m b e r T y p e MemberTypes
, ,
. .
/
MemberTypes.Constructor
MemberTypes.Method
MemberTypes.Field
MemberTypes.Event
MemberTypes.Property

, , MemberType. ,
M e m b e r T y p e M e m b e r T y p e s .Method,
.
M e m b e r l n f : G e t C u s t o m A t t r i b u t e s ()
Is Defined (). .
, ,
, . .NET Framework
Version 4.0 G e t C u s t o m A t t r i b u t e s D a t a (),
. ( .)
,
Memberlnf .
.

C ons t r u c t o r l n f []
G etConstructors ()
EventInfo[] GetEvents()

F ield l n f [] G e t F i e l d s ()
Type []
G e t G e n e r i c A r g u m e n t s ()



,
,
,
.

17. ,

543

M e m b e r l n f o []
G e t M e m b e r s ()
M e t h o d l n f o []
G e t M e t h o d s ()
P r o p e r t y l n f o []
GetProperties ()

, .
( 18.)


,
.

Assembly Assembly
TypeAttributes Attributes
Type BaseType
string FullName
bool IsAbstract
bool isArray
bool IsClass
bool IsEnum
bool IsGenericParameter

bool IsGenericType
string Namespace






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



. .
,
. ,
, .
Reflection API
. !
Reflection API ,
, , .
,
: , ,
.

544

I. #


, ,
, G etMethods ().
, .
MethodInfo[]

GetMethods()

M e t h o d l n f ,
, . M e t h o d l n f o
System.Reflection.
Methodlnfo MethodBase,
M ember Inf .
, . ,
Name.
Methodlnfo: ReturnType GetParameters ().

ReturnType, .
GetParameters () ,
. .
Parameterlnf [] GetParameters();

P a r a m e t e r Inf .
P a r a m e t e r l n f , .
: Name ,
, a 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;

17. ,

public void Set(int a, int b)


x = a;
= b;

}
public void Set(double a, double b)
x = (int) a;
= (int) b;

}
public void Show() {
Console.WriteLine(" x:

{0}, :

{1}", x, y) ;

}
}
class ReflectDemo {
static void Main() {
Type t = typeof(MyClass); // Type,
// MyClass
Console.WriteLine(" , " +
" " + t.Name);
Console.WriteLine ();
Console.WriteLine(" :

");

MethodInfo[] mi = t .GetMethods();
// , MyClass.
foreach(Methodlnfo m in mi) {
// .
Console.Write(" " + m.ReturnType.Name + " " + m.Name + "(");
// .
Parameterlnfo[] 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(", ");

}
Console.WriteLine(")");
Console.WriteLine();

}
}
}
.
,

MyClass

:
Int32 S u m ()

545

546

I. #

Boolean IsBetween (Int32 i)


Void Set(Int32 a, Int32 b)
Void Set (Double a, Double b)'
Void Show()
String ToSt r i n g ()
Boolean Equals(Object obj)
Int32 GetHashCode()
Type G e t T y p e ()

, , MyClass,
, obj e c t ,
C# obj e c t . ,
.NET. , S et () ,
. in t,
double.
. ,
M yClass ,
S e t ().
, MyClass, Main ()
.
Type t = typeof(MyClass); // ,
// MyClass

, ty p e o f ,
( MyClass).
t R eflectio n API
, MyClass.

.
MethodInfo[]

mi = t .GetMethods();

fo r e a c h mi.
,
, .
foreach(Methodlnfo m in mi) {
// .
Console.Write(" " + m.ReturnType.Name + " " + m.Name + "(");
// .
Parameterlnfo[] pi = m.GetParameters();
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name + " " + pi[i],Name);
if (i + 1 < pi.Length) Console.W r i t e (", ");

17. ,

547

, ,
Ge t P arameters () pi.
for p i n
. ,
,
MyClass.

GetM ethods ()
GetMethods (),
.
GetMethods ().
MethodInfo[]

GetMethods(BindingFlags )

,
. B indingFlags .
.

DeclaredOnly
Instance
NonPublic
Public
Static

, .


,


. I n s t a n c e S t a t i c
Public Non Pub lie.
.
B i n dingFlag s GetMethods ()
, ,
. ,
, .
GetMethods ()
.
// ,
// MyClass.
MethodInfo[] mi = t .GetMethods(BindingFlags.DeclaredOnly
BindingFlags.Instance |
BindingFlags.Public);

.
,

MyClass

:
Int32 Sum ()
Boolean IsBetween(Int32 i)

548

I. #

Void Set(Int32 a, Int32 b)


Void Set(Double a, Double b)
Void Show()

, ,
MyClass.


, ,
, . Invoke (),
Methodlnf . :
object Invoke(object o b j ,

obj e c t [] p a r a m e te rs)

o b j , .
(static) o b j (null).
, ,
p a r a m e t e r s . , p a r a m e t e r s
(null). , p a r a m e t e r s
. ,
, p a r a m e t e r s ,
. , ,
Invoke (), .
Invoke ()
Methodlnf , 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) {
i f ((x < i) && (i < y ) ) return true;
else return false;

17. ,
public void Set (int a, int b) {
Console.W r i t e (" Set (int, int).
x = a;
= b;
S h o w ();

") ;

// Set.
public void Set(double a, double b) {
Console.Write(" Set(double, double).
x = (int) a;
= (int) b;
Show () ;

public void Show() {


Console.WriteLine(" x:

");

{0}, :

{1}", x, );

}
}
class InvokeMethDemo {
static void Main() {
Type t = typeof(MyClass);
MyClass reflectOb = new M y C l a s s (10, 20);
int val;
Console.WriteLine(" , " + t.Name);
Console.WriteLine();
MethodInfo[] mi = t .GetMethods();
// ,
foreach(Methodlnfo m in mi) {
// .
Parameterlnfo[] pi = m.GetParameters();
if(m.Name.C o m pareTo("Set")==0 &&
p i [0].ParameterType == typeof(int))
object[] args = new object[2];
args[0] = 9;
args[l] = 18;
m. Invoke(reflectOb, args);

}
else if(m.Name.CompareTo("Set") ==0 &&
p i [0].ParameterType == typeof(double)) {
object[] args = new object[2];
a r g s [0] = 1.12;
a r g s [1] = 23.4;
m. Invoke(reflectOb, args);

}
else if(m.Name.CompareTo("Sum")==0) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(" " + val);

}
else if(m.Name.CompareTo("IsBetween")==0)

549

550

I. C#
o b j e c t [] args = new obje c t [1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.W riteLine(" 14 x ");

}
else if(m.Name.CompareTo("Show")==0)
m.Invoke(reflectOb, null);

.
,

MyClass

30
14
Set (int, int). : 9, : 18
Set(double, double). : 1, : 23
: 1, : 23

. .
for each .

if/else.
Set () .
if(m.Name.CompareTo("Set")==0 &&
p i (0].ParameterType == typeof(int)) {
o b j e c t [] args = new o bject[2];
args[0] = 9;
args[l] = 18;
m.Invoke(reflectOb, args);

}
else if(m.Name.CompareTo("Set")==0 &&
p i [0].ParameterType == typeof(double)) {
o b j e c t [] args = new object[2];
args[0] = 1.12;
a r g s [1 ] = 23.4;
m.Invoke(reflectOb, args);

}
Set, ,
. , Set (int, int),
a rg s.
double.


, MyClass,
, MyClass
.
.
, .

17. ,

551

,
, .
,
.

GetConstructors () .
.
Constructorlnfo[] GetConstructors()

GetConstructors () Constructorlnfo,
.
C o n s t r u c t o r l n f o
MethodBase, M e m b e r l n f .
.
G e t C o n s t r u c t o r s ( ) , ,
. ,
GetParameters (), M e t h o d l n f .
,
Invoke (), Constructorlnfo.
.
object Invoke(object[] p a r a m e t e r s )

, ,
p a r a m e t e r s . , p a r a m e t e r s
(null).
p a r a m e t e r s ,
. Invoke ()
.

MyClass.
// .
using System;
using System.Reflection;
class MyClass
int x;
int y;

public MyClass(int i) {
Console.WriteLine(" MyClass(int,
x = = i;

int).

");

int).

");

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

55 2

I. C#

public int S u m () {
return x+y;

}
public bool IsBetween (int i) {
i f ((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(" (double, double).
x = (int) a;
= (int) b;
S h o w ();

");

}
public void Show() {
Console.WriteLine(" x:

{0}, :

{1}", x, );

}
}
class InvokeConsDemo {
static void Main() {
Type t = typeof(MyClass);
int val;
// .
Constructorlnfo[] ci = t .GetConstructors();
Console.WriteLine(" :
foreach(Constructorlnfo in ci) {
// .
Console.Write(" " + t.Name + "(");

");

// .
Parameterlnfo[] pi = .GetParameters() ;
for(int i=0; i-< pi.Length; i++) {
Console.Wr i t e ( p i [i ].ParameterType.Name + " " + pi[i].Name);
if (i + 1 < pi.Length) Console.W r i t e (", ");

}
Console.WriteLine(")");

}
Console.WriteLine() ;

17. ,
// ,
int ;
for(x=0; < ci.Length; ++) {
Parametgrlnfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;

}
if (x == ci.Length) {
Console.WriteLine(" .");
return;

}
else
Console.WriteLine(" .\n");
// ,
object[] consargs = new obje c t [2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[ x ] .Invoke(consargs) ;
Console.WriteLine(" reflectOb.");
Console.WriteLine() ;
MethodInfo[] mi = t .GetMethods() ;
// ,
foreach(Methodlnf m in mi) {
// .
Parameterlnfo[] pi = m.GetParameters() ;
if(m.Name.CompareTo("Set")==0 &&
p i [0].ParameterType == typeof(int))
// Set (int, int).
object[] args = new obj e c t [2];
args[0] = 9;
args[l] = 18;
m. Invoke(reflectOb, args);

}
else if(m.Name.Comp a r e T o ("Set")==0 &&
p i [0].ParameterType == typeof(double)) {
// Set(double, double),
o bject[] args = new object[2];
a r g s [0] = 1 . 1 2 ;
1
args[l] = 23.4;
m. Invoke(reflectOb, args);

}
else if(m.Name.CompareTo("Sum")==0) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(" " + 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 x ");

5 53

554

1/ C#
else if(m.Name.CompareTo("Show")==0)
m.Invoke(reflectOb, null);

}
}
}
}
.
:
M y C l a s s (Int32 i)
M y C l a s s (Int32 i, Int32 j)
.
MyClass(int,
: 10, : 20

int)

reflectOb
30
14
Set(int, int). : 9, : 18
Set(double, double). : 1, : 23
: 1, : 23


MyClass.
.
Constructorlnfo[] ci = t .GetConstructors();

.
, ,
.
for(x=0; < ci.Length; ++) {
Parameterlnfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;

}
, ,
.
// ,
o b j e c t [] consargs = new o bject[2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = c i[x].Invoke(consargs);

Invoke () reflectOb
MyClass.
.
, , ,
i n t . ,

.

17. ,

555


MyClass
, : MyClass.
,
, M yClass
ty p e o f ,

. ,
,

.
16, ,
, .
Reflection API ,
. ,

,
. . ,
, , " ",
, , ,
,
. ,
.

Assembly. Assem bly .
Assem bly . ,
LoadFrom ( ).
:
static Assembly LoadFrom(string _)

_ - .
Assem bly,
, Get Types ()
.
[] GetTypesO

, .
,
. ,
. M yC lasses . c s ,
.
// ,

MyClasses.cs.

using System;
class MyClass
int x;
int y;

556

I. C#

public MyClass(int i) {
Console.WriteLine(" MyClass(int). ");
x = = i;
Show () ;

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

int).

= j;
S h o w ();

}
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,
x = a;
= b;
S h o w ();

int).

");

}
// . Set.
public void Set(double a, double b) {
Console.W r i t e (" Set(double, double).
x = (int) a;
= (int) b;
Show () ;

");

}
public void Show() {
Console.WriteLine (" x:

{0}, :

}
}
class AnotherClass {
string msg;
public AnotherClass(string str)
msg = str;

}
public void S h o w () {
Console.WriteLine(msg);

}
}

{1}", x, );

") ;

17. ,

557

class Demo {
static void Main() {
Console.WriteLine(" .");

}
}
MyClass,
. , An o t h e r C l a s s
Demo. , , ,
, . ,
MyClasses ..
.
,
MyClasses .. .
/* ,
. */
using System;
using System.Reflection;
class ReflectAssemblyDemo
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 = .GetParameters();
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name + " " + pi[i].Name);
if(i+1 < pi.Length) Console.W r i t e (", ");

558

I. C#
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");
// ,
o b j e c t [] consargs = new o b j e c t [2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs) ;
Console.WriteLine("\ reflectOb.");
Console.WriteLine();
M ethodlnfo[] mi = t .GetMethods();
// ,
foreach(Methodlnfo m in mi) {
// .
Parameterlnfo[] pi = m.GetParameters();
if(m.Name.CompareTo("Set")==0 &&
p i [0].ParameterType == typeof(int))
// Set(int, int).
o b j e c t [] args = new o b j e c t [2];
a r g s [0] = 9;
args[l] = 18;
m.Invoke(reflectOb, args) ;

}
else if(m.Name.CompareTo("Set")==0 &&
p i [0].ParameterType == typeof(double)) {
// Set(double, double).
o b j e c t [] args = new o b j e c t [2];
a r g s [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.W r i teLine(" " + val);

}
else if(m.Name.CompareTo("IsBetween")==0)
o b j e c t [] args = new obj e c t [1];

17. ,

559

a r g s [0] = 14;
if(<bool) m .Invoke (reflectOb, args))
Console.WriteLine(" 14 x ");

}
else ifjm.Name.C ompareTo("Show")==0)
m.Invoke(reflectOb, null);

.
: MyClass
: AnotherClass
: Demo
: MyClass
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)
.
MyClass(int,
: 10, : 20

int)

reflectOb
30
14
Set (int, int) . : 9, : 18
Set(double, double). : 1, : 23
: 1, : 2 3

,
, l a s s e s . .
MyClass,
.
M y C l a s s e s .
, 1 ().
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.") ;
// , MyClasses.exe.
[] alltypes = a s m .GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(": " + temp.Name);

,
.

. .

560

I. C#

(DLL) . d l l . , l a s s e s . cs
:
csc /t:library MyClasses.es

MyClasses .d l l .
DLL , , , Main ()
,
, .
Demo Main () . DLL
Main () . MyClass DLL,
LoadFrom () .
Assembly asm = Assembly.LoadFrom("MyClasses.dll");


,
.
MyClass ,

MyClass. , S et Sum
. ,
. ,
.
, ,
,
, .
,
. MyClasses . ,
MyClass ,
MyClass, .
// MyClass,

using System;
using System.Reflection;
class ReflectAssemblyDemo {
static void Main() {
int val;
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
Type[]

alltypes = asm.GetTypes();

Type t = a l l types [0]; //


Console.Write L i n e (": " + t.Name);
Constructorlnfo [.] ci = t .GetConstructors () ;
// .
Parameterlnfo[] cpi = c i [0].GetParameters();
object reflectOb;

17. ,

if (cpi.Length > 0) {
object[] consargs = new object[cpi.Length];
// ,
fox (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();
// .
MethodInfo[] mi = t .GetMethods(BindingFlags.DeclaredOnly
BindingFlags.Instance |
BindingFlags.Public);

// ,
foreach(Methodlnfo m in mi) {
Console.WriteLine(" {0} ", m.Name);
// .
Parameterlnf [] 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 (pi[0] .ParameterType == typeof(int)) {
object[] args = new object[1];
args[0] = 14;
if ((bool) m.Invoke(reflectOb, args))
Console.WriteLine (" 14 x ");
else
Console.WriteLine (" 14 ");

}
break;
case 2: //
i f ((pi[0].ParameterType == typeof(int)) &&
(pi[1].ParameterType == typeof(int)))
o b ject[] args = new object[2];
args[0] = 9;

561

562

I. C#
args[l] = 18;
m.Invoke(reflectOb,

args);

}
else i f ( (pi[0] .ParameterType == typeof(double)) &&
(pi[1].ParameterType == typeof(double))) {
o b j e c t [] args = new object [2];
args[0] = 1J12;
args[l] = 23.4;
m.Invoke(reflectOb, args);

}
break;

}
C onsole.W riteLine();

}
}
}
.
: MyClass
MyClass(int).
: 10, : 10
reflectOb.
Sum
: 20
IsBetween
14
Set
Set (int,

int). : 9, : 18

Set
Set(double,

double). : 1, : 23

Show
: 1, : 23

, .
-, ,
MyClass. BindingFlags GetMethods (),
, . -,
,
switch.
.

C#
,
(), , , .. ,

17. ,

5 63

, ,
. ,
. , ,
, .


, S y s t e m .Attribute.
Attribute.
Attribute ,
.
Attribute. , E rro r A t t r i b u t e ,
.

AttributeUsage. ,
. ,
.


, .

. , ,
, .
.
[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;

}
}
}
.
Rem a r k A t t r i b u t e .
A t t r i b u t e U s a g e , ,
RemarkAttribute .
A ttributeUsage ,
.
.
RemarkAttribute, Attribute.
Re m a r k A t t r i b u t e pri_remark,
Remark.
, . (, R e m a r k

564

I. C#

set,
, .)
,
Remark.
RemarkAttribute, .


,
. , ,
.
, RemarkAttribute .
[RemarkAttribute(" .")]
class UseAttrib {

//

...

}
RemarkAttribute,
" . 11
UseAttrib.
, Attribute.
, .
[Remark(" .")]
class UseAttrib {

//

..

}
Remark.
,
, .


,
.
. , GetCustomAttributes (), Memberlnf
. ,
. .
ob j e c t [] GetCustomAttributes(bool )

true,
, .
,
.
, GetCu s t o m A t t r i b u t e (), Attribute.
:
static Attribute GetCustomAttribute(Memberlnf , _)

Member Inf , ,
, _ .
, ,

17. ,

565

. , UseAttrib RemarkAttribute,

.
// MemberInf,
// , RemarkAttribute.
Type t = typeof(UseAttrib);
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);

,
M e m berlnfo . , t
Memberlnfo.

, .
, ,
. ,
Remark.
Console.WriteLine(.Remark);

,
RemarkAttribute.
// .
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 {
static void Main() {
Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": ");

566

I. C#
o b j e c t [] attribs = t .GetCustomAttributes(false);
foreach(object in attribs) {
Console .WriteLine ( ).;

}
Console.W r i t e (": ");
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.Remark);

}
}
.
UseAttrib: RemarkAttribute
: .


R e m a r k A t t r i b u t e

. c omment R e m a r k A t t r i b u t e ()
. ,
. ,
, ..
,
. ,
.
'

, ,
, .
,
.

.
,
. ,
.
[ a t t r i b (_ _ ,
__1 = ,
__2 = , ...)]

, .
.

17. ,

567

.
, ,
.

. R e m a kAttribute,
Supplement, .
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // Remark
// ,
public string Supplement;
public RemarkAttribute(string comment)
pri_remark = comment;
Supplement = "";

}
public string Remark {
get {
return pri_remark;

}
}
}
, Supplement
"".
. Supplement
RemarkAttribute, ,
.
[RemarkAttribute(" .",
Supplement = " .")]
class UseAttrib {

//

...

}
RemarkAttribute.
, , ,
Supplement,
. , , ), , . , .
:
, ,
.
,
Supplement .
// .
using System;
using System.Reflection;

568

!. C#

[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // Remark
public string Supplement;

//

public RemarkAttribute(string comment)


pri_remark = comment;
Supplement = "";

}
public string Remark {
get {
return pri_remark;

}
}
}
[RemarkAttribute(" .",
Supplement = " .")]
class UseAttrib {

//

...

}
class NamedParamDemo {
static void Main() {
Type t = typeof(UseAttrib);
Console.W r i t e (" " + t.Name + ": ");
o b j e c t [] attribs = t .GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine (o);

}
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.W r i t e (": ");
Console.WriteLine(ra.Remark);
Console.W r i t e (": ") ;
Console.WriteLine(ra.Supplement);

}
}
.
UseAttrib: RemarkAttribute
: .
: .

, ,
p ri_ re m a rk ,

17. ,

569

RemarkAttribute. Remark
, .
,
.

, .
, Priority int
RemarkAttribute.
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // Remark
public string Supplement;

//

public RemarkAttribute(string comment)


pri_remark = comment;
Supplement = "";
Priority = 1;

}
public string Remark {
get {
return pri_remark;

}
}
// ,
public int Priority { get; set; }

}
[RemarkAttribute(" .",
Supplement = " .",
Priority = 10)]
class UseAttrib {

//

. . .

}
class NamedParamDemo {
static void Main() {
Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": ");
object[] attribs = t .GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine(o);

570

!. C#
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute = (RemarkAttribute)
A ttribute.GetCustomAttribute(t, tRemAtt);
Console.Write(": ") ;
Console.WriteLine(ra.Remark);
Console.W r i t e (": ") ;
Console.WriteLine(ra.Supplement);
Console.WriteLine(": " + r a .Priority);

}
}
.
UseAttrib: RemarkAttribute
: .
: .
: 10


U s e A ttrib , .
[RemarkAttribute(" .",
Supplement = " .",
Priority = 10)]
class UseAttrib {

//

...

}
Supplement P r i o r i t y
- .
, .
: ( ,
) , o b je c t, ,
.


C# ,
, .
AttributeUsage, Conditional Obsolete, .

A t t r ib u t e U s a g e
, A t t r i b u t e U s a g e ,
. A t t r i b u t e U s a g e ,
, System. AttributeUsageAttribute.
:
AttributeUsage(AttributeTargets validO n)

17. ,

571

v a lid O n ,
, A t t r ibuteTargets ,
.

Delegate
GenericParameter
Parameter

Asse mb l y
Enum
Interface
Property

Class
Event
Method
ReturnValue

Constructor
Field
Module
Struct


. , , ,
.
AttributeTargets.Field

I AttributeTargets.Property

Att ributeUsage .
AllowMultiple,
. ,
. , Inherited,
. ,
, . AllowMultiple
(false), Inherited (true).
Attr i b u t e U s a g e
ValidOn. AttributeTargets,
, .
AttributeTargets .All.

C o n d it io n a l
C o n d i t i o n a l , ,
. ,
, #define
, . ,
# if.
C o n d i t i o n a l , , S y s t e m .
Diagnostics .ConditionalAttribute. Conditional
System. Diagnostics.
.
// Conditional.
#define TRIAL
using System;
using System.Diagnostics;
class Test {
[Conditional("TRIAL")]
void T r i a l () {
Console.WriteLine(" , " +
" .");

572

I. C#

[Conditional("RELEASE")]
void Release () {
Console.W r i teLine(" .");

}
static void Main() {
Test t = new Test();
t.Trial();

// ,
// TRIAL
t. R e leaseO; // ,
// RELEASE

}
}
.
,

,
. ,
TRIAL. Trial ()
R elease (). Conditional,
:
[Conditional ]

,
. .
, , .
, .
, Trial () n R e l e a s e ( ) , Mai n ().
TRIAL, Trial ( ) ,
R e l e a s e () .
RELEASE, Release () .
TRIAL, Trial () .
C o n d i t i o n a l , .. ,
Attribute. , ,
, .
.
. -,
void, , . -,
, . -,
override.

O b s o le te
Obsolete ( System. Obso-leteAttribute)
.
:
[Obsolete (" ") ]

17. ,

573

,
. .
// Obsolete,
using System;
class Test {
[Obsolete(" MyMeth2.")]
public static int MyMeth(int a, int b) {
return a / b;

}
// MyMeth.
public static int MyMeth2(int a, int b) {
return b == 0 ? 0 : a /b;

}
static void Main() {
// .
Console. Writeliine ("4 / 3 " + Test .MyMeth (4, 3) ) ;
/ / .
Console.WriteLine("4 / 3 " + Test.MyMeth2(4, 3));

}
}
Main ()
, ,
M y M e t h 2 ().
Obsolete:

M y M e t h (),

[Obsolete (" ",

)]

. (true),

. , ,
, .



#. ,

1 . 0 2 .0 ,
#.
,
#.
,

.
,

C# .
,
, ,
,
.
,
,
. , , ,
,
in t, s t r i n g , o b je c t
, .


.

,
- .

576

I. C#

, ,
,
, .
25,
,
.


, , .
, ,
, , ,
. , ,
,
. , , , , , , , ,
.
, C#
, object. object
, o b j e c t
. ,
,
object.
, ,
ob j ect
. - ,
.
, ,
. , ,

. ,
.

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


.
.
Gen, Generics Demo, Gen.

18.
// ,
using System;
/ / Gen
// Gen.
class Gen<T> {
ob; //
// ,
public Gen(T ) {
ob = ;

}
// ob, .
public GetObO {
return ob;

}
// .
public void ShowTypeO {
Console.WriteLine(" T " + typeof ());

}
}
// ,
class GenericsDemo {
static void Main() {
// Gen int.
Gen<int> iOb;
// Gen<int> iOb
iOb = new Gen<int> (102);
// , iOb.
iOb.ShowType();
// iOb.
int v = iOb.GetOb();
Console.WriteLine(": " + v) ;
Console.WriteLine();
// Gen .
Gen<string> strOb = new Gen<string>(" .");
// , strOb.
strOb.ShowType();
// strOb.
string str = strOb.GetOb ();
Console.WriteLine(": " + str);

578

I. #

.
' System.Int32
: 102
System.String
: .

.
Gen :
class Gen<T> {

. -
, Gen. ,
Gen , .
, (< >).
: , ,
. Gen,
.
Gen ,
.
V . , , ,
TValue .
.
ob,
.
ob; //

, -
, Gen.
ob , Gen.
, string,
ob string.
Gen.
public Gen(T ) {
ob = ;

}
, . ,
,
Gen. ob
, Gen
.
,
, GetOb ().
public GetOb() {
return ob;

}
ob , ,
GetOb ().

18.

579

ShowType () , typeof.
Gen,
typeof .
Gen e r i c s Demo Gen.
Gen int.
Gen<int> iOb;

.
, int Gen.
int , Gen.
Gen, int
, . , int
ob GetOb ().
iOb
Gen int.
iOb = new Gen<int> (102);

, Gen
int. , (
iOb), , Gen<int>. ,
new, Gen<int>.
. ,
.
iOb = new Gen<double>(118.12); // !

iOb Gen<int>
Gen<double>.
, .
ob iOb System.
Int 32. .NET, int. ob
.
int v = iOb.GetOb ();

G etOb () ,
int iOb, GetOb ()
int. ,
v int.
GenericsDemo Gen<string>.
Gen<string> strOb = new Gen<string>(" .");

string, Gen
string. Gen string,
.
,
. Gen , int string,
C# . , Gen<int>
. , ,
, Gen<T>, . ,
, Gen<int>, .

580

I. C#

, Gen<T>, C# ,
, , int.
C# , .
,
. ,
, .
, .
,
. ,
.


, ,

. ,
, .
iOb = strOb; // !

, iOb strOb, Gen<T>,


, .


:
Gen
,
, , Gen ?
,
, Gen.

.
,
, Gen.
// NonGen
// Gen, .
using System;
class NonGen {
object ob; // ob object
// object,
public NonGen(object ) {
ob = ;

}
// object,
public object GetObO {
return ob;

18.
}
// ob.
public void ShowTypeO {
Console.WriteLine(" ob: " + o b .GetType());

}
}
// ,
class NonGenDemo {
static void Main() {
NonGen iOb;
// NonGen.
iOb = new NonGen(102);
// , iOb.
iOb.ShowType();
// iOb.
/ / ,
int v = (int) iOb.GetObO;
Console.WriteLine(": " + v);
Console.WriteLine();
// NonGen
// it.
NonGen strOb = new NonGen(" ");
// , strOb.
strOb.ShowType();
// strOb.
/ / .
String str = (string) strOb.GetOb();
Console.WriteLine(": " + str);
// , !
iOb = strOb;
//
// .
// v = (int) iOb.GetObO; // !

}
}
.
ob: System.Int32
: 102
ob: System.String
:

581

58 2

!. #

, ,
.
.
, , Non Gen.
Non Gen ,
. . -,
. -,

. .
.
int v = (int) iOb.GetObO;

GetOb () object, ,
, GetOb (),
v int.
, .
, int
iOb.
. ,
.

.
// , !
iOb = strOb;
//
// .
// v = (int) iOb.GetObO; // !

strOb iOb.
strOb , ,
. ,
NonG e n , ,
No n G e n NonGen.
,
. ,
G etOb (), int,
int. ,
.
,
int. ,
, , .
.
,
.
, ,
, ,
.
,

18.

5 83

, . C#
"" ,
, , .. ,

. . ,
.
.

. , ob
NonGen ShowType () .
Console.WriteLine(" ob: " + o b .GetType ());

11, object ,
. GetType (),
, .
, , ob,
, , ob
object. CLR

.


.
.
TwoGen, Gen
.
// V.
using System;
class TwoGenCT, V> {
T obi;
V ob2;
// ,
// V.
public TwoGen( ol, V 2) {
obi = ol;
2 = 2;

}
// V.
public void showTypes() {
Console.WriteLine(" T " + typeof());
Console.WriteLine(" V " + typeof(V));

}
public getobl()

584

I. C#
return obi;

}
public V Get0bj2()
return ob2;

}
}
// ,
class SimpGen {
static void Main() {
TwoGenCint, string> tgObj =
new TwoGenCint, string>(119,

" ");

// .
tgObj.showTypes();
// ,
int v = tgObj.getobl();
Console.WriteLine(": " + v) ;
string str = tgObj.GetObj2();
Console.WriteLine(": " + str);

}
}
.
System.Int32
V System.String
: 119
:

, TwoGen.
class TwoGenCT, V> {

V, .
TwoGen ,
, .
TwoGenCint, string> tgObj =
new TwoGenCint, string>(119,

" ");

int, V string.
,
. ,
.
TwoGencstring, string> =
new TwoGencstring, string>("Hello",

"Goodbye");

, V, , string. ,
,
.

18.

585


, ,
. .
class _<__> { // ...

.
_<__> _ =
new _<__> (__) ;



. , ,
.
class Gen<T> {

, Gen,
int, double, string, FileStream
.
, ,
.
, , ,
FileStream MemoryStream. ,
, -
,
, int . , -
, , ,
. , - ,
Read ().
^ C# .
, .
where :
class _<_> where _ : { // ...

.
C# .
,
.
.
, ,
.
.
,
.
.

586

I. #

,
.
new ().
,
c l a s s .
,
s t r u c t .

, .
.


,
.
. -,
, . , ,
.
,
. ,
, ,
.
-,
, .
, , ,
.
,
,
.
/
,
where:
where : __

, _ _
.
.

.
// ,
// .
using System;
class {
public void Hello () {
Console.WriteLine("Hello");

18.

587

// .
class : { }
// .
class '{ }
/ / ,
// Test, .
class Test<T> where : {
obj;
public Test( )
obj = ;

}
public void SayHelloO {
// Hello() , .
obj.Hello();

}
}
class BaseClassConstraintDemo
static void Main() {
A a = new A ();
b = new ()
= new ()j
// , .
Test<A> tl = new Test<A>(a);
t l .SayHello();
// , .
Test<B> t2 = new Test<B> (b);
t 2 .SayHello();
// , .
// Test<C> t3 = new Test<C>(c); // !
// t3 .SayHello(); // !

}
}
,
. , Hello (),
Test .
class Test<T> where : {

where :
, , .
, T e s t
SayHello (), .

588

I. C#

public void SayHelloO {


// Hello () , .
obj.Hello();

}
Hello () obj .
, Hello ()
: ,
, ,
Hello (). ,
Hello (). ,
, Hello ()
. , where
Test. ,
Hello () .
,
,
, .
.
// Test<C> t3 = new Test<C>(c); // !
// t 3 .SayHello(); // !

,
Test. ,
.
,
. -,
. -,
,
, .
,
, , .
, ,
. ,
,
, , , ..
PhoneNumber,
. .
// , ,
class PhoneNumber {
public PhoneNumber(string n, string num) {
Name = n;
Number = num;

}
// ,
// ,
public string Number { get; set; }
public string Name { get; set; }

18.

589

, PhoneNumber: F r i e n d Supplier.
.
// ,
class Friend : -PhoneNumber {
public Friend(string n, string num, bool wk)
base(n, num)

{
IsWorkNumber = wk;

}
public bool IsWorkNumber { get; private set;

...

}
// ,
class Supplier : PhoneNumber {
public Supplier(string n, string num) :
base(n, num) { }

//

. . .

}
, Friend IsWorkNumber,
true, .

PhoneList. ,
.
, ,
, ,
, , , ,
PhoneNumber.
// PhoneList
// , , PhoneNumber.
class PhoneList<T> where T : PhoneNumber {
T [] phList;
int end;
public PhoneList() {
phList = new T[10];
end = 0;

}
// ,
public bool Add(T newEntry) {
if(end == 10) return false;
phList[end] = newEntry;
end++;
return true;

590

I. C#

//
public FindByName(string name)
for(int i=0; i<end; i++) {
// ,
//
//
if(phList[i].Name == name)
return phList[i];

,
{
Name
PhoneNumber,
,

}
// .
throw new NotFoundException();

}
// ,
public FindByNumber(string number) {
for (int i=0; i<end; i++) {
// ,
// Number PhoneNumber,
// ,
if(phList[i].Number == number)
return phList[i];

}
// ,
throw new NotFoundException();

}
//

...

}
PhoneList
Name Number .
, PhoneList
. , PhoneList
NotFoundException, .
, .
class NotFoundException : Exception {
/* Exception.
.
NotFoundException Exception
. */
public NotFoundException() : base() { }
public NotFoundException(string str) : base (str) { }
public NotFoundException(
string str, Exception inner) : base(str, inner) { }
protected NotFoundException(
System.Runtime.Serialization.Serializationlnfo si,
System.Runtime.Serialization.StreamingContext sc) :
base(si, sc) { }

18.

591

, ,
N otFoundException
, Exception.
, ,
.Exception. N o t F o u n d E x c e p t i o n
Exception,
.

, Phone L i s t .
, E m a i l Friend.
PhoneNumber, ,
PhoneList.
// ,
// .
using System;
// , ,
// ,
class NotFoundException : Exception {
/* Exception.
.
NotFoundException Exception
. */
public NotFoundException ()
base() { }
public NotFoundException(string str) : base(str) { }
public NotFoundException (
string str,Exception inner) : base(str, inner) { }
protected NotFoundException(
System.Runtime.Serialization.Serializationlnf si,
System.Runtime.Serialization.StreamingContext sc) :
base (si, sc) { }

}
// , ,
class PhoneNumber {
public PhoneNumber(string n, string num) {
Name = n;
Number = num;

}
public string Number { get; set; }
public string Name { get; set; }

}
// ,
class Friend : PhoneNumber {
public Friend(string n, string num, bool wk)
base(n, num)

{
IsWorkNumber = wk;

592

I. C#

}
public bool IsWorkNumber { get; private set;

//

...

}
// ,
class Supplier : PhoneNumber {
public Supplier(string n, string num) :
base(n, num) { }

/ / ...
}
// PhoneNumber.
class EmailFriend {

//

. . .

}
// PhoneList ,
// , PhoneNumber.
class PhoneList<T> where T : PhoneNumber {
T [] phList;
int end;
public PhoneList() {
phList = new T[10];
end = 0;

}
// ,
public bool Add(T newEntry) {
if(end == 10) return false;
phList[end] = newEntry;
end++;
return true;

}
// ,
public FindByName(string name) {
for(int i=0; i<end; i++) {
// , Name
// PhoneNumber,
// ,
if(phList[i].Name == name)
return phList[i];

}
// ,
throw new NotFoundException() ;

18.

// ,
public FindByNumber(string number) {
for(int i=0; i<end; i++) {
// " ,
// Number PhoneNumber,
// ,
if(phList[i].Number == number)
return phList[i] ;

}
// .
throw new NotFoundException ();

}
//

. . .

// ,
class UseBaseClassConstraint {
static void Main() {
// ,
// Friend PhoneNumber.
PhoneList<Friend> plist = new PhoneList<Friend>();
plist.Add(new Friend("", "555-1234", true));
plist.Add(new Friend("", "555-6756", true));
plist.Add(new Friend("", "555-9254", false));
try {
// .
Friend frnd = plist.FindByName("") ;
Console.Write(frnd.Name + ": " + frnd.Number);
if(frnd.IsWorkNumber)
Console.WriteLine(" ()") ;
else
Console.WriteLine ();
} catch(NotFoundException) {
Console.WriteLine("He ");

}
Console.WriteLine();
// ,
// Supplier PhoneNumber.
PhoneList<Supplier> plist2 = new PhoneList<Supplier>();
plist2.Add(new Supplier(" Global Hardware", "555-8834"));
plist2.Add(new Supplier (" Computer Warehouse", "555-9256"));
plist2.Add(new Supplier(" NetworkCity", "555-2564"));
try {
// .
Supplier sp = plist2.FindByNumber("555-2564");
Console.WriteLine(sp.Name + ": " + sp.Number);

5 93

594

I. C#
} catch(NotFoundException) {
Console.WriteLine("He ");

}
// ,
// EmailFriend PhoneNumber.
// PhoneList<EmailFriend> plist3 =
// new PhoneList<EmailFriend>(); // !

}
}
.
: 555-6756 ()
NetworkCity: 555-2564

. ,
IsWorkNumber
PhoneList. ,
, IsWorkNumber Friend,
PhoneNumber, , PhoneList.


,
. ,
. -,
. -,
, . ,
, ,
, .
,
where:
where : _

, _
.
.
, .
,

, .
PhoneNumber I PhoneNumber,
Friend Supplier.
// ,
using System;
// , ,
// ,
class NotFoundException : Exception {

18.
/* Exception.
.
NotFoundException Exception
. */
public NotFoundException() : base() { }
public NotFoundException(string str) : base(str) { }
public NotFoundException(
string str,Exception inner) : base(str, inner) { }
protected NotFoundException (
System.Runtime.Serialization.Serializationlnfo si,
System.Runtime.Serialization.StreamingContext sc) :
base(si, sc) { }

}
// , ,
public interface IPhoneNumber {
string Number {
get;
set;

}
string Name {
get;
set;

}
}
// .
/ / IPhoneNumber.
class Friend : IPhoneNumber {
public Friend(string n, string num, bool wk)
Name = n;
Number = num;

IsWorkNumber = wk;

}
public bool IsWorkNumber { get; private set;
// IPhoneNumber.
public string Number { get; set; }
public string Name { get; set; }

//

. . .

}
// ,
class Supplier : IPhoneNumber {
public Supplier(string n, string num) {
Name = n;
Number = num;

595

596

I. C#

}
// IPhoneNumber.
public string Number { get; set; }
public string Name { get; set; }

/ / ...
}
// IPhoneNumber ,
class EmailFriend {

/ / ...
}
// PhoneList
// , , PhoneNumber.
class PhoneList<T> where T : IPhoneNumber {
T [] phList;
int end;
public PhoneList() {
phList = new T[10];
end = 0;

}
public bool-Add(T newEntry) {
if(end == 10) return false;
phList[end] = newEntry;
end++;
return true;

}
// ,
public FindByName(string name) {
for(int i=0; i<end; i++) {
// , Name
// IPhoneNumber,
// ,
if(phList[i].Name == name)
return phList[i];

}
// ,
throw new NotFoundException();

}
// ,
public FindByNumber(string number) {
for(int i=0; i<end; i++) {
// ,
// Number IPhoneNumber,
// .

18.
if(phList[i].Number == number)
return phList[i];

}
// ,
throw new NotFoundException();

}
//

. . .

// ,
class UselnterfaceConstraint {
static void Main() {
// ,
/ / Friend IPhoneNumber.
PhoneList<Friend> plist = new PhoneList<Friend>();
plist.Add(new Friend("", "555-1234", true));
plist.Add(new Friend("", "555-6756", true));
plist.Add(new Friend("", "555-9254", false));
try {
// .
Friend frnd = plist.FindByName("") ;
Console.Write(frnd.Name + ": " + frnd.Number);
if(frnd.IsWorkNumber)
Console.WriteLine (" ()");
else
Console.WriteLine();
} catch(NotFoundException) {
Console.WriteLine("He ");

}
Console.WriteLine();
// , Supplier
// IPhoneNumber.
PhoneList<Supplier> plist2 = new PhoneList<Supplier>();
plist2.Add(new Supplier(" Global Hardware", "555-8834"));
plist2.Add(new Supplier(" Computer Warehouse", "555-9256"));
plist2.Add(new Supplier(" NetworkCity", "555-2564"));
try {
// .
Supplier sp = plist2.FindByNumber("555-2564");
Console.WriteLine(sp.Name + ": " + sp.Number);
} catch(NotFoundException) {
Console.WriteLine("He ");

}
// ,

597

598

I. #

// EmailFriend IPhoneNumber.
// PhoneList<EmailFriend> plist3 =
// new PhoneList<EmailFriend>(); // !

}
}
,
PhoneList, , IPhoneList.
, Friend Supplier,
, .
EmailFriend,
. ,
M a i n (). ,

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

. new (),
.
,
n e w ().
// new() .
using System;
class MyClass {
public MyClass() {

//

. . .

}
//. . .
}
class Test<T> where T : new()
T obj;
public Test() {

// new().
obj = new (); //

}
//

. . .

}
class ConsConstraintDemo {

18.

599

static void Main() {


Test<MyClass> x = new Test<MyClass>();

}
}
Test.
class Test<T> where T : new()

new ()
.
Test.
public Test () {
// new().
obj = new (); //

}
,
o b j. ,
new () . ,
n ew (),
. .
Main () Test, .
Test<MyClass> = new Test<MyClass>();

,
MyClass .
, Test.
, MyClass

.
.
, ,
.
new ( ) ,
. -,
, . -, new ()
, ,
. ,
. -, new ()
, .


, , ,
, .
,
.
.
where : class

600

!. #

where class ,
. ,
, int bool,
.
.
where : struct

struct ,
. (, .)
, , string,
. ,
class struct
.
,
.
// .
using System;
class MyClass {

//...
}
// ,
class Test<T> where : class {
obj;
public Test () {
// ,
//
// , ,
obj = null;

}
/ / ...
}
class ClassConstraintDemo {
static void Main() {
// , MyClass .
Test<MyClass> = new Test<MyClass>();
// ,
// int .
// Test<int> = new Test<int>();

}
}
Test,
class Test<T> where T : class {

18.

601

c l a s s , .

T est.
public Test () {
// ,
//
// , ,
obj = null;

}
obj .
. ,
. (
, ,
(n u ll).
20.) ,
, . ,

.
.
, , ,
, s t r u c t enum. (
.) .
// .
using System;
struct MyStruct {

//...
}
class MyClass {

...
)
class Test<T> where T : struct {
T obj;
public Test(T x) {
obj = x;

}
II

...

}
class ValueConstraintDemo {
static void Main() {
// .
Test<MyStruct> = new Test<MyStruct>(new MyStruct ());

602

I. C#
Test<int> = new Test<int>(10);

/ / !
// Test<MyClass> z = new Test<MyClass>(new MyClass());

}
}
Test .
class Test<T> where : struct {

Test struct,
. ,
Test<MyStruct>,n Test<int> ,
Test<MyClass> . ,

. .


,
.
.
class Gen<T/ V> where V : T {

w h e r e ,
, V, , ,
, .
Gen,
.
. .
// .
using System;
class {

//...
}
class : {

//

. . .

}
// V .
class Gen<T, V> where V : T {

//

. . .

}
class NakedConstraintDemo {
static void Main() {
// ,

18.

6 03

// .
GerKA, > = new Gen<A, > () ;
// ,
// -. . .
// Gen<B, > = new Gen<B, >();

}
}
, .
G e n M a i n () .

Gen<A, > = new Gen<A, > ();

, .
// Gen<B, > = new Gen<B, >();

, .


.
.
cla s s struct, ,
, . c l a s s s t r u c t
rte .
,
ne w (). , .
class Gen<T> where : MyClass,

//

IMylnterface, new()

. . .

,
MyClass, I M y l n t e r f a c e
.
,
where,
.
// where,
using System;
// Gen ,
// where,
class Gen<T, V> where T : class
where V : struct {
T obi;
V ob2;
public Gen(T t, V v)
obi = t;

604

I. #
ob2 = v;

}
}
class MultipleConstraintDemo {
static void Main() {
// ,
// string , a int .
Gen<string, int> obj = new Gen<string, int>(nTecTM, 11);
/ / ,
// bool .
// Gencbool, int> obj = new Gencbool, int>(true, 11);

}
}
Gen ,
where.
.
class GenCT, V> where T : class
where V : struct {

, where .
.

,

,
.
, , ,
.
n u ll, 0 f a ls e ,
bool, s t r u c t ,
. :
: n u ll, 0 ?
, T est:
class Test<T> {
obj;

//

. . .

obj ,
obj = null; //

obj = 0 ;

//
// ,

?
d e f a u lt, .

18.

605

default ()

d e f a u l t ,
.
,
d e fa u lt.
// default.
using System;
class MyClass {

/ I ...
}
// , ,
class Test<T> {
public obj;
public Test() {
// .
// obj = null; / /
// .
// obj = 0; //
/ / ,
// ,
obj = default(); // !

}
II . ..
}
class DefaultDemo {
static void Main()

// Test, .
Test<MyClass> = new Test<MyClass> () ;
1
if(x.obj == null)
Console.WriteLine(" x.obj <null>.");
// Test, .
Test<int> = new Test<int>();
i f (.obj == 0)
Console.WriteLine(" .obj 0.");

}
}
.
x.obj <null>.
.obj 0.

606

I. C#


C# . ,
. ,
XY X, Y.
// ,
using System;
// ,
struct XY<T> {
;
;
public X Y ( , )
= ;
= ;

}
public X {
get { return ; }
set { = value; }

}
public T Y {
get { return y; }
set { = value; }

}
}
class StructTest {
static void Main() {
XY<int> xy = new XY<int>(10, 20);
XY<double> xy2 = new XY<double>(88.0, 99.0);
Console.WriteLine(xy.X + ", " + xy.Y);
Console.WriteLine(xy2.X + ", " + xy2.Y);

}
}
.
1 0 , 20
88, 99

,
. , XY
.
struct XY<T> where : struct {

//

. . .

18.

607


, ,
, , ,

.
,
.
.
A r r a y U tils ,
Copy I n s e r t (). ,
. C o p y ln s e rtO
.
// ,
using System;
// . ,
class ArrayUtils {
// , .
// .
public static bool CopyInsert<T> ( e, uint idx,
T[] src, T[] target) {
// , ,
if(target.Length < src.Length+1)
return false;
// src ,
// - idx.
for(int i=0, j=0; i < src.Length; i++, j++) {
if(i == idx) {
target[j] = e;
j++;

}
target[j] = src[i];

}
return true;

}
}
class GenMethDemo {
static void Main() {
int[] nums = { 1, 2, 3 };
int[] nums2 = new int [4];
// nums.
Console.Write(" nums: ");
foreach(int x in nums)

608

I. C#
Console.Write( + " ") ;
Console.WriteLine() ;
// int.
ArrayUtils.Copylnsert(99, 2, nums, nums2);
// nums2.
Console.Write(" nums2: ");
foreach(int x in nums2)
Console.Write(x + " ") ;
Console.WriteLine();
/ / , copylnsert.
string[] strs = {"", "", "."};
string[] strs2 = new string[4];
// strs.
Console.Write(" strs: ");
foreach(string s in strs)
Console.Write(s + " ");
Console.WriteLine();
// .
ArrayUtils.Copylnsert(" #", 1, strs, strs2);
// strs2.
Console.Write(" strs2: ");
foreach(string s in strs2)
Console.Write(s + " ");
Console.WriteLine();

// ,
// double,
// int.
// ArrayUtils.Copylnsert(0.01, 2, nums, nums2);

}
}
.

nums: 1 2 3
nums2: 1 2 99.3
strs: .
strs2: C# .

C o p y I n s e r t().
.
public static bool CopyInsert<T>( e, uint idx,
T[] src, T[] target)

18.

609

, .
, C o p y lnsert () ,
. , , ,
, .
.
, C o p y l n s e r t ()
Main () . ,
,
. . ,

ArrayUtils.Copylnsert (99, 2, nums, nums2);

T int, 99
nums num&2 int.
, string.

.
// ArrayUtils.Copylnsert(0.01, 2, nums, nums2);


, . ,
Copylnsert () double,
nums n u m s 2
int. ,
, ,
.
.
Copylnsert () .
.
_ _<__> (_)

{ //

...

_ _
. ,
.



,
.
. , Copylnsert ()
string.
ArrayUtils.CopyInsert<string>(" #", 1, strs, strs2);

,

.

61 0

I. C#


,
. C opylnsert ()
.
public static bool CopyInsert<T>( e, uint idx,
T [] src, T [] target) where T : class {


, C o p y ln se rt ( )
, i n t , .
// , !
ArrayUtils.Copylnsert(99, 2, nums, nums2); // !


, .
.
delegate _ _<__> (_) ;

.
.
, ,
.

SomeOp .
.
'
// ,
using System;
// ,
delegate Some0p<T>(T v) ;
class GenDelegateDemo {
// ,
static int Sum(int v) {
int result = 0;
for(int i=v; i>0; i )
result += i;
return result;

}
// , ,
static string Reflect(string str) {
string result =
foreach(char ch in str)

18.

611

result = ch + result;
return result;

}
static void Main() {
// int.
SomeOp<int> intDel = Sum;
Console.WriteLine(intDel(3));
// string.
SomeOp<string> strDel = Reflect;
Console.WriteLine(strDel(""));

}
}
.
6

.
SomeOp.
delegate SomeOp<T>(T v) ;

, , ,
SomeOp.
GenDelegateDemo Sum () Reflect (),
.
static int Sum(int v)

static string Reflect(string str)

Sum () ,
, Reflect () ,
, .
Main () intDel ,
Sum ().
SomeOp<int> intDel = Sum;

Sum () int int,


SomeOp.
strDel ,
Reflect ().
SomeOp<string> strDel = Reflect;

Reflect () string
string, SomeOp.

. ,
.
SomeOp<int> intDel = Reflect; // !

6 12

I. C#

R eflect () s t r i n g
s t r i n g , ,
SomeOp.


, C#
. .
12, I S e r i e s .
(, I S e r i e s ,
.) , ,
.
// ,
using System;
public interface ISeries<T> {
T GetNext();//
void Reset(); //
void SetStart(T v) ; //

}
// ISeries,
class ByTwos<T> : ISeries<T> {
T start;
T val;
// ,
// ,
public delegate IncByTwo( v ) ;
// ,
// ByTwos.
IncByTwo incr;
public ByTwos(IncByTwo incrMeth) {
start = default(T);
val = default(T);
incr = incrMeth;

}
public T GetNextO
val = incr(val);
return val;

}
public void Reset() {
val = start;

}
public void SetStart(T v)
start = v;
val = start;

18.
}
}
class ThreeD {
public int x / , z;
public ThreeD(int a, int b, int c) {
x = a;
= b;
z = c;

}
}
class GenlntfDemo {
//
// int.
static int IntPlusTwo(int v) {
return v + 2;

}
//
// double,
static double DoublePlusTwo(double v) {
return v + 2.0;

}
//
// ThreeD.
static ThreeD ThreeDPlusTwo(ThreeD v) {
if(v==null) return new ThreeD(0, 0, 0) ;
else return new ThreeD(v.x + 2, v.y + 2, v.z + 2);

}
static void Main()

//
// int.
ByTwos<int> intBT = new ByTwos<int>(IntPlusTwo);
for(int i=0; i < 5; i++)
Console.Write(intBT.GetNext() + " ") ;
Console.WriteLine();
//
// double.
ByTwos<double> dblBT =
new ByTwos<double>(DoublePlusTwo);
dblBT.SetStart(11.4);
for(int i=0; i < 5; i++)
Console.Write(dblBT.GetNext() + " ");
Console.WriteLine();

613

61 4

!. C#
//
// ThreeD.
ByTwos<ThreeD> ThrDBT = new ByTwos<ThreeD>(ThreeDPlusTwo);
ThreeD coord;
for (int i=0; i < 5; i++) {
coord = ThrDBT.GetNext();
Console.Write(coord.x +
+
coord. +
+
coord.z + " ");

}
Console.WriteLine();

}
}
.
2 4 6 8 10
13.4 15.4 17.4 19.4 21.4
0, 0, 0 2,2,2 4, 4, 4 6, 6, 6 8, 8,8

.
ISeries .
public interface ISeries<T> {

,
, .
ByTwos,
I series.
class ByTwos<T> : ISeries<T> {

ByTwos,
ISeries. . ,
, . ,
, .
class ByTwos : ISeries<T> { // !

, ISeries,
ByTwos. .
, (val)
(start), .
IncByTwo. ,
, .
ByTwos , .
B yTwos ,
. in c r.
,
incr.

18.

6 15

ThreeD.
(X,Z,Y).
ByTwos.
Genlntf Demo
int, d o u b l e ThreeD.
ByTwos .
ThreeDPlusTwo ().
//
// ThreeD.
static ThreeD ThreeDPlusTwo(ThreeD v) {
if(v==null) return new ThreeD(0, 0, 0);
else return new ThreeD(v.x + 2, v.y + 2, v.z + 2);

}
, v
(null). ,
ThreeD . ,
v default ()
ByTwos.
.
SetStart(),TO v
. ,
.

, .
ISeries
.
public interface ISeries<T> where T : class {

ISeries,
,
.
class ByTwos<T> : ISeries<T> where T : class {

I S e r i e s
.
, ByTwos<ThreeD>,
ByTwos<int> ByTwos<double>.


.
, Is In (),
true, .
.
// !
public static bool IsIn<T>(T what, T[] obs)
foreach(T v in obs)

616

I. C#
if(v == what) // !
return true;

return false;

}
, .
, , .
?
, ?
. , .

IComparable IComparable<T> / IEquatable<T>.
I C o m p a r a b l e
( ) , I E q u a t a b l e < T > E quals ().
I Compa r a b l e ,
.
IE qua table .
System C#
, int, string double.
. , IEquatable<T>.
IEquatable<T> .
public interface IEquatable<T>

.
Equals (), .
bool Equals( oth er)

,
o t h e r . true,
, false.
IEquatable<T>
G e t H ash C o d e () Equals (Object), Object,
E q u a l s ().
,
Is In ().
// IEquatable<T>.
public static bool IsIn<T>(T what, T[] obs) where T : IEquatable<T> {
foreach(T v in obs)
if(v.Equals(what)) // Equals().
return true;
return false;

}

.
where : IEquatable<T>

, ,
IEquatable, Is In ().

18.

617

Equals (),
.

IComparable. :
.
, .
IComparable<T> .
public interface IComparable<T>

.
CompareTo (), .
int CompareTo( oth er)

,
o t h e r . ,
, o t h e r ; ,
, o t h e r .
CompareTo (),
,
IComparable<T>. CompareTo (),
.
IComparable<T>.
InRange (),
true, .
// IComparable<T>.
// , .
// true, what
// , obs.
public static bool InRange<T>(T what, T[] obs) where T : IComparable<T> {
if(what.CompareTo(obs[0]) < 0 ||
what.CompareTo(obs[obs.Length-1]) > 0) return false;
return true;

}

Is In () InRange () .
//
// IComparable<T> IEquatable<T>.
using System;
// MyClass
// IComparable<T> IEquatable<T>.
class MyClass : IComparable<MyClass>, IEquatable<MyClass> {
public int Val;
public MyClass(int x)

{ Val = x; }

// IComparable<T>.
public int CompareTo(MyClass other) {

618

I. C#
return Val - other.Val; // Now, no cast is needed.

>

// IEquatable<T>.
public bool Equals(MyClass other) {
return Val == other.Val;

}
// Equals(Object).
public override bool Equals(Object obj) {
if(obj is MyClass)
return Equals((MyClass) obj);
return false;

}
// GetHashCode().
public override int GetHashCode() {
return V a l .GetHashCode() ;

}
class CompareDemo {
// IEquatable<T>.
public static bool IsIn<T>(T what, T[] obs) where T : IEquatable<T> {
foreach(T v in obs)
if(v.Equals(what)) // Equals()
return true;
return false;

}
// IComparable<T>.
// , .
// true, what
// , obs.
public static bool InRange<T>(T what, T[] obs) where T : IComparable<T> {
if(what.CompareTo(obs[0]) < 0 ||
what.CompareTo(ob[obs.Length-1]) > 0) return false;
return true;

}
// ,
static void Main() {
// Isln() int.
int[] nums = { 1, 2, 3, 4, 5 };
if(IsIn(2, nums))
Console.WriteLine(" 2.");
if(Isln(99, nums))
Console.WriteLine("He .");

18.

619

// Isln() MyClass.
MyClass[] mcs = { new MyClass(1), new MyClass(2),
new MyClass(3), new MyClass(4) };
if(lsln(new MyClass(3), mcs))
Console.WriteLine(" MyClass(3).");
if(Isln(new MyClass(99), mcs))
Console.WriteLine("He .");
// InRangeO int.
if(InRange(2, nums))
Console.WriteLine(" 2 nums.");
if(InRange(1, nums))
Console.WriteLine(" 1 nums.");
if(InRange(5, nums))
Console.WriteLine(" 5 nums.");
i f (!InRange(0, nums))
Console.WriteLine(" HE nums.");
i f (!InRange(6, nums))
Console.WriteLine(" 6 HE nums.");
// InRangeO MyClass..
if(InRange(new MyClass(2), mcs))
Console.WriteLine(" MyClass(2) nums.");
if(InRange(new MyClass(1), mcs))
Console.WriteLine(" MyClass(1) " +
" nums.");
if(InRange(new MyClass(4), mcs))
Console.WriteLine(" MyClass(4) " +
" nums.");
i f (!InRange(new MyClass(0), mcs))
Console.WriteLine(" MyClass(0) HE " +
" nums.");
i f (!InRange(new MyClass(5), mcs))
Console.WriteLine(" MyClass(5) HE " +
" nums.");

}
}
.
2.
MyClass (3) .
2 nums.
1 nums.
5 nums.
0 nums
6 nums
MyClass(2) nums.
MyClass(1) nums.
MyClass(4) nums.
MyClass(0) nums.
MyClass(5) nums.

620

I. C#

,
, , == ! =,
.
IComparable IComparable<T> IEquatable<T>.



. ,
.
, ,
,
.


,
.
// ,
using System;
// ,
class Gen<T> {
ob;
public G e n ( ) {
ob = ;

}
// ob.
public GetOb () {
return ob;

}
// , Gen.
class Gen2<T> : Gen<T> {
public Gen2(T o) : base(o) {
II . . .

}
class GenHierDemo {
static void Main() {
Gen2<string> g2 = new Gen2<string>("") ;
Console.WriteLine(g2.GetOb());

18.

621

G e n 2 Gen.
G e n 2 .
class Gen2<T> : Gen<T> {

G e n 2
Gen. , , Gen2,
Gen. , :
Gen2<string> g2 = new Gen2<string>("");

string Gen. ob
Gen2, Gen, string.
, G e n 2
, Gen. ,
,
,
.
,
, .
, G e n 2
.
// ,
using System;
// ,
class Gen<T> {
ob; //
// .
public Gen(T ) {
ob = ;

}
// ob.
public GetOb() {
return ob;

}
}
// , Gen.
// V.
class Gen2<T, V> : Gen<T> {
V ob2;
public Gen2(T , V o2)
ob2 = o2;

}
public V Get0bj2()
return ob2;

' }

: base (o) {

622

I. C#

}
1 1 Gen2.
class GenHierDemo2 {
static void Main() {

// Gen2
// string int.
Gen2<string, in.t> x =
new Gen2<string, int>(" : ", 99);
Console.Write(x.GetOb());
Console.WriteLine(x.GetObj2());

}
}
G e n 2
.
class Gen2<T, V> : Gen<T> {

, Gen; V ,
Gen2.
2 , G e t O b j 2 (). M a i n ()
G e n 2 s t r i n g V int.
.
: 99


.
. .
//
// .
using System;
// ,
class NonGen {
int num;
public NonGen(int i) {
num = i;

}
public int GetNum()
return num;

}
}
// ,
class Gen<T> : NonGen {
T ob;

18.
public Gen(T , int i)
ob = o;

: base

623

(i) {

}
// ob.
public T GetObO {
return ob;

}
}
// Gen.
class HierDemo3 {
static void Main() {
// Gen string.
Gen<String> w = new Gen<String>("", 47);
Console.Write(w.GetOb() + " ");
Console.WriteLine(w .GetNum());

}
}
.
47

, Gen
NonGen .
class Gen<T> : NonGen {

NonGen ,
. , ,
Gen, N o n G e n
. , Gen N o n G e n
, .. - .



, .
, GetOb ().
// ,
using System;
// ,
class 'Gen<T> {
protected ob;
public Gen(T ) {
ob = ;

}
// ob. .

624

I. #

public virtual T GetObO {


Console.Write(" GetObO
return ob;

Gen" + " : ");

}
}
// , Gen.
// GetObO .
class Gen2<T> : Gen<T> {
public Gen2(T o)

: base(o)

{ }

// GetObO .
public override T GetObO {
Console.Write(" GetObO Gen2" + " : ") ;
return ob;

}
}
// ,
class OverrideDemo {
static void Main() {
// Gen int.
Gen<int> iOb = new Gen<int> (88);
// GetObO
Console.WriteLine(iOb.GetOb());

Gen.

/ / Gen2
// iOb Gen<int>.
iOb = new Gen2<int> (99);
// GetObO
Console.WriteLine(iOb.GetOb());

Gen2.

}
}
.
GetObO
GetObO

Gen : 88
Gen2 : 99

,
GetOb () G e n 2,
Gen.
.
iOb = new Gen2<int>(99);

, iOb
Gen<int>. , Gen<int>
, Gen<int>, Gen2<int>. ,
iOb , , Gen2<int>,
.

18.

625


, ,
.
. , ,
, ,
. ,
.
,
,
. ,
, ,
.
.
// ,
// .

//
// ,
using System;
// , Set(),
// ,
class Gen<T, V> {
obi;
V ob2 ;

//

. . .

//
// ,
public void Set(T ) {
obi = ;

}
public void Set(V ) {
ob2 = o;

}
}
class AmbiguityDemo {
static void Main() {
Gen<int, double> ok = new Gencint, double>();
Gen<int, int> notOK = new Gencint, int>();
ok.Set(10); // ,
notOK.Set(10); // , !

}
}
.
, Gen : V. Gen
Set () V, .

626

I. #

public void Set (T )


obi = ;

}
public void Set(V o)
ob2 = o;

}
, V
. .
Gen
V. , ,
Gen , .
Gencint, int> notOK = new Gencint, int>();

, V, int.
Set () , , , .
, Set () notOK
Main ()
.
, ,
. , , ,
,
.
. ,
.



15
. #, . C# 4.0

, .
, ,
,
, .NET Framework.
, , ,
. ,

, .
.


,
, ,
.

18.

627

.
,
.
out, .
,
. IMyCoVarGenlF,
.
/ / ,
public interface IMyCoVarGenlFCout > {
GetObjectO;

}
, .
out. out
, . ,
Get Obj ect ()
, .
,
IMyCoVarGenlF
. MyClass.
// IMyCoVarGenlF.
class MyClass<T> : IMyCoVarGenIF<T> {
T obj;
public MyClass(T v) { obj = v; }
public T GetObjectO

{ return obj;

}
, out
, MyClass.
, , out
.
.
// ,
class Alpha {
string name;
public Alpha(string n) { name = n; }
public string GetNameO

//

{ return name;

. . .

}
class Beta : Alpha {
public Beta(string n)

//

: base (n) { }

. . .

}
, B e t a Alpha.

628

I. C#

,
.
// IMyCoVarGenlF MyClass<Alpha>.
// , .
IMyCoVarGenIF<Alpha> AlphaRef =
new MyClass<Alpha>(new Alpha("Alpha #1"));
Console.WriteLine(" , AlphaRef: " +
AlphaRef.GetObj e c t () .GetName());
/ / MyClass<Beta> AlphaRef.
// *** . ***
AlphaRef = new MyClass<Beta>(new Beta("Beta #1"));
Console.WriteLine(" , " +
" AlphaRef: " + AlphaRef.GetObject().GetName());

, -AlphaRef I M y C o V a r GenIF<Alpha>
MyClass<Alpha>.
, MyClass IMyCoVarGenlF,
, Alpha.
GetName () ,
GetOb j ect (). , Alpha
, G e t N a m e (), .
AlphaRef MyClass<Beta>,
, Beta Alpha,
IMyCoVarGenlF.
, .


.
// ,
using System;
// .
public interface IMyCoVarGenIF<out > {
GetObjectO;

}
// IMyCoVarGenlF.
class MyClass<T> : IMyCoVarGenIF<T> {
T obj;
public MyClass(T v)
public T GetObjectO

{ obj = v; }
{ return obj;

}
// ,
class Alpha {
string name;
public Alpha(string n)

{ name = n; }

18.
public string GetNameO

//

{ return name;

629

. . .

}
class Beta : Alpha {
public Beta(string n)

//

: base(n)

{ }

. . .

}
class VarianceDemo {
static void Main() {
// IMyCoVarGenlF
MyClass<Alpha>.
// , .
IMyCoVarGenIF<Alpha> AlphaRef = new MyClass<Alpha>(new Alpha("Alpha #1"));
Console.WriteLine(" , " +
"AlphaRef: " + AlphaRef.GetObj e c t ().GetName());
/ / MyClass<Beta>
// AlphaRef.
// *** . ***
AlphaRef = new MyClass<Beta>(new Beta("Beta #1"));
Console.WriteLine(" , " +
"AlphaRef: " + AlphaRef.GetObj e c t () .GetName());

}
}
.
, AlphaRef: Alpha #1
, AlphaRef: Beta #1

, A l p h a R e f
MyClass<Beta> ,
IMyCoVarGenlF. ,
out
IMyCoVarGenlF .
,
.
.
, ,
.
public interface IMyCoVarGenIF2<out > : IMyCoVarGenIF<T> {

//

. . .

}
, out
.
, . :
IMyCoVarGenIF2.
,

630

I. C#

IMyCoVarGetlF. , IMyCoVarGenIF2
.
.
,
. , out ,
.
.
. , .
public interface IMyCoVarGenIF2<out > {
void M < V > () where V:T; // , T
//


- .
, ,
, .

.
, . in,
.
,
.
I MyContraVarGenlF .
, Show ().
// , .
public interface IMyContraVarGenIF<in > {
void Show(T obj);

}
,
in, .
, obj
Show ().
IMyContraVarGenlF MyClass,
.
// IMyContraVarGenlF.
class MyClass<T>
IMyContraVarGenIF<T> {
public void Show(T x) { Console.WriteLine(x); }

}
Show ()
, ToString ()
WriteLine ().
, .
// ,
class Alpha {

18.

631

public override string ToStringO {


return " Alpha.";

}
//

. . .

}
class Beta : Alpha {
public override string ToStringO {
return " Beta.";

}
//

. . .

}
A l pha Beta
.
, T o S t r i n g O ,
.
,
.
}
// IMyContraVarGenIF<Alpha>
/ / MyClass<Alpha>.
// , .
IMyContraVarGenIF<Alpha> AlphaRef = new MyClass<Alpha>();
// IMyContraVarGenIF<beta>
// MyClass<Beta>.
/ / , .
IMyContraVarGenIF<Beta> BetaRef = new MyClass<Beta>();
// IMyContraVarGenIF<beta>
7/ MyClass<Alpha>.
// *** . ***
IMyContraVarGenIF<Beta> BetaRef2 = new MyClass<Alpha>();
// , .
BetaRef.Show(new Beta());
// AlphaRef BetaRef.
// *** . ***
BetaRef = AlphaRef;
BetaRef.Show(new Beta ());

,
IMyContraVarGenlF, MyClass,

.
Alpha,
Beta. .
IMyContraVarGenIF<Beta>,
MyClass<Alpha>.
, .

632

I. C#

, , B e t aRef.
Show () Beta, . Beta
M yClass<Beta> Show ().
A l p h a R e f BetaRef.
.
M y C l a s s < B e t a > , A l p h a R e f
MyClass<Alpha>. Alpha Beta,
.

, in
IMyContraVarGenlF,
. .

.
// ,
using System;
// , .
public interface IMyContraVarGenIF<in > {
void Show(T obj);

}
// IMyContraVarGenlF.
class MyClass<T> : IMyContraVarGenIF<T> {
public void Show(T x) { Console.WriteLine(x); }

}
// ,
class Alpha {
public override string ToString() {
return " Alpha.";

}
//

. . .

}
class Beta : Alpha {
public override string ToString() {
return " Beta.";

}
//

. . .

}
class VarianceDemo {
static void Main() {
// IMyContraVarGenIF<Alpha>
/ / MyClass<Alpha>.
// , .
IMyContraVarGenIF<Alpha> AlphaRef = new MyClass<Alpha>();
// IMyContraVarGenIF<beta>
// MyClass<Beta>.
/ / ,

18.

6 33

// .
IMyContraVarGenIF<Beta> BetaRef = new MyClass<Beta>();
// IMyContraVarGenIF<beta>
/ / MyClass<Alpha>.
// *** . ***
IMyContraVarGenIF<Beta> BetaRef2 = new MyClass<Alpha>();
// , .
BetaRef.Show(new Beta());
// AlphaRef BetaRef.
// *** .
BetaRef = AlphaRef;

***

BetaRef.Show(new Beta ());

}
}
.
Beta.
Beta.


.

, , in,
.
public interface IMyContraVarGenIF2<in > : IMyContraVarGenIF<T> {

//
}

. . .

, in
, . ,
I M y C o n t r a V a r G e n I F 2 .
, I M y C o n t r a V a r G e n I F 2
in. , ,
IMyContraVarGen,
IMyContraVarGenIF2.
,
.
, in ,
.


15,
, , ,
. C# 4.0,
.
,
.

634

I. C#

.
// , .
delegate bool SomeOpcin >( obj);


, .
.
// , .
delegate AnotherOp<out , V > (V obj);

, ,
, . V
.

.
//
// .
using System;
// , .
delegate bool SomeOpcin >( obj);
// , .
delegate AnotherOpCout , V > (V obj);
class Alpha {
public int Val { get; set;
public Alpha(int v)

{ Val = v; }

}
class Beta : Alpha {
public Beta (int v) : base (v) { }

}
class GenDelegateVarianceDemo {
// true,
// obj.Val ,
static bool IsEven(Alpha obj) {
if((obj.Val % 2) == 0) return true;
return false;

}
static Beta Changelt(Alpha obj)
return new Beta(obj.Val +2);

}
static void Main() {
Alpha objA = new Alpha(4);
Beta objB = new Beta(9);
// .
// SomeOp<Alpha> IsEven.
SomeOp<Alpha> checklt = IsEven;

18.

635

// SomeOp<Beta>.
SomeOp<Beta> checklt2;
/ / - SomeOp<Alpha> SomeOp<Beta>.
// *** . ***
checklt2 = checklt;
// .
Console.WriteLine(checklt2(objB));
// , .
// AnotherOp.
// Beta,
/ / Alpha.
// , modifylt
// Changelt.
AnotherOp<Beta, Alpha> modifylt = Changelt;
// Alpha,
// Alpha.
AnotherOp<Alpha, Alpha> modifyIt2;
// modifylt modifyIt2.
// *** . ***
modifyIt2 = modifylt;
// .
objA = modifyIt2(objA);
Console.WriteLine(objA.Val);

}
}
.
False
6


. ,
SomeOp and An o t h e r O p
in out .
-
.


, :
?
: . , C#
:
. .

636

I. C#

MSIL,
.
, JIT-
,
.
.
, Gen<T>,
Gen< T > .
, ,
, .
,
.
,
, ,
int double. , Gen<int>
Gen, Gen<double>
Gen,
. , ,
,
( ). .

,
,
.
, , .
,
.
e x te rn .
.
static,
. ,

static.
. ,
static .


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

LINQ
, LINQ
#.
C# 3.0
,
#,

,
,
. , LINQ
#.
LINQ Language-Integrated Query,
.. .
,
. ,
.
,
,
,
. ,
, . ,

.

(SQL).
, XML,
. , 3.0
C# .
LINQ.
LINQ C# ,
LINQ-

6 3 8 , I. #
. , ,
, . , , ,
, ,
, .
SQL
C# .
#.
SQL, LINQ XML-
ADO.NET Dataset. LINQ
C# ( 25). ,
LINQ , , .
,
LINQ . LINQ ,
.
LINQ.
LINQ ,
C# , -, .
- 15,
.

LINQ C# , , . LINQ
, .
LINQ,
, .
.
LINQ, .
LINQ ,
.

LINQ
LINQ , ,
. ,
,
;
, ; ,
,
. , ,
LINQ.
, . ,
, fo re a c h . .
.
, . ,
, .
.

19. LINQ

639

,
LINQ, IEnumerable.
: . ,
, IEnumerable<T>,
. ,
IEnumerable<T>.
System. Collections. Generic. ,
IEnumerable<T>, ,
,
. IEnumerable<T> #.

LINQ. , , , LINQ
.


LINQ.

, .
// LINQ.
using System;
using System.Linq;
class SimpQuery {
static void Main()

int[] nums = { .1, -2, 3, 0, -4, 5 };


// ,
var posNums = from n in nums
where n > 0
select n;
Console.Write(" nums: ");
// ,
foreach(int i in posNums) Console.Write(i + " ");
Console.WriteLine();

}
}
.
nums: 1 3 5

, ,
nums. ,
LINQ. .

.
using System.Linq;

640

I. C#

LINQ
System.Linq.
nums int. C#
IEnumerable<T>.
C# ,
LINQ.
, nums
.
var posNums = from n in nums
where n > 0
select

posNums .
, .
v ar p o s N u m s .
, posNums
. ,
( IEnumerable<T>).
posNums .
from, .
, .
.
( nums).
. int.
from.
from _ in _

where, ,
, .
where.
where _

_ bool.
.
where. where.
where n >

,
. > 0
.
, . ,
where ,
.
s e l e c t group.
select, ,
. , ,
.
, ,
where. ,

19. LINQ

641

. ,
. ,
select , .
.
, p o s N u m s ,
. , ,
. ,
, ,

.
posNums ,
.

.
foreach(int i in posNums) Console.WriteLine(i + " ");

p o s N u m s ,
. f reach
, posNums.
, .
, .
int i ,
.
, ,
. ,
,
var.


, , ,
,
, .

, .
,
. .
, nums

, posNums.
// .
using System;
using System.Linq;
using System.Collections.Generic;
class SimpQuery {
static void Main() {
int[] nums = { 1, -2, 3, 0, -4, 5 };

642

I. C#

// ,
var posNums = from n in nums
where n > 0
select n;
Console.Write(" nums: ");
// .
foreach(int i in posNums) Console.Write(i + " ");
Console.WriteLine();
// nums.
Console.WriteLine(" 99 nums[l].");
nums[l] = 99;
Console.Write(" nums\n" +
" : ");
// .
foreach(int i in posNums) Console.Write(i + " ");
Console.WriteLine ();

}
}
.
nums: 1 3 5
99 nums[l].
nums
: 1 99 3 5

,
nums [ 1 ] -2 99,
. .
,
.
, .
' . ,
-,
,
.


, ,
. ,
. ,
, ,
.

19. LINQ

64 3

,
. ,
. ,
#. ,
IEnumerable<T>,
. ( ,
IEnumerable<T> , , ,
.)
I Enumerable, .
from.
int .
var posNums = from int n in nums
// . . .

, ,
IEnumerable<T>,
.
, ,
IEnumerable<T>, . ,
IEnumerable<T>,
, select.
int,
int. ( , int,
nums.)
IEnumerable<int>
.
IEnumerable<int> posNums = from n in nums
where n > 0
select ^-

, , select,
, IEnumerable<T>,
.
v a r ,

select. ,
, select
, .
foreach,
, .
int. :
,
var. , var
, .


,
- .

644

!. C#

Ascending
from
join
select

by
group
let
where

descending
in
on

equals
into
orderby

.
from
orderby

group
select

join
where

let

from
select group. select ,
, group ,
. ,
where ,
, .
. .

w here
, where ,
.
,
.
, , where.
, ,
1 0 .
// where.
using System;
using System.Linq;
class TwoWheres {
static void Main()

int [] nums = { 1, -2, 3, -3, 0, -8, 12, 19, 6, 9, 10 };


// 10.
var posNums = from n in nums
where n > 0
where n < 10
select n;
Console.Write(" 10: ");
// ,
foreach(int i in posNums) Console.Write (i + " ");
Console.WriteLine();

19. LINQ

645

.
10: 1 3

6 9

,
. 10.
where.
where n > 0
where n < 10

where ,
. where ,
10. ,
1 9 (), .
where
,
where. ,
.
var posNums = from n in nums
where n > 0 & & n < 1 0
select n;

, where
C# , . ,
.
. netAddrs ,
".net". ,
, . n e t
.
// where.
using System;
using System.Linq;
class WhereDemo2 {
static void Main()

string[] strs = { ".com", ".net", "hsNameA.com",


"hsNameB.net", "test", ".network",
"hsNameC.net", "hsNameD.com" };
//
// , .net.
var netAddrs = from addr in strs
where addr.Length > 4 && addr.EndsWith(".net",
StringComparison.Ordinal)
sel-ect addr;
// .
foreach(var str in netAddrs) Console.WriteLine(str);

}
}

646

I. C#

.
hsNameB.net
hsNameC.net

, where
Ends With ().
true,
, .

orderby
. ,
:
.
, ,
LINQ, orderby.
o rd e rb y
.
. orderby
:
orderby

, .
, ,
.
asce n d in g
d escen d in g . ,
ascen d in g, , .
, o rd e rb y
int .
// orderby.
using System;
using System.Linq;
class OrderbyDemo {
static void Main()

int[] nums = { 10, -19, 4, 7, 2, -5, 0 };


// ,
var posNums = from n in nums
orderby n
select n;
Console.Write(" :

");

// ,
foreach(int i in posNums) Console.Write(i + " ");
Console.WriteLine();

19. LINQ

647

.
: -19 -5 0 2 4 7 10


, d escending, .
var posNums = from n in nums
orderby n descending
select n;

, .
.

orderby.
orderby _ , _ , _ , ...

_ ,
; _ ,
; _ ,
, .. ,
.
,
. ,
: ,
.
//
// , orderby.
using System;
using System.Linq;
class Account {
public string
public string
public double
public string

FirstName { get; private set; }


LastName { get; private set; }
Balance { get; private set; }
AccountNumber { get; private set;

public Account(string fn, string In, string accnum, double b)


FirstName = fn;
LastName = In;
AccountNumber = accnum;
Balance = b;

}
}
class OrderbyDemo {
static void Main()

// .
Account[] accounts =
{ new Account("", " " , "132CK", 100.23),
new Account("", " " , "132CD", 10000.00),

648

!. C#
new
new
new
new
new
new
new
new
new
new
new

Account("", "", "436CD", 1923.85),


Account ("", "", "454", 987.132),
Account("", "", "897CD", 3223.19),
Account("", "", "434", -123.32),
Account("", "", "543", 5017.40),
Account("", "", "547CD", 34955.79),
Account("", "", "843", 345.00),
Account("", "", "445", -213.67),
Account("", "","968",5146.67),
Account("", "", "078CD", 15345.99),
Account("", "", "108", 10.98)

};
//
// .
// ,
/ / , , ,
var acclnfo = from in accounts
orderby acc.LastName, acc.FirstName, acc.Balance
select acc;
Console.WriteLine(" : ") ;
string str = "";
// ,
foreach(Account acc in acclnfo) {
if(str != acc.FirstName) {
Console.WriteLine();
str = acc.FirstName;

}
Console.WriteLine("{0}, {l}\tHoMep : {2}, {3,10:C}",
acc.LastName, acc.FirstName,
acc. AccountNumber, acc.Balance);

}
Console.WriteLine ();

}
}
.
:
,

: 108,

,
,
,

: 434,
: 454,
: 436CD,

($123.32)
$987.13
$1,923.85

: 968,

$5,146.67

: 897CD,

$3,223.19

: 445,

($213.67)

$10.98

19. LINQ
,

: 078CD, $15,345.99

,
,
,

: 843,
$345.00
: 543,
$5,017.40
: 547CD, $34,955.79

,
,

: 132,
$100.23
: 132CD, $10,000.00

649

derby
.
var acclnfo = from in accounts
orderby acc.LastName, acc.FirstName, acc.Balance
select acc;

.
,
. ,
.
.
,

: 108,

$10.98

,
,
,

: 434, ($123.32)
: 454,
$987.13
: 436CD, $1,923.85

,
, , , .
,
descending. ,
.
var acclnfo = from acc in accounts
orderby x.LastName, x.FirstName, x.Balance descending
select acc;

,
.
,

: 108,

$10.98

,
,
,

: 436CD, $1,923.85
: 454,
$987.13
: 434, ($123.32)

,
: .

s e l e c t
s e l e q t , .
.
select

650

!. #

select
.
. sele c t
.
,
,
, .
.
s e l e c t
.*
, double.
// select
// , double.
using System;
using System.Linq;
class SelectDemo {
static void Main()

double[] nums =
{ -10.0, 16.4, 12.125, 100.85, -2.2, 25.25, -3.5 };
//
// , nums.
var sqrRoots = from n in nums
where n > 0
select Math.Sqrt(n);
Console.WriteLine(" ,\n" +
" :");
// ,
foreach(double in sqrRoots)
Console.WriteLine("{0:#.##}", r);

}
}
.
,
:
4.05
3.48
10.04
5.02


select.
select Math.Sqrt(n);

.
M a t h . Sqrt (),

19. LINQ

651

. ,
, ,
, nums. ,
. , s e l e c t
,
, .
,
s e l e c t . E m ailA ddress,
. ,
. ,
Em ailAddress. , ,
, .
// .
using System;
using System.Linq;
class EmailAddress {
public string Name { get; set; }
public string Address { get; set;

public EmailAddress(string n, string a) {


Name = n;
Address = a;

}
}
class SelectDemo2 {
static void Main()

EmailAddress[] addrs = {
new EmailAddress("", "Herb@HerbSchildt.com"),
new EmailAddress ( " T o m " , "Tom@HerbSchildt.com"),
new EmailAddress("Capa", "Sara@HerbSchildt.com")

};
//
// .
var eAddrs = from entry in addrs
select entry.Address;
Console.WriteLine(" :");
// ,
foreach(string s in eAddrs)
Console.WriteLine(" " + s);

}
}
.
:
Herb@HerbSchildt.com

652

I. C#

Tom@HerbSchildt.com
Sara@HerbSchildt.com

select,
select entry.Address;


(Address). ,
, Email Address.
s foreach string.
, , ,
, select.
select
, ,
. .
Contactlnfo, ,
. ,
Email Address, . Main ()
Contactlnfo, ,
,
EmailAddress. ,
, select, EmailAddress,
Contactlnfo, .
//
// EmailAddresses Contactlnfo.
using System;
using System.Linq;
class Contactlnfo {
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public Contactlnfo(string n, string a, string p)
Name = n;
Email = a;
Phone = p;

}
}
class EmailAddress {
public string Name { get; set; }
public string Address { get; set; }
public EmailAddress(string n, string a) {
Name = n;
Address = a;

}
class SelectDemo3 {
static void Main()

19. LINQ

653

Contactlnfo[] contacts = {
new Contactlnfo("", "Herb@HerbSchildt.com", "555-1010"),
new Contactlnfo("", "Tom@HerbSchildt.com", "555-1101"),
new Contactlnfo("Capa", "Sara@HerbSchildt.com", "555-0110")

};
// EmailAddress.
var emailList = from entry in contacts
select new EmailAddress(entry.Name, entry.Email);
Console.WriteLine(" :");
// ,
foreach(EmailAddress in emailList)
Console.WriteLine(" {0}: {1}", e.Name, e.Address );

}
}
.
:
: Herb@HerbSchildt.com
: Tom@HerbSchildt.com
: Sara@HerbSchildt.com

select.
select new EmailAddress(entry.Name, entry.Email);

EmailAddress,
, Contactlnfo,
contacts. , E mailAddress
select .

fro m
-f ,
. from ,
.
, from
.
,
.
// from
// , X, Y Z.
using System;
using System.Linq;
// ,
class ChrPair {
public char First;

654

I. C#

public char Second;


public ChrPair(char c, char c2)
First = c;
Second = c2;

}
}
class MultipleFroms {
static void Main() {
char[] chrs = { 'A', 1 ', 'C' };
char[] chrs2 = { 'X', 1Y ', 'Z' };
// from
/ / chrs, from
// chrs2.
var pairs = from chi in chrs
from ch2 in chrs2
select new ChrPair(chl, ch2);
Console.WriteLine(" ABC XYZ: ");
foreach(var p in pairs)
Console.WriteLine("{0} {1}", p.First, p.Second);

}
}
.
ABC XY Z :
X
A Y
A Z
X
Y
Z
X
Y
Z

ChrPair,B
. , chrs c h r s 2 , , ,

.
var pairs = from chi in chrs
from ch2 in chrs2
select new ChrPair(chl, ch2);

fr o m
, chrs chrs2. chrs ,
chi. chrs2.
f r o m
chrs2 ch2 select.
select ChrPair,

19. LINQ

655

, chi ch2
from.
ChrPair,
.
' from
, .
" let
" .

g ro u p

group, .

,
, .
group ,
, . group
, . ( ,
, select.) group.
group _ by

, ,
.
group ,
IGrouping<TKey, TElement>, .. ,
System. Linq.
. ,
, IEnumerable<IGrouping<TKey, TElement>>. IGrouping
Key, ,
.
, group.
, -,
,
, . org . .
// group.
using System;
using System.Linq;
class GroupDemo {
static void Main()

string[] websites = { "hsNameA.com", "hsNameB.net", "hsNameC.net"


"hsNameD.com", "hsNameE.org", "hsNameF.org"
"hsNameG.tv", "hsNameH.net", "hsNamel.tv"

};
// -,
// .

656

I. C#
var webAddrs = from addr in websites
where addr.LastlndexOf('.') != -1
group addr by addr.Substring(addr.LastlndexOf('.'));
// .
foreach(var sites in webAddrs) {
Console.WriteLine("-, " +
" " + sites.Key);
foreach(var site in sites)
Console.WriteLine (" " + site);
Console.WriteLine();

}
}
}
.
-, .
hsNameA.
hsNameD.
-, .net
hsNameB.net
hsNameC.net
hsNameH.net

-, .org
hsNameE.org
hsNameF.org
-, .tv
hsNameG.tv
hsNamel.tv

, , ,
-.
, group .
var webAddrs = from addr in websites
where addr.LastlndexOf('.') != -1
group addr by addr.Substring(addr.LastlndexOf('.'));

L a s t l n d e x O f ()
Substring ( ), string. (
7, . Subst r i n g (),
, , ,
, .)
- LastlndexOf ().
S u b s t r i n g () ,
. ,
wh e r e , .
L a stlndexOf () -1 ,
.

19. LINQ

657

, ,
webAddrs, ,
foreach.
,
. foreach
I Grouping, .
string.
sites I Grouping<string, string>,
site string.
,
, .
foreach(IGrouping<string, string> sites in webAddrs)
Console.WriteLine("-, " +
" " + sites.Key);
foreach(string site in sites)
Console.WriteLine(" " + site);
Console.WriteLine ();

i n t o
select group
,
.
into select group.
into:
into _

,
,
_ . into
select group, ,
. ,
.

into,
join, ,
.
, into
group.
, -
.
ws ,
.

658

I. #

// into group.
using System;
using System.Linq;
class IntoDemo {
static void Main()

string[] websites = { "hsNameA.com", "hsNameB.net", "hsNameC.net",


"hsNameD.com", "hsNameE.org", "hsNameF.org",
"hsNameG.tv", "hsNameH.net", "hsNamel.tv"

};
// -,
/ / ,
// , .
// ws ,
// ,
var webAddrs = from addr in websites
where addr.LastlndexOf(1.1) != -1
group addr by addr.Substring(addr.LastlndexOf('.'))
into ws
where ws.Count() > 2
select ws;
// .
Console.WriteLine(" " +
" .\");
foreach(var sites in webAddrs) {
Console.WriteLine(" : " + sites.Key);
foreach(var site in sites)
Console.WriteLine (" " + site);
Console.WriteLine();

}
}
}
:
.
: .net
hsNameB.net
hsNameC.net
hsNameH.net

,
.n e t , ,
.

.
group addr by addr.Substring(addr.LastlndexOf('.'))
into ws
where ws.Count() > 2
select ws;

19. LINQ

659

g r o u p
where.
ws. ,
group. where
, ,
. C ount (),
I Enumerable.
. (
.)
select.

l e t


. , ,
, ,
where. ,
let.
let:
let =

, , .
.

let .
,
char. ,
ToCharArray () , .
chrArray,
from .
, ,
.
// let from.
using System;
using System.Linq;
class LetDemo {
static void Main()

string[] strs = { "alpha", "beta", "gamma" };


// ,
// .
// from,
var chrs = from str in strs
let chrArray = str.ToCharArray()

660

I. C#
from ch in chrArray
orderby ch
select ch;
Console.WriteLine(" , :");

// ,
foreach(char in chrs) Console.Write( + " ");
Console.WriteLine();

}
}
.
, :
a a a a a b e g h l m m p t

, let
c h r A r r a y , str.
T o C h a r A r r a y ().
let chrArray = str.ToCharArray()

let c h r A r r a y
, . C#
IEnumerable<T>, chrArray
, from.
, from
,
.
let
.
IntoDemo .
var webAddrs = from addr in websites
let idx = addr.LastlndexOf('.')
where idx != -1
group addr by addr.Substring(idx)
into ws
where ws.Count() > 2
select ws;


idx. Substring ().
.


j o i n
,
, . ,

19. LINQ

661

- ,
, ,
.
,
, .
- "" ( ).
LINQ, jo in .
join ( from).
from __ in __
join __ in __
on __. equals __ .

jo in , ,
, .
_ _ _ _
, .
on . _ _ .
_ _ . , "
" . , jo in ,
, .
, j o i n ,
, . , j in
, ,
. -.
, Item,
.
InStockStatus,
, .
, Temp : (string)
(bool). .
join ,
.
// join.
using System;
using System.Linq;
// , ,
class Item {
public string Name { get; set; }
public int ItemNumber { get; set; }
public Item(string n, int inum)
Name = n;
ItemNumber = inum;

}
}
// , ,
class InStockStatus {

662

I. C#

public int ItemNumber { get; set; }


public bool InStock { get; set; }
public InStockStatus (int n, bool b)
ItemNumber = n;
InStock = b;

}
}
// ,
// ,
class Temp {
public string Name { get; set; }
public bool InStock { get; set; }
public Temp(string n, bool b)
Name = n;
InStock = b;

}
}
class JoinDemo {
static void Main()

Item[] items = {
new Item("", 1424),
new Item("", 7892),
new Item("", 8534),
new Item("", 6411)

};
InStockStatus[] statusList = {
new InStockStatus(1424,
new InStockStatus(7892,
new InStockStatus(8534,
new InStockStatus(6411,

true),
false),
true),
true)

};
// , Item
/ / InStockStatus
// .
// Temp,
var inStockList = from item in items
join entry in statusList
on item.ItemNumber equals entry.ItemNumber
select new Temp(item.Name, entry.InStock);
9

Console.WriteLine("\^\");
// .
foreach(Temp t in inStockList)
Console.WriteLine("{0}\t{1}", t.Name, t.InStock);

19. LINQ

663

True
False
True
True

join,
.
, , from.
var inStockList = from item in items

item
items, Item. Item
,
.
join.
join entry in statusList
on item.ItemNumber equals entry.ItemNumber

entry
statusList, InStockStatus,
.
, items sta t u s L i s t :
. on/equals join
,
, .
, select Temp,
.
select new Temp(item.Name, entry.InStock);

, , ,
Temp.
join .

. , into join,
, ,
. (
.) , ,
join, ,
.
. , ,
.


C# ,
LINQ. ,

664

I. C#

, .
, s e l e c t .
, ,
(, , jo in ),
.

.
,
.
:
new { _ = _, _ = _,

... }

, ,
,
.
new { Count = 10, Max = 100, Min = 0 }


: Count, Min, 10, 100 0 .
. ,

. 8 ,
.
,
. (, , .
, , .)
, ,
.
.
, ,
.
var myOb = new { Count = 10, Max = 100, Min = 0 }

, .
Console.WriteLine(" " + myOb.Count);
if(i <= myOb.Max && i >= myOb.Min)

// ...

,
, .
.
.
, ,
. ,
C# .
,
,
j o i n . , Temp
, j o in .

19. LINQ

665

- ,
.
.
//
// , join-.
using System;
using System.Linq;
// , ,
class Item {
public string Name { get; set; }
public int ItemNumber { get; set; }
public Item(string nv int inum)
Name = n;
ItemNumber = inum;

}
}
// , ,
class InStockStatus {
public int ItemNumber { get; set; }
public bool InStock { get; set; }
public InStockStatus(int n, bool b)
ItemNumber = n;
InStock = b;

}
}
class AnonTypeDemo {
static void Main() {
Item[] items = {
new Item("", 1424),
new Item("", 7892),
new Item("", 8534),
new Item("nnna", 6411)

};
InStockStatus[] statusList = {
new InStockStatus(1424,
new InStockStatus(7892,
new InStockStatus(8534,
new InStockStatus (6411,

true),
false),
true),
true)

};
// , Item
// InStockStatus
// . .
var inStockList = from item in items
join entry in statusList
on item.ItemNumber equals entry.ItemNumber

666

I. #
select new { Name = item.Name,
InStock = entry.InStock };
Console .WriteLine ("\\") ;
// .
foreach(var t in inStockList)
Console.WriteLine("{0}\t{1}", t.Name, t.InStock);

}
}
select.
select new { Name = item.Name,
InStock = entry.InStock };


: Name InStock.
.
Temp .
f reach, .
var.
, , inStockList,
. , C#
,
.
,
. ,
,
. .
.
select .
select new { item.Name, entry.InStock };

, ,
"" Name InStock,
. ,
item.Name entry. InStock .


, into
join , ,

.
,
. , ,
.

, (,
) :

19. LINQ

667

, , .
Transport, .
Main () .
,
: , , ,
Transport, .
,
.
// .
using System;
using System.Linq;

*
// ,
// , :
// , , ,
class Transport {
public string Name { get; set; }
public string How { get; set; }
public Transport(string n, string h) {
Name = n;
How = h;

}
}
class GroupJoinDemo {
static void Main() {
// ,
string[] travelTypes = {
"",
"",
"",
"",

};
// .
Transport[] transports = {
new Transport("", ""),
new Transport ("", ""),
new Transport("", ""),
new Transport("", ""),
new Transport("", ""),
new Transport("", ""),
new Transport("", ""),
new Transport("", ""),
new Transport("", "")

};
// ,
//

668

I. C#
// ,
var byHow = from how in travelTypes
join trans in transports
on how equals trans.How
into 1st
select new { How = how, Tlist = 1st };
// ,
foreach(var t in byHow) {
Console.WriteLine(" <{0} > :", t.How);
foreach(var m in t.Tlist)
Console.WriteLine(" " + m.Name);
Console.WriteLine();

}
}
}
.
< > :

< > :

< > :

< > :

, , .
var byHow = from how in travelTypes
join trans in transports
on how equals trans.How
into 1st
select new { How = how, Tlist = 1st };

. from
how tr a v e lT y p e s . ,
tr a v e lT y p e s : ,
, .
jo i n . , , ^
. in to
j o in ,
. 1 s t . , s e l e c t
,

19. LINQ

669

how ( ) .
foreach.
foreach(var t in byHow) {
Console.WriteLine(" <{0} > :", t.How);
foreach(var m in t.Tlist)
Console.WriteLine(" " + m.Name);
Console.WriteLine();

}
,
, , .
.


, ,
#. , ,
.
,
, .


S y s t e m .L i n q .Enumerable
IEnumerable<T>.
( S y s t e m .Linq. Queryable,
IQueryable<T>,
.)
, .
C# 3.0 .
, ,
IEnumerable<T>.
Enumerable ,
, .
. ,
, , ,
.
.
v

select
where
orderby

S e l e c t (s e l e c t o r )
W h e r e (p r e d i c a t e )

join

O r d e r B y (k e y S e l e c t o r )
O r d e r B y D e s c e n d i n g (k e y S e l e c t o r )
Join(in n er, o u te r K e y S e le c to r , in n e r K e y S e le c t o r ,

group

G r o u p B y (k e y S e l e c t o r )

resu ltS elector)

670

I. #

Jo i n ( ) ,
,
Func<T, T R e s u l t x ,
:
delegate TResult Funccin , out TResult>( arg)

T Re s u l t , , .
s e l e c t o r ,p r e d i c a t e k e y S e l e c t o r
, . , Where ()
p r e d i c a t e .
.
, .
Join () . ( i n n e r )
,
, Join ().
o u t e r K e y S e l e c t o r ,
i n n e r K e y S e l e c t o r .
r e s u l t S e l e c t o r . o u t e r K e y S e l e c t o r
Func<T0uter , >, i n n e r K e y S e l e c t o r Func<TInner ,
>, r e s u l t S e l e c t o r Func<T0uter, Tinner, TResult>,
TOuter ; Tinner
; T R e s u l t
, .
,
Fun ,
. -.
15, - ,
, , , ,
C# - ,
Fun . -
,
, .


-,
, , C#
. .
.
,
Where () Select () .
// .
// .
using System;
using System.Linq;
class SimpQuery {
static void Main()

19. LINQ
int[] nums = { 1, - 2 ,

6 71

3, , -4, 5 };

// Where() Select ()
// .
var posNums = nums.Where(n => n > 0).Select(r => r);
Console.Write(" nums: ");
// .
foreach(int i in posNums) Console.Write(i + " ") ;
Console.WriteLine ();

}
}
, .
nums: 1 3

.
var posNums = nums.Where(n => n > 0) .Select(r => r);

, posNums.
, ,
, nums. Where (),
, Select (),
. W here ()
nums, IEnumerable<T>,
.
Select () ,
. , Where (),
.
,
. , nums
, .
var posNums = nums.Where(n => n > 0) .Select (r => r * 10);

,
, . ,
,
:
var posNums = nums.Where(n => n > 0) .OrderByDescending(j => j);

j => j , ,
,
W h e r e ().


GroupBy (). .
// GroupBy().
// ,
// .
using System;
using System.Linq;

672

!. C#

class GroupByDemo {
static void Main()

string[] websites = {
"hsNameA.com", "hsNameB.net", "hsNameC.net",
"hsNameD.com", "hsNameE.org", "hsNameF.org",
"hsNameG.tv", "hsNameH.net", "hsNamel.tv"

};
//
// - .
var webAddrs = websites.Where(w => w.LastlndexOf('.') != 1).
GroupBy(x => x.Substring(x.LastlndexOf(".", x.Length)));
// ,
foreach(var sites in webAddrs) {
Console.WriteLine("-, " +
" " + sites.Key);
foreach(var site in sites)
Console.WriteLine (" " + site);
Console.WriteLine();

}
}
}
, .
, .
.
.
join.
var inStockList = from item in items
join entry in statusList
on item.ItemNumber equals entry.ItemNumber
select new Temp(item.Name, entry.InStock);

, ,
.
: items statusList.
, ,
C# , Join ().
// Join()
// ,
var inStockList = items.Join(statusList,
kl => kl .ItemNumber,
k2 => k2 .ItemNumber,
(kl, k2) => new Temp(kl.Name, k2 .InStock)

);

Temp
, .
.
var inStockList = items.Join(statusList,
kl => kl .ItemNumber,

19. LINQ

673

2 => 2 .ItemNumber,
(kl, 2) => new { kl.Name, k2.InStock} );


, C#
, . ,
, ,
. , .

where < 10

.
Where( => < 10)

,
.
,
#? ,
, #,
.

,
, , #, ,
. .NET Framework
IEnumerable<T> Enumerable.
, .
, .

A l l (p r e d i c a t e )

true,
,
.p r e d ic a te

A n y (p r e d i c a t e )

true,
,
p red ica te

A v e r a g e ()
Contains(v a l u e )
C o u n t ()
F i r s t ()
L a s t ()
Max ()
Min ()
Sum ()


true,

, ..





_______

674

I. #

C o u n t () .
, .
// , Enumerable.
using System;
using System.Linq;
class ExtMethods {
static void Main()

int[] nums = { 3, 1, 2, 5, 4 };
Console .WriteLine (" " + nums.MinO);
Console.WriteLine(" " + nums.Max());
Console.WriteLine(" " + nums.First());
Console.WriteLine(" " + nums.Last());
Console.WriteLine(" " + nums.SumO);
Console.WriteLine(" " + nums.Average());
if(nums.All(n => n > 0))
Console.WriteLine(" .");
if(nums.Any(n => (n % 2) == 0))
Console.WriteLine(" .");
if(nums.Contains(3))
Console.WriteLine(" 3.");

}
}
.
1
5
3
4
15
3
.

3.

, ,
, , #.
. , A v e r a g e ()
,
, .
// Average() .
using System;
using System.Linq;
class ExtMethods2 {
static void Main()

19. LINQ

675

int[] nums = { 1, 2, 4, 8, 6, 9, 10, 3, 6, 7 };


var ItAvg = from n in nums
let x = nums.Average()
where n < x
select n;
Console.WriteLine(" " + nums.Average());
Console.Write(" : ");
// ,
foreach(int i in ItAvg) Console.Write(i + " ");
Console.WriteLine ();

}
}
.
5.6
: 1 2

4 3

.
var ItAvg = from n in nums
let x = nums.Average()
where n < x
select n;

, x let
nums. A v e r a g e ()
nums.

:
LINQ : .
,
, foreach.
.
, ,
,
. , , Co unt ().
,
, Count ().
,
. , , 1
foreach.

, .
// .
using System;

676

I. C#

using System.Linq;
class ImmediateExec {
static void Main() {
int[] nums = { 1, -2, 3, 0, -4, 5 };
//
// nums.
int len = (from n in nums
where n > 0
select n).Count();
Console.WriteLine(" nums: " +
len) ;

}
}
.
nums: 3

, foreach
.
Count ().
,
.
var posNums = from n in nums
where n > 0
select n;
int len = posNums.Count(); //

Count () .
.
,
, A r ray () ToList ().
Enumerable. ToAtray ()
, ToList () List. (
25.)
. ,
, posNums,
.
int[] pnums = posNum.ToArray(); //
foreach(int i in pnums)
Console.Write(i + " ");


, LINQ, ,
- . , -

19. LINQ

677

, .
S y s t e m .L i n q .E x p r e s s i o n s .Expression<TDelegate>.
,
, SQL . ,
, .
, , LINQ to SQL
Visual Studio. , C#
.

Compile (), Expression. ,
.

Func System. Func
, .
:
-.
-.
,
. ,
, ,
. .
, .
// .
using System;
using System.Linq;
using System.Linq.Expressions;
class SimpleExpTree {
static void Main() {
// - .
Expression<Func<int, int, b o o l
IsFactorExp = (n, d) => (d != 0) ? (n % d) = = 0

: false;

// .
Func<int, int, bool> IsFactor = IsFactorExp.Compile ();
// ,
if(IsFactor(10, 5))
Console.WriteLine(" 5 10.");
i f (!IsFactor(10, 7))
Console.WriteLine(" 7 10.");
Console.WriteLine ();

}
}
.

678

I. C#

5 10.
7 10.


.
.
Expression<Func<int, int, b o o l
IsFactorExp = (n, d) => (d != 0) ? (n % d) = = 0

: false;

-
. , ,
IsFactorExp.
.
Func<int, int, bool> IsFactor = IsFactorExp.Compile();

IsFactorExp ,
, .
, < F u n c < i n t , int, boo 1>
. Fun int
bool.
Fun , -,
. -
Fun .
, Fun .


,
, .
, , ,
. , , .
LINQ.

, .
, . ,
this. ,
, .
. , , ,
-
, , .
.
static _ ( t h is __ ob,

_)

, _ ,
, . ,
, ,
, . ,
.

19. LINQ

679


.
// ,
using System;
using System.Globalization;
static class MyExtMeths {
// double,
public static double Reciprocal(this double v) {
return 1.0 / v;

}
//
// ,
public static string RevCase(this string str) {
string temp =
foreach(char ch in str) {
if(Char.IsLower(ch)) temp += Char.ToUpper (ch, Culturelnf .
CurrentCulture);
else temp += Char.ToLower(ch, Culturelnfo.CurrentCulture);

}
return temp;

}
// n / d.
public static double AbsDivideBy(this double n, double d)
return Math.Abs(n / d);

}
class ExtDemo {
static void Main() {
double val = 8.0;
string str = "Alpha Beta Gamma";
// Reciprocal()..
Console.WriteLine(" {0} {1}",
val, val.Reciprocal());
// RevCaseO .
Console.WriteLine(str + " : " +
str.RevCase ());
// AbsDivideBy() .
Console.WriteLine(" val.AbsDivideBy(-2) : " +
val.AbsDivideBy(-2));

}
}
.

680

I. #

8 0.125
Alpha Beta Gamma : aLPHA
v a l .AbsDivideBy(-2): 4


MyExtMeths. ,
. ,
, . (
System.
Linq, ,
LINQ.)
,
. ,
.

val.AbsDivideBy(-2)

val A b s D i v i d e B y (),
-2 d.
, R e c i p r o c a l () A b s D i v i d e B y ()
double, ,
.
8.0 .Reciprocal()
8.0 .AbsDivideBy(-1)

, RevCase () .
"AbCDe".RevCase()

PLINQ
.NET Framework 4.0 LINQ
PLINQ.
.
. PLINQ ,
, 24.

, ,


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


C# "
" .
.
, ,

(CLR).
1 , C#
.
,
CLR.

682

I. C#

, ,
, , -
. , ,
- . , ,
.
,
? , .
C++,
, ,
, .. - #.
,
, .
,
. ,
, .
#. -
(,
), C# .
,
.
C# , C/C++.
, C/C++, #.
, C# .

. , , ,
#. ,
/u n s a fe .
,
.


, -
, . ,
, , .
,
. .


- .
-:
*

_;

, .
, C# .
.
* . .
_ -.

20. , ,

683

. ip
i n t, .
int* ip;

float , .
float* fp;

, *,
, .
, ,
. ip
i n t , fp float.
, , , .
.
C/C++,
C# C/C++.
C/C++ * .
:
int* , q;

i n t q i n t .
.
int* ;
int q;

C# * ,
int* , q;

-. .
int* ;
int* q;

C/C++ #.

* &
: * &. &
. (,
.) , :
int* ip;
int num = 10;
ip = &num;

ip num.
num .
num. ip
1 0 , num, ,
. &
, . ,
: " ip
num."

684

I. C#

, *, &.
, ,
. , ,
. , ip
num, , :
int val = *ip;

val 10 num,
ip. * .

: " val ,
ip."
* .
, ,
.
*ip = 100;

1 0 0 ,
ip, .. num.
: " 100 ,
ip."

u n s a fe
, ,
unsafe.
(, ),
( ) .
,
Main (), .
// unsafe.
using System;
class UnsafeCode {
// Main() ,
unsafe static void Main() {
int count = 99;
int* p; // int
p = &count; // count
Console.WriteLine(" count: " + *) ;
* = 10; // 10 count,
//
Console.WriteLine(" count: " + *);

}
}

20. , ,

685

.
count: 99
count: 10

fixe d
fixed,
" '7.
, , ,
.
" ", , .
fixed:
fixed (* = &_) {
//

}
, .
.
fixed
, . fixed
, . ,
fixed .
fixed.
// fixed.
using System;
class Test {
public int num;
public Test (int i) { num = i; }

}
class FixedCode {
// Main() ,
unsafe static void Main() {
Test = new Test(19);
fixed (int* p = &o.num)

{ // fixed
// .num

Console.WriteLine(" .num: " + *);


* = 10; // 10 count,
//
Console.WriteLine(" .num: " + *);

}
}
}
.

686

I. C#

o.num: 19
o.num: 10

. fixed .
. num,
, .


,
.
- (->), - (.).
,
struct MyStruct {
public int a;
public int b;
public int Sum()

{ return a + b; }

}
.
MyStruct = new MyStruct();
MyStruct* p; //
p = &o;
p->a = 10; // ->
p->b = 2 0 ; // ->
Console.WriteLine(" " + p->Sum());


: ++,
, + - . ,
, . ,
p i 2 0 0 0 , ..
2000.
pl++;

p i 2004, 2001! ,
p i in t.
i n t C# 4 ,
p i 4. :
p i 4.
pl ;

, p l 1996,
2 0 0 0 !
:
,
,
, .

20. , ,

687


.
. , :
pi = pi + 9;

p i
, .
,
, , .
,
.
,
, .
, flo at
double. void*.

, ,
, (ip)
(fp).
.
// .
using System;
class PtrArithDemo {
unsafe static void Main()
int x;
int i;
double d;

int* ip = &i;
double* fp = &d;
Console.WriteLine("int
double\n");
for(x=0; x < 10; x++) {
Console.WriteLine((uint) (ip) + " " + (uint)
ip++;
fp++;

(fp));

}
}
}
.
,
.
int

double

1243464
1243468
1243472
1243476
1243480

1243468
1243476
1243484
1243492
1243500

688

I. #

1243484
1243488
1243492
1243496
1243500

1243508
1243516
1243524
1243532
1243540

,
. , i n t
4 , double 8 ,
.


, ==, <
>. ,
- . ,
p i 2 ,
, , .
p i 2 ,
, .


C# . ,
fixed
. .
/*
. */
using System;
class PtrArray {
unsafe static void Main() {
i n t [] nums = new in t [10];
fixed(int* p = &nums[0], p2 = nums) {
if(p == p 2 )
Console.WriteLine(" p p2 " +
" .");

}
}
}
.
2

,
&nums[0]

nums

. ,
, .

20. , ,

689


, .

. .
// .
using System;
class PtrlndexDemo {
unsafe static void Main() {
int[] nums = new int [10];
// .
Console.WriteLine(" .");
fixed (int* p = nums) {
for(int i=0; i < 10; i++)
p[i] = i; //
forjint i=0; i < 10; i++)
Console.WriteLine("p[{0}]:

{1} ", i, p[i]);

}
// .
Console.WriteLine(" " +
" .");
fixed (int* = nums) {
for(int i=0; i < 10; i++)
* (p+i) = i; //
for(int i=0; i < 10; i++)
Console.WriteLine("*(p+{0}):

{1} ", i, *(p+i));

.
.

[0] : 0
[1] = 1
[ 2] : 2
[3] :

[4] : 4
[5] : 5

[6] : 6
[7] : 7

[8 ] :

[9] : 9
.
* (+0) : 0

*(P+1 ) :

* (+2) : 2
* (+3) : 3
* (+4) : 4

690

I. C#

*(+5) : 5
* (+6) : 6

* (+7): 7
* (+8) : 8
* (+9) : 9

,

* (ptr + i)

.
ptr[i]

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


C# ^.
. c h a r*

fixed.
fixed(char* = s t r )

{ // ...

fixed
, .
, .. .
. C/C++
, , ,
ch a r* , , C/C++.
,
c h a r* .
// fixed
// .
using System;
class FixedString {
unsafe static void Main() {
string str = " ";
// str.
fixed(char* = str) {
// str .
for(int i=0; p[i] != 0; i++)
Console.Write(p[i]);

20. , ,

691

Console.WriteLine();

}
}
.


, , ,
. ,
. , ,
.
. 20.1. ,
, .
, , ,
.

--------------

--------------

--------------

. 20.1. -
,

.
.
, ,
. *
. , ,
q in t.
int** q;

, , , q
, i n t.
,
, *, .
using System;
class Multiplelndirect {

692

I. C#

unsafe static void Main() {


int x; // int
int* p; // int
int** q; // int
= 10;
= &; //
q = &; // q
Console.WriteLine(**q); //

}
}
1 0
.
i n t , q in t.
:
, ,
.


, .
i n t
.
int * [] ptrs = new int * [3];

v a r i n t
, .
p t r s [2] = &var;

v ar,
.
*ptrs [2]

s i z e o f

C# .
s i z e o f . :
sizeof ()

, . ,
s i z e o f , ,
: .

s t a c k a llo c
, , s t a c k a l l o c .
.
:

20. , ,

693

* = stackalloc []

, ,
, , , .
,
System. StackOverflowException. , stackalloc
.
,
. .
, , " ",
,
. .
stackalloc , , ,
" ".
stackalloc*
// stackalloc.
using System;
class UseStackAlloc {
unsafe static void Main() {
int* ptrs = stackalloc int[3];
ptrs[0] = 1;
ptrs[1] = 2;
ptrs[2] = 3;
for(int i=0; i < 3; i++)
Console.WriteLine(ptrs[i]);

}
}
.
1


fixed
. C#
. .
, ,
. , ,
, .
, . ,
, ' , , ,
, , #,
, .
.

694

I. C#

:
fixed _[ ];

; _
; , .
.
,
, , C++,
. ,
, .
Name
Balance
ID

80 , 8- ASCII
double 8
long 8

C++ Name,
C# .
C#
, .
// -.
unsafe struct FixedBankRecord {
public fixed byte N a m e [80]; //
public double Balance;
public long ID;

}
Name,
Fi xe dBankRecord 80 Name.
C++. ,
FixedBankRecord 96, .. .
, .
// ,
using System;
// ,
unsafe struct FixedBankRecord {
public fixed byte Nam e [80];
public double Balance;
public long ID;

}
class FixedSizeBuffer {
// Main() ,
unsafe static void Main() {
Console.WriteLine(" FixedBankRecord:
sizeof(FixedBankRecord));

}
}
.
FixedBankRecord: 96

" +

20. , ,

695

FixedBankRecord
, ,
.
, .
,
, .
, C++. ,
, .
, ,
Name.
public fixed byte Name[80]; //

, .
C++ #.
80 FixedBankRecord.


2.0, C# ,
,
, .. .
. ,
, , ,
, -
. , . ,
, -
, , .

, ,
. , ,
,
, . , ,
, ,
. .


,
. , ,
(null). ,
, .
, ,
.
System. Nullable<T>, , .

696

I. #

. -,
Nullable<T>, System,

. ,
int bool.
System.Nullable<int> count;
System.Nullable<bool> done;

-,
? .

int bool.
int? count;
bool? done;

,
.
int? count = null;

count
(null). :
, .
, .
,
. ,
count 1 0 0 .
count = 100;

, ,
. -,
. , count , ,
, .
if (count != null)

//

count , .
-,
Ha sV al ue Nullable<T>, ,
. .
bool HasValue

HasValue true, ,
, ,
false. ,
count
HasValue.
if(count.HasValue)

//

,
Value Nullable<T>.
Value

20. , ,

697

V a l u e ,
.
, S y s t e m .
InvalidOperationException. ,
.

.
// .
using System;
class NullableDemo {
static void Main() {
int? count = null;
if (count.HasValue)
Console.WriteLine(" count :
count.Value);
else
Console.WriteLine(" count ");

" +

count = 100;
if(count.HasValue)
Console.WriteLine(" count : " +
count.Va^lue) ;
else
Console.WriteLine(" count ");

}
}
.
count
count : 100


,
. ,
.
.
,
.

.
// .
using System;
class NullableDemo {
static void Main() {

698

!. C#
int? count = null;
int? result = null;
int incr = 10; // incr
// result ,
// count ,
result = count + incr;
if(result.HasValue)
Console.WriteLine(" result : " +
result.Value);
else
Console.WriteLine(" result ");
// count ,
// result .
count = 100;
result = count + incr;
if(result.HasValue)
Console.WriteLine(" result : " +
result.Value);
else
Console.WriteLine(" result ");

}
}
.
result
result : 110

??

S y s t e m .
InvalidOperationException, .
, , ,
.
, ? ?,
. ,
,
. .
??.
_ ?? __

_ ,
? ? . ? ?
_ _ .
, bala nc e
. c u r re n tB al an ce
0 . 0 , ,
.

20. , ,

699

double? balance = null;


double currentBalance;
currentBalance = balance ?? 0.0;

b a l a n c e
123.75.
double? balance = 123.75;
double currentBalance;
currentBalance = balance ?? 0.0;

c u r r e n t B a l a n c e 1 2 3 . 7 5
balance.

: ? ?
, .
.
// ??
using System;
class NullableDemo2 {
// ,
static double GetZeroBalO {
Console. WriteLine (" GetZeroBalO.");
return 0.0;

}
static void M ai n () {
double? balance = 123.75;
double currentBalance;
// GetZeroBalO ,
// balance .
currentBalance = balance ?? GetZeroBalO;
Console.WriteLine(currentBalance);

}
}
G e t Z e r o B a l () ,
balance . ,
? ? ,
.

,

, .
:
<, >, <= >=, ,
, .. null.
.

700

I. C#

byte? lower = 16;


byte? upper = null;
// lower , upper ,
if(lower < upper) //

%
,
, . , , ,
.
if(lower > upper) // .. !

,
, . ,
(null) .
== ! = ,
. ,
.
if(upper == null)

// ...

bool?,
: true (), false ()
n u l l ().
& | bool?.

P 1Q

P&Q

tr u e
fa ls e
n u ll
n u ll
n u ll

n u ll
n u ll
tr u e
fa ls e
n u ll

tr u e
n u ll
tr u e
n u ll
n u ll

n u ll
fa ls e
n u ll
fa lse
n u ll

, ! b o o l?,
(n u ll),
(n u ll).


2.0, C# ,

. p a r t i a l .
.
p a r t i a l ,
:
partial _ { / / . . .

_ , ,
.
p a r t i a l .

20. , ,

701

, XY,
. .
partial class XY {
public XY(int a, int b)
X = a;
Y = b;

}
}
.
partial class XY {
public int X { get; set;

}
, .
partial class XY {
public int Y { get; set;

}

XY.
// .
using System;
class Test {
static void Main() {
XY xy = new XY (1, 2);
Console.WriteLine(xy.X +

+ xy.Y);

}
}
XY,
. , XY x y l .cs, 2 .cs .cs,
Test t e s t .cs,
.
csc test.cs xyl.cs xy2.cs xy3.cs

: C# .
,
.


, partial
. 3.0, C#

. ,
. , partial
.

70 2

!. C#

,
! ,
. ,
, .
, .
,
Show (). , ShowXY ().
XY ,
, .
// .
using System;
partial class XY {
public XY(int a, int b)
X = a;
Y = b;

}
// ,
partial void Show();

}
partial class XY {
public int X { get; set;

// ,
partial void Show() {
Console.WriteLine("{0}, {1}", X, Y);

}
}
partial class XY {
public int Y { get; set;

// ,
public void ShowXY() {
Show();

}
}
class Test {
static void Main() {
XY xy = new X Y (1, 2);
x y .ShowXY ();

}
}
, Show () XY,
.
X Y. , Show () ShowXY (),
:

20. , ,

7 03

X Y. S h o w (),
S h o w X Y () .
.
void.
. out.


, 3, C#
. , ,
, ,
, .
,
, ,
.
, COM-
,
, , , IronPython. C# 4.0
.
C# 4.0 dynamic.
, dynam ic o b j e c t ,
.
o b j e c t , dynamic
, o b j e c t
.
, ,
dynamic ,
, , ..
. , ,
, ,
.
dynamic
.
// dynamic,
using System;
using System.Globalization;
class DynDemo {
static void Main() {
// ,
dynamic str;
dynamic val;
// .
// ,
str = " ";
val = 10;

704

I. C#
Console.WriteLine(" str : " + str);
Console.WriteLine(" val : " + val + '\n');
str = str.ToUpper(Culturelnfo.CurrentCulture);
Console.WriteLine(" str : " + str);
val = val + 2;
Console.WriteLine(" val : " + val + '\n');
string str2 = str.ToLower(Culturelnfo.CurrentCulture);
Console.WriteLine(" str2 : " + str2);
// .
int = val * 2;
Console.WriteLine(" x : " + x);

}
}
.
str :
val : 10
str :
val : 12
str2 :
: 24

str val,
dynamic. ,
.
.
str T oU pp er () To Lower () String,
.
,
, .
, , ,
.
""
, , ,
, . , val
, ,
. str ,
. , , ,
, ,
dynamic .
.

: d y n a m i c
dynamic. ,
dynamic . ,
,

20. , ,

705

. ,
:
bool b = val;

-
i n t ( v a l ) b ool.
,
.
,
. , s t r v a l o b j e c t ,
.
, o b j e c t ,
, . , ,
o b j e c t dynam ic.
,
o b j e c t ,
o b je c t. dynamic,
, ,
.
, dynamic
,
. 17, ,
, , ,
Invoke (). ,
, . ,
,
, , .
, ,
. ,
, , ,
, .
dynamic, Invoke (), .
MyClass . c s .
.
public class DivBy {
public bool IsDivBy(int a, int b)
if ((a % b) == 0) return true;
return false;

}
public bool IsEven(int a) {
if ((a % 2) == 0) return true;
return false;

}
}
DLL M yClass . d l l .
,
.
csc /t:library MyClass.cs

706

I. C#

, M y C l a s s .dll,
.
// dynamic .
using System;
using System.Reflection;
class DynRefDemo {
static void Main()

Assembly asm = Assembly.LoadFrom("MyClass.dll");


Type[] all = asm.GetTypes();
// DivBy.
int i;
for(i = 0 ; i < all.Length; i++)
if(all[i].Name == "DivBy") break;
if(i == all.Length) {
Console.WriteLine(" DivBy .");
return;

}
Type t = all[i];
/ / .
Constructorlnfo[] ci = t .GetConstructors();
int j ;
for(j = 0 ; j < ci.Length; j++)
if(ci[j].GetParameters().Length == 0) break;
i f (j == ci.Length) {
Console.WriteLine(" .");
return;

// DivBy ,
dynamic obj = ci[j].Invoke(null);
// obj. ,
// obj dynamic,
// , ,
if(obj.IsDivBy(15, 3))
Console.WriteLine("15 3.");
else
Console.WriteLine("15 HE 3.");
if(obj.IsEven(9))
Console.WriteLine("9 .");
else
Console.WriteLine("9 HE .");

}
}

20. , ,

707

,
MyClass . d l l , DivBy.
obj dynamic. ,
Is DivBy () IsEven () obj ,
Invoke (). ,
obj DivBy.
.
.
, dynamic ,
. ,
, , , ,
dynamic,
. , .
dynamic, ,
dynamic ,
.
dynamic o b j e c t , dynamic
o b je c t .
.
static void f(object v) { // ... }
static void f(dynamic v) { / / . . . } / /

: dynamic DLR (Dynamic


Language Runtime ),
.NET 4.0.


C# 4.0 ,
, ()
, , COM- Office Automation.
, dynamic, ,
.
COM- Office Automation ,
, .
.
,
, .
,
COM-, .
, C#
get set.
. , C# 4.0,
COM-
COM-,
. ,
, . , myXLApp,
Microsoft .O ff ic e. I n t e r o p . E x e c l .A p p l i c a t i o n .

708

I. #

"" 1-
Excel ,
.
myXLapp.get_Range("Cl",

"").set_Value(Type.Missing,

"OK");


get R a n g e (), .
s e t _ V a l u e (), (
) . Range
Value, .
,
. , Ty p e . M i s s i n g
, , .
, C# 4.0,
, .
myXLapp.Range["Cl",

""].Value = "OK";


, Ty p e . M i s s i n g ,
.
, r e f
. , ,
r e f , . ,
,
, re f
.


.
.
,
. ,
I n t e r n a l s Vi sibleTo.


I
, C#
.

lo c k
l o c k .
23,
.
.

20. , ,

7 09

C# .
, ,
.. .
,
, .
,
.
lock. :
lock(obj) {
//

}
obj , .
, ,
.
,
.
.

lo c k 23.

re a d o n ly
,
readon ly.
,
. ,
. ,
read on ly .
, , ,
. ,
read on ly.

, re a d o n ly
co n st, .
readonly.
// readonly.
using System;
class MyClass {
public static readonly int SIZE = 10;

710

I. C#

class DemoReadOnly {
static void Main() {
int[] source = new int[MyClass.SIZE];
i n t [] target = new int[MyClass.SIZE];
// source,
for(int i=0; i < MyClass.SIZE; i++)
source[i] = i;
foreach(int i in source)
Console.Write(i + " ");
Console.WriteLine();
// source target.
for(int i = MyClass.SIZE-1, j = 0; i > 0; i , j++)
target[j] = source[i];
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
// MyClass.SIZE = 100; // !!! He !

}
}
M y C l a s s .SIZE 10.
, . ,

. .

c o n s t v o l a t i l e
, , const
, .
. ,
const, , . ,
:
const int i = 10;

i const 10. const


readonly, .
readonly , const .
, , vo la til e ,

. ,
. , C#
,
, .
, volatile.

20. , ,

711

, volatile
, .

u s in g
using,
using . :
using (obj) {
// o b j

}
using ( o b j = )
// obj

}
o b j ,
, System. IDisposable.
, using.
using, .
us in g o b j D is po se (),
System. IDisposable. , using
, ,
. , , , using
, System. IDisposable.
usin g.
// using.
using System;
using System.10;
class UsingDemo {
static void Main() {
try {
StreamReader sr = new StreamReader("test.txt");
// using,
using(sr) {

//

. . .

}
} catch(IOException exc)

II ...
)
try {
// StreamReader using,
using(StreamReader sr2 = new StreamReader("test.txt")) {

/ / ...
}
} catch(IOException exc)

II

...

712

I. C#

I Di sp os ab le StreamReader
( TextReader).
using.
Dispose () , .
, using
,
, . ,
using .
, us ing .
.NET Framework ,
I Disposable.
using.

e x t e r n
extern .
.


extern
#. , ,
. ,
.
,
extern. ,
.
extern _ _ (_) ;

.
e x t e r n
Dll Import, DLL,
. Dll I m p o r t S y s t e m .R u n t i m e .
Inter op Services. , , ,
DLL, .
, . ( C++,
DLL
.)
, ,
, .
E x t M e t h ., AbsMax ().
#include <stdlib.h>
int __declspec(dllexport) AbsMax(int a, int b)
return abs(a) < abs(b) ? abs(b) : abs(a);

}
A b s M a x ()
. _
d e c l s p e c ( d l l e x p o r t ) .

20. , ,

713

Microsoft.
AbsMax () DLL, .
ExtM eth . .
CL /LD /MD ExtMeth.

DLL ExtMeth .d l l .
#,
AbsMax().
using System;
using System.Runtime.InteropServices;
class ExternMeth {
// .
[Dlllmport("ExtMeth.dll")]
public extern static int AbsMax(int a, int b) ;
static void Main()

// ,
int max = AbsMax(-10, -20);
Console.WriteLine(max);

}
}
D lllm p o rt
. DLL,
AbsMax (). ExtM eth. d l l ,
AbsMax () .
, , 2 0 .


e x t e r n
, ,
. , t e s t l
MyClass, t e s t 2 ,
.

. . ,
/ , .
/:Asml=testl
/:Asm2=test2

e x te r n ,
.
.
extern alias _;

,
.
extern alias Asml;
extern alias Asm2;

714

!. C#

MyClass
.
,
. .
, testl.cs.
using System;
namespace MyNS {
public class MyClass {
public MyClass() {
Console.WriteLine(" MyClassl.dll.");

}
}
}
test2.cs.
using System;
namespace MyNS {
public class MyClass {
public MyClass() {
Console.WriteLine(" MyClass2.dll.");

}
}
}
, , t e s t l .cs test2 .cs,
MyNS
MyClass. , MyClass
.
, test3.cs,
MyClass t e s t l .cs test2 .cs.
.
// ,
extern alias Asml;
extern alias Asm2;
using System;
class Demo {
static void Main() {
Asml::MyNS.MyClass t = new Asml::MyNS.MyClass() ;
Asm2::MyNS.MyClass t2 = new Asm2::MyNS.MyClass();

}
}
t e s t l .cs test2 .cs
DLL. .
csc /t:library testl.cs
csc /t:library test2.cs

20. , ,

715

test3.cs,
csc /:Asml=testl.dll /:Asm2=test2.dll test3.cs

/ ,
, .
Asml test 1. dll, Asm2
t e s t 2 .dll.


extern, .
extern alias Asml;
extern alias Asm2;

Main ()
MyClass.
MyClass.
Asml::MyNS.MyClass

,
, ,
, , , , -.
.
.
MyClassl.dll.
MyClass2.dll.

C#
II #.
I, C#

.N E T F ra m e w o rk .
#, .N E T
F ra m e w o rk .
. N E T F ra m e w o rk
.
, ,
,
u s i n g . ,

,

.
. N E T F ra m e w o rk ,

. (
!) II

,
System. ,
,
.

- 14.

21
System
22

23
.
:
24 ]
.
:
T P L
25 ,


26

! [

__________________

System
System.

.NET Framework.
, ,
, ,
C#
.NET Framework. ,
System
.
, System
,
, S ystem.Net.

.
System.

720

II. C#

S ystem
,
.
ActivationContext
AppDomainManager
Applicationldentity
Attribute
Buffer
Console
Co ntextStat icAttr ib ute
Delegate
EventArgs
FlagsAttribute
GenericUriParser
Lazy<T>
LoaderOptimizationAttribute
Math
NetPipeStylellriParser
NonSerializedAttribute
ObsoleteAttribute
Random
STAThreadAttribute
ThreadStaticAttribute
Tim eZonelnfo.AdjustmentRule
Type
UriBuilder
UriTemplateEquivalenceComparer
UriTypeConverter
W eakReference

Activator
AppDomainSetup
Array
AttributeUsageAttribute
CharEnumerator
ConsoleCancelEventArgs
Convert
Enum
Exception
FtpStylellri Parser
GopherStylellri Parser
Lazy<T, TMetadata>
Local DataStoreSlot
MTATh read Attribute
NetTcpStylellriParser
Nullable
Ope rati ngSystem
ResolveEventArgs
String
Tim eZone
Tuple
Unhandled Exception EventArgs
Uri Parser
UriTemplateMatch
ValueType

AppDomain
Applicationld
Asse m b ly Loa d Eve ntA rgs
BitConverter
CLSCompliantAttribute
Co ntext Bo u n d 0 bj ect
DBNull
Environment
FileStylellriParser
GC
HttpStyleUri Parser
LdapStylellriParser
Ma rsha 1By RefO bject
MulticastDelegate
NewsStylellriParser
Object
Pa ra m Ar rayAttr ib ute
SerializableAttribute
StringCom parer
TimeZonelnfo
Tuple<...> ( )
Uri
UriTemplate
UriTemplateTable
Version

, S y s t e m .
Arglterator
Byte
DateTime
Double
Int32
ModuleHandle
RuntimeFieldHandle
Sbyte
Tim eZonelnfo.TransitionTim e
Ulnt32
Void

ArraySegment<T>
Char '
DateTimeOffset
Guid
Int64
Nullable<T>
RuntimeMethodHandle
Single
Typed Reference
Ulnt64

Boolean
ConsoleKeylnfo
Decimal
Int 16
IntPtr
RuntimeArgumentHandle
RuntimeTypeHandle
TimeSpan
Uint16
U IntPtr

System .

21. System
_AppDomain
ICIoneable
IC onvertib le

IEquatable<T>
IObservable<T>

lappDomainSetup
IComparable
1Custom Formatter
IFormatProvider
IObserver<T>

721

lAsyncResult
IComparable<T>
IDisposable
IFormattable
IServiceProvider

, System.
Action
AssemblyLoadEventHandler
ConsoleCancelEventHandler
EventHandler
Predicate<T>

Action<...> ( )
AsyncCallback
Converter<Tlnput, VOutput>
EventHandler<TEventArgs>
ResolveEventHandler

AppDomainlnitializer
Comparison<T>
CrossAppDoma in Delegate
Func<...> ( )
Unhandled ExceptionEventHandler

System .
ActivationContext.contextForrri
Base64Formatting0ptions
ConsoleModifiers
DayOfWeek
EnvironmentVariableTarget
GenericUriParserOptions
PlatformID
TypeCode
UriHostNameType
Uri Partial

AppDomainManagerlnitializationOptions
ConsoleColor
ConsoleSpecialKey
Environment.SpecialFolder
GCCol lection Mode
LoaderOptimization
StringComparison
UriComponents
UrildnScope

AttributeTargets
ConsoleKey
DateTimeKind
Environment.SpecialFolderOption
GCNotificationStatus
MidpointRounding
StringSplitOptions
UriFormat
UriKind

, S y s t e m
,
. , System,
Nullable<T>, Type, Exception Attribute, I
II. , System. String,
string #,
22.
,
C# .

Math
M ath ,
, , .
Math , , , ,
static, Math , Math
. , Math,
. 2 1 .1 , .
Math :
public const double
public const double PI

E ,
) a PI .

722

II. C#

21.1. , M ath

public static double


A bs(double v a l u e )
public static float
A bs(float v a l u e )
public static decimal
Abs(decimal v a l u e )
public static int Abs(int

v a l u e
v a l u e
v a l u e
'

v a l u e

v alu e)
public static short
Ab s( short v a l u e )
public static long Abs(long

v a l u e
v a l u e

v alu e)
public static sbyte
Abs(sbyte v a l u e )
public static double
Ac os (double d)
public static double
As in (double d)
public static double
At an(double d)
public static double
Atan2(double y, double x)
public static long
BigMul(int a , int b)
public static double
Ceiling(double a)

public static double


Ceiling(decimal d)

public static double


Cos(double d)
public static double
Cosh(double d)
public static int DivRem(int a,
int b , out int r e s u l t )
public static
long DivRem(long a ,
long b , out long r e s u l t )

v a l u e
d. d
-1 1
d. d
-1 1
d
/
*
long,
,

. , 1,02,
C e i l i n g () 2,0.
-1,02, C e i l i n g ()
-1
,

d. , d 1,02, C e i l i n g ()
2,0. d -1,02,
Ceiling () -1
d

/ ,
r e s u l t out / ,
r e s u l t out

21. System

public static double


Exp (double "d)
public static decimal
Floor(decimal d)

public static double


Floor(double d)

public static double


IEEERemainder(double x ,
double y)
public static double
Log(double d)
public static double'
Log(double d, double

723

_______________ . 21.1

,
d
,

d. , d 1,02, Floor ()
1,0. d -1,02,
Floor () -2
,

d. , d 1,02, Floor ()
1,0. d -1,02,
Floor () -2
/

newBase

newBase)

public static double


LoglO(double d)
public static double
Max(double v a i l , double v a l 2 )
public static float
Max(float v a i l , float v a l 2 )
public static decimal
Max(decimal v a i l , decimal

10

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

val2)
public static int Max(int
v a i l , int v a l 2 )
public static short Max(short
v a i l , short v a l 2 )
public static long Max(long
v a i l , long v a l 2 )
public static uint Max(uint
v a i l , uint v a l 2 )
public static ushort
Max(ushort v a i l , ushort v a l 2 )
public static ulong
Max(ulong v a i l , ulong v a l 2 )
public static byte Max(byte
v a i l , byte v a l 2 )
public static sbyte Max(sbyte
v a i l , sbyte v a l 2 )

724

II. C#
. 21.1

public static double


Min(double v a i l , double v a l 2 )
public static float
Min(float v a i l , float v a l 2 )
public static decimal
Min(decimal v a i l , decimal
v a l 2 )
public static int Min(int
v a i l , int v a l 2 )
public static short Min(short
v a i l , short v a l 2 )
public static long Min(long
v a i l , long v a l 2 )
public static uint Min(uint
v a i l , uint v a l 2 )
public static ushort
Min (ushort v a i l , ushort v a l 2 )
public static ulong Min(ulong
v a i l , ulong v a l 2 )
public static byte Min(byte
v a i l , byte v a l 2 )
public static sbyte Min(sbyte
v a i l , sbyte v a l 2 )
public static double
Pow(double x , double y)
public static double
R ound(double a)
public static decimal
R ound(decimal d)
public static double
Round(double v a l u e ,
int d i g i t s )
public static decimal
R ound(decimal d, int d i g i t s )
public static double
R ound(double v a l u e ,
M id po in tR ou ndi ng m o d e )
public static decimal
Round(decimal d,
M i d p o in tR ou nd ing m o d e )
public static double
R ound(double v a l u e , int
d i g i t s , Midpo in tR ou nd in g
mode)

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

vail

val2

,
( )

,

d,

v a l u e ,
,
d i g i t s
d, ,

d i g i t s
v a l u e ,
,
m o d e
d,
,
m o d e
v a l u e ,
,
d i g i ts, mode
___________________________

21. System

725

. 21.1

public static decimal


Round(decimal d, int d i g i t s ,
MidpointRounding mode)
public static int
Sign(double v a l u e )
public static int Sign(float

v alu e)
public static int
Sign(decimal v a l u e )
public static int Sign(int

v alu e)
public static int Sign(short

v alu e)
public static int Sign(long

v alu e)
public static int Sign(sbyte

v alu e)
public static double
Sin(double a)
public static double
Sinh(double v a l u e )
public static double
Sqrt(double d)
public static double
Tan(double a)
public static double
Tanh(double v a l u e )
public static double
Truncate(double d)
public static decimal
Truncate(decimal d)

d, ,

d i g i t s , m o d e

-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e
-1, v a l u e ;
, v a l u e ; 1,
v a l u e

v a l u e
d
a

v alu e

Sqrt ()

.

726

II. C#

// .
using System;
class Pythagorean {
static void Main()
double si;
double s2;
double hypot;
string str;

Console.WriteLine(" : ");
str = Console.ReadLine();
si = Double.Parse(str);
Console.WriteLine(" : ");
str = Console.ReadLine();
s2 = Double .'Parse (str) ;
hypot = Math.Sqrt(sl*sl + s2*s2);
Console.WriteLine(" " + hypot);

}
}
.
: 3
: 4
: 5

, Pow ()
,
, .
.
=
/ (1 + )

Pow () double,
double.

d ecim al.
/* ,
,
. */
using System;
class Initiallnvestment {
static void Main() {
decimal initInvest; //
decimal futVal;
//
double numYears;
double intRate;

//
//

21. System

727

string str;
Console.Write(" : ");
str = Console.ReadLine();
try {
ftitVal = Decimal.Parse (str) ;
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;

}
Console.Write(" (, 0.085): ") ;
str = Console.ReadLine();
try {
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;

}
initlnvest =
futVal / (decimal) Math.Pow(intRate+1.0, numYears);
Console.WriteLine(" :
initlnvest);

{0:C}",

}
}
.
: 10000
(, 0.085): 0.07
: 10
: $5,083.49

.NET,
, C# ,
14, ,
, .
.NET .
.NET ,
#, .

728

II. C#

.NET

C#

S y s t e m .Boolean
System.Char
System.Decimal
System.Double
S y s t e m .Single
System.Intl6
S y s t e m .Int32
System.Int64
S y s t e m .U l n t l 6
System.UInt32
System.UInt64
S y s t e m .Byte
System.Sbyte

bool
char
decimal
double
float
short
int
long
ushort
uint
ulong
byte
sbyte

, ,
.
.

, , C#
, iFormatProvider NumberStyles.
I Format Provide , NumberStyles
System.Globalization.
22.


.
Byte
Int32

SByte
UInt32

In 1 16
Int64

Uintl6
U i n t 64

. . 21.2
I n t 32.
, ,
.
,
const.
MaxValue
MinValue

,
.

: I C o m p a r a b l e , I C o m p a r a b l e < T > , I C o n v e r t i b l e , I F o r m a t t a b l e

21. System

7 29

I E q u a t a b l e < T > ,
. , Int32 int.

21.2. , In t3 2

public int
CompareTo(object v a l u e )

public int CompareTo(int


value)

public override bool


Equals(object o b j )


v a l u e . ,
; ,
; , ,
,


v a l u e . ,
; ,
; , ,
,

true,

obj

public bool Equals(int


obj)

true,

obj

public override int


G e t H a s h C o d e ()

public TypeCode
G e t T y p e C o d e ()

TypeCode
. , Int32
T y p e C o d e .Int32
,
s.
,
,
,
s,
,
p r o v i d e r .
,
,

,
s,
, s t y l e s .
,
,

public static int


Parse(string s )

public static int


Parse(string s,
IformatProvider
p r o v i der)

public static int


Parse(string s ,
NumberStyles s t y l e s )

730

II. C#
. 21.2

public static int


Parse(string s ,
NumberStyles s t y l e s ,
IformatProvider

p r o v i der)

public override string


T o S t r i n g ()
public string
T oS tr ing(string f o r m a t )
public string
T o S t r i n g (IformatProvider

p r o v i der)
public string
ToStri ng (s tr in g f o r m a t ,
IformatProvider

p ro v id er)
public static bool
TryParse( st ri ng s , out
int r e s u l t )

public static bool


TryParse( st ri ng s ,
N um berStyles s t y l e s ,
IformatProvider
p r o v i d e r , out int

resu lt)

,
s, ,
s t y l e s ,
,
p r o v i d e r .
,
,



, ,
f o r m a t

,

p r o v i d e r

, ,
f o r m a t ,
,
p r o v i d e r

, s,
.
r e s u l t
true,
false, Parse (),


, s,
,
s t y l e s ,
,
p r o v i d e r .
r e s u l t
true,
false,
Parse (),
__________________


: Double
Si ng le . S i n g l e float.
. 21.3, . 21.4. D o u b le double.

21. System

731

. 21.5, . 21.6.
, Parse () T o S t r i n g O
,
, .

21.3. , S in g le

public int
CompareTo(object v a l u e )

public int
CompareTo(float v a l u e )

public override bool


Equals(object o b j )
public bool Equals(float

obj)
public override int
G e t H a s h C o d e ()
public TypeCode
G e t T y p e C o d e ()
public static bool
Islnfinity(float f )
public static bool
IsNaN(float f )
public static bool
IsPositivelnfinity(float
f)

public static bool


IsNegativelnfinity(float
f)

public static float


Parse(string s )
public static float
Parse(string s ,
IformatProvider

p ro v id er)


v a l u e . ,
; ,
, , ,
,


v a l u e . ,
; ,
, , ,
,

true,
o b j
true,
o b j
-
T y p e C o d e
Single, .. TypeCode .Single
true,
f .
false
true, f
.
false
true,
f .
false
true, f
.
false
,
s.
float,
,
s,
,
p r o v i d e r .
float,
_______________________

732

II. C#
. 21.3

public static float


Parse(string s ,
NumberStyles s t y l e s )

public static float


Parse(string s ,
NumberStyles s t y l e s ,
IformatProvider

p r o v i der)

public override string


ToString ()
public string
ToString( st ri ng f o r m a t )
public string
T o S t r i n g (IformatProvider

p r o v i der)
public string
ToString( st ri ng f o r m a t ,
IformatProvider

p ro v id er)
public static bool
T r y P a r s e (string s , out
float r e s u l t )

public static bool


T ry Pa rs e(string s ,
NumberStyles s t y l e s ,
IformatProvider
p r o v i d e r , out float

resu lt)

,
s,
, s t y l e s .
float,

,
s,
,
p r o v i d e r ,
, s t y l e s .
float,




, ,
' f o r m a t

,

p r o v i d e r

, ,
f o r m a t ,
,
p r o v i d e r
,
s, float.

r e s u l t
true,
false, Parse (),


, s,
float, ,
f o r m a t ,
,
p r o v i d e r ,
a, ,
s t y l e s .
r e s u l t
true,
false, Parse (),

21. System

733

21.4. , S in g le

public const float Epsilon

public const float


MaxValue

float

public const float


MinValue

public const float NaN

,
,

public const float


NegativeInfinity
public const float
PositiveInfinity

float

21.5. , Double

public int CompareTo(object


v a l u e . ,
; ,
,
, , ,


v a l u e . ,
; ,
,
, , ,

true,
o b j
true,
o b j
-

value)

public int CompareTo(double


value)

public override bool


Equals(object o b j )
public bool Equals(double
obj)

public override int


G e t H a s h C o d e ()
public TypeCode
G e t T y p e C o d e ()
public static bool
Islnfinity(double d)

public static bool


IsNaN(double d)
public static bool
IsPositivelnfinity(double
d)

T y p e C o d e
Double, .. TypeCode .Double
true,
d .

false
true,
d .
false
true,
d .
false

734

II. C#
. 21.5

public static bool


Is Ne gativelnfinity(double

d)
public static double
Parse(string s)

public static double


Parse(string s ,
IFormatProvider p r o v i d e r )

public static double


Parse (string s ,
NumberStyles s t y l e s )

public static double


Parse(string s ,
NumberStyles s t y l e s ,
IFormatProvider p r o v i d e r )

public override string


T o S t r i n g ()
public string
To St ring(string f o r m a t )
public string
T o S t r i n g (IformatProvider

p r o v i der)
public string
ToString( st ri ng f o r m a t ,
IformatProvider p r o v i d e r )

public static bool


TryParse( st ri ng s , out
double r e s u l t )

true,
d .
false
,
s.
double,

,
s,
,
p r o v i d e r .

double,
,
s,
, s t y l e s .

double,
,
s,
,
p r o v i d e r ,
,
s t y l e s .
double,



,
, f o r m a t


,
p r o v i d e r

, ,
f o r m a t ,
,
p r o v i d e r
,
s, double.

r e s u l t
true,
false, Parse (),

21. System

735

. 21.5

public static bool


TryParse(string s ,
NumberStyles s t y l e s ,
IFormatProvider p r o v i d e r ,
out double r e s u l t )


, s,
double,
, f o r m a t ,
,

p r o v i d e r , ,
s t y l e s .

r e s u l t true,
false,
Parse (),

21.6. , Double

public const double Epsilon

public const double


MaxValue

double

public const double


MinValue

double

public const double NaN


public const double
NegativeInfinity
public const double
PositiveInfinity

,
,
,
,

D ecim al
Decimal ,
, .
, , , decimal
, #. ,
decimal
.
Decimal .
.
public
public
public
public
public
public

Decimal(int )
Decimal(uint )
Decimal(long )
Decimal(ulong )
Decimal(float )
Decimal(double )

736

II. C#

Decimal
.
, Decimal
.
public Decimal(int l o ,

int mid, int h i , bool Is N e g a tiv e , byte sc a le )

. 96-
, , .
, 96- 32-
l o , m i d h i ;
I s N e g a t i v e , false
, true
; s c a l e ,
0 28. 10 (.. 10scaJe),
.
Decimal
, ,
.
public Decimal(int[] b i t s )

int b i t s 96-
; 31- b i t s [ 3 ] (0
, 1 ); 16-23
.
D e c i m a l : I C o m p a r a b l e ,
IComparable<decimal>, IConvertible, IFormattable, IEquatable<decimal>,

IDeserializationCallback.
decimal
.
// .
using System;
class CreateDec {
static void Main() {
decimal d = new decimal(12345, 0, 0, false, 2);
Console.WriteLine(d);

}
}
.
123.45

96- 12345.
.
, Decimal, ._21.7,
. 21.8. , Decimal
,
. ,
, 3.

21. System

737

21.7. , Decim al

public static decimal


Add(decimal "dl, decimal d2)
public static decimal
Ceiling(d)

public static int


Compare(decimal dl, decimal d2)

public int CompareTo(object


value)

public int CompareTo(decimal


value)

public static decimal


Divide(decimal dl,
decimal d2)
public bool Equals(decimal
value)

public override bool


Equals(object v a l u e )
public static bool
Equals(decimal dl, decimal d2)
public static decimal
Floor(decimal d)

public static decimal


FromOACurrency(long cy)

dl + d2

,
decimal
d. , d 1,02, C eiling ()
2,0. d -1,02,
C e i l i n g () -1
dl
d2. ,
; , dl
d2; , , ,
dl d2

v a l u e . ,
;
,
; , , ,


v a l u e . ,
;
,
; , , ,

d l / d2

true,

v a l u e
true,

v a l u e
true,
dl d2
,
d e c i m a l
d. , d 1,02, Floor ()
1,0. d -1,02,
Floor 0 -2

, OLE
Automation, _______________

738

II. C#
. 21.7

public static i n t []
GetBits(decimal d)
public override int
G e t H a s h C o d e ()
public TypeCode G e t T y p e C o d e ()


d int.

-

..

T y p e C o d e D e c i m a l ,
T y p e C o d e .Decimal
public static decimal
Multiply(decimal d l , decimal d2)
public static decimal
N egate(decimal d)
public static decimal
Parse(string s)

public static decimal


Parse(string s ,
IFormatProvider p r o v i d e r )

public static decimal


Parse(string s , NumberStyles

sty les)

public static decimal


Parse (string s , NumberStyles
s t y l e s , IformatProvider

p r o v i der)

public static decimal


Remainder(decimal d l , decimal d2)
public static decimal
Round(decimal d)
public static decimal
Round(decimal d, int d e c i m a l s )

d l * d2

-d

,
s.

decimal,
,
s,
,

p r o v i d e r .
decimal,

,
s,
,
s t y l e s .
decimal,

,
s,
,

p r o v i d e r ,
, s t y l e s .

decimal,

d l / d2

d,

d,
,
d e c i m a l s ,
0 28_____________

_21. System

7 39

_______________ . 21.7

public static decimal


d,
Round(decimal d,
,
MidPoiritRounding mode)
mode.
, d

public static decimal


d,
Round(decimal d, int d e c i m a l s , ,
MidPointRounding mode)
d e c i m a l s ,
0 28, mode
.
,
d

public static decimal
d l - d2
Subtract(decimal d l , decimal d2)
public static byte
ToByte(decimal v a l u e )

public static double


ToDouble(decimal d)

public static short


T o ln tl 6 (decimal d)

v a l u e
.
v a l u e
byte,
O verflowException
dTnna double.
,
double ,
decimal
dTnna short.
. d

short,
byte.

OverflowException

d int.
. d

int,

public static int


ToInt32(decimal d)

OverflowException

d long.
. d

long,

public static long


ToInt64(decimal d)

OverflowException
public static long
ToOACurrency(decimal

v alu e)

v a l u e
,
OLE Automation, __________________________

740

II. C#
. 21.7

public static sbyte


ToSByte(decimal v a l u e )

public static float


ToSingle(decimal d)

v a l u e
sbyte. .
value
sbyte,
Overf lowException
dTnna float.
. d

float,
OverflowException

public override string


T o S t r i n g ()
public string ToString(string

form at)





,
,
form at

public string
T o S t r i n g (IFormatProvider

p ro v id er)



,

p ro v id er

public string ToString (string


f o r m a t , IFormatProvider

p ro v id er)

public static ushort


T o U I n t l 6 (decimal v a l u e )

public static uint


ToUInt32(decimal d)


,
,
f o r m a t , ,

p r o v i d e r
v a l u e
ushort. .
v a l u e
ushort,
Overf lowException
dTnna uint.
. d

uint,
OverflowException

public static ulong


ToUInt64(decimal d)

dTnna ulong.
. d

ulong,
OverflowException

public static decimal


Truncate(decimal d)

d.
___________ ________________

21. System

741

. 21.7

public static bool


TryParse(string s , out decimal
result)

public static bool


TryParse(string s ,
NumberStyles s t y l e s ,
IFormatProvider p r o v i d e r ,
decimal r e s u l t )

out


,
s, decimal.

r e s u l t
true.
false,
Parse ( ) ,


,
s, decimal,
,
format, ,

p r o v i d e r ,
,
s t y l e s .
r e s u l t
true.
false,
Parse (),

21.8. , Decim al

public static readonly


decimal MaxValue

public static readonly


decimal MinusOne
public static readonly
decimal MinValue

-1

public static readonly


decimal One
public static readonly
decimal Zero

decimal
decimal

, '
decimal

decimal

decimal

C h ar
Char char ,
,
. ,
, T o U p pe r (),
Is Digit () , .

742

II. C#

, Char, . 21.9. ,
, , , C o n v e r t F r o m U t f 32 ()
Conver tT oU tf 32 (), UTF-16
UTF-32. 16 ,
char.
, 16 .
,
(UTF). , UTF-16
16- ,
16- .
16- ,
char. ,
. UTF-32
32- . Char
UTF-16 UTF-32 .
C ha r :
To Up pe r () ToLower ()
( ),
.

, Culturelnf
. Culture Info System.
Globalization,
Culturelnf .CurrentCulture .
Char .
public const char MaxValue
public const char MinValue

, Char : IComparable,
IComparable<char>, IConvertible IEquatable<char>.

21.9. , Char

public int CompareTo(char


v a l u e . ,
; ,

; , , ,


v a l u e . ,
; ,

; , , ,

,
u t f 3 2 UTF-32,
UTF-16 __________________

value)

public int CompareTo(object


value)

public static string


C o n v e r t F r o m U t f 3 2 (int u t f 3 2 )

21. System

pubic static int


ConvertToUtf*32 (char
h i g h S u r r o g a t e , char

low S u rrog ate)


pubic static int
ConvertToUtf3 2 (string s ,

int

in dex)
public bool Equals(char o b j )
public override bool
Equals(object o b j )
public override int
G e t H a s h C o d e ()
public static double
GetNumericValue(char c)
public static double
GetNumericValue(string s ,

int

in d e x )
public TypeCode G e t T y p e C o d e ()
public static UnicodeCategory
GetUnicodeCategory(char c)

public static UnicodeCategory


GetUnicodeCategory(string s ,
int in d e x )

public static bool


IsControl(char c)
public static bool
IsControl(string s ,

index)
public static bool
IsDigit(char c)

int

743

______________ . 21.9

,
h ig hS ur ro ga te
l o w S u r r o g a t e UTF-16,
UTF-32

UTF-16,

s [ i n d e x ] , UTF-32

true,
o b j
true,
o b j
-
,
.
-1
,
s [ i n d e x ] ,
.
-1
TypeCode
Char, .. TypeCode .Char

U n i c o d e C a t e g o r y .
U n ic od eC at eg or y
S y s t e m . G l o b a l i z a t i o n


U n i c o d e C a t e g o r y ,
s [ i n d e x ] .
U n i c o d e C a t e g o r y
Syste m. Gl ob al iz at io n

true,
,
false
true,
, s [ i n d e x ] ,
,
false
true,
,
false

744

II. C#
. 21.9

public static bool


IsDigit(string s , int i n d e x )

public static bool


I sH ighSurrogate(char c)

public static bool


I sH ighSurrogate(string s ,

int

in d e x )

public static bool


IsLetter(char c)
public static bool
IsLetter(string s , int i n d e x )

public static bool


IsLetterOrDigit(char c)
public static bool
I sL et te rOrDigit(string s ,

int

in d ex )
public static bool
IsLower(char c)
public static bool
IsLower(string s , int i n d e x )

public static bool


IsLowSurrogate(char c)

public static bool


I sL ow Surrogate(string s ,

in d e x )

public static bool


IsNumber(char c)

int

true,
, s [ i n d e x ] ,
,
false
true,

UTF-32,
false
true,
,
s [ i n d e x ] ,
UTF-32,
false
true,
,
false
true,
, s [ i n d e x ] ,
,
false
true,
,
false
true,
, s [ i n d e x ] ,
,
false
true,
,
false
true,
, s [ i n d e x ] ,
,
false
true,

UTF-32,
false
true,
,
s [i n d e x ] ,
UTF-32,
false
true,
(
),
false____________________________

21. System

public static bool


IsNumber(string s , int i n d e x )

public static bool


IsPunctuation(char c)
public static bool
IsPunctuation(string s ,

int

index)

public static bool


IsSeparator(char c)
public static bool
IsSeparator(string s ,

int

index)

public static bool


IsSurrogate(char c)

public static bool


IsSurrogate(string s ,

int i n d e x )

public static bool


IsSurrogatePair(char
h i g h S u r r o g a t e , char

745

______________ . 21.9

true,
, s [ i n d e x ] ,
( ),
false
true,
,
false
true,
, s [ i n d e x ],
,
false
true,
,
false
true,
, s [ i n d e x ],
,
false
true,

,
false
true,
,
s [ i n d e x ] ,
, false
true,
h i g h S u r r o g a t e
l o w S u r r o g a t e

low Surrogate)

public static bool


IsSymbol(char c)

public static bool


IsSymbol(string s , int i n d e x )

public static bool


IsUpper(char c)
public static bool
IsUpper(string s , int i n d e x )

true,
,
,
false
true,
, s [ i n d e x ],
,
,
false
true,
,
false
true,
, s [ i n d e x ],
,
false________

746

II. C#
. 21.9

public static bool


IsWhiteSpace(char )

public static bool


Is WhiteSpace(string s ,

int

index)

public static char


Parse(string s )

true,
,
,
false
t r u e ,
,
s [ i n d e x ] , ,
,
false
c h a r
s. s
,
F ormatException

public static char


ToLower(char c)
public static char
To Lower(char c, Culturelnfo
culture)

,
.

,
.
.

,
c u l t u r e , C u l t u r e l n f o
,
System.Globalization

public static char


ToLowerln va ri an t( ch ar c)
public override string
T o S t r i n g ()
public static string
ToString (char c)
public string
ToString(IForm at Pr ov id er
p r o v i der)

public static char


ToUpper(char c)
public static char
ToUpper(char c , Culturelnfo
culture)




Char



C ha r
,
p r o v i d e r
,
.

,
.
.

,
c u l t u r e , Cultu re ln fo ,
System.
Globalization

21. System

747

. 21.9

public static char


ToUpperlnvariant(char )
public' static bool
TryParse(string s , out char
result)




s
char.
r e s u l t
true. s
,
false,
P arse ( ) ,
____________

,
, Char.
// ,
// Char.
using System;
using System.Globalization;
class CharDemo {
static void Main() {
string str = " . $23";
int i;
for(i=0; i < str.Length; i++) {
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 ();

748

II. C#
V

Console.WriteLine(" : " + str);


// .
string newstr = "";
for(i=0; i < str.Length; i++)
newstr += Char.ToUpper (str[i], Culturelnf .CurrentCulture) ;
Console.WriteLine(" : " + newstr);

}
}
.
















.

$
2
3
: . $23
: . $23

B o o le a n
B oolean bool. ,
, . 21.10. ,
.
public static readonly string FalseString
public static readonly string TrueString

t r u e f a l s e
. , F a l s e S t r i n g -
W riteLine (), "False".
B o o l e a n : I C o m p able,
IComparable<bool>, IConvertible IEquatable<bool>.

21. System

749

21.10. , B o o le a n

public int CompareTo(bool


v a l u e ).

public int
CompareTo(object o b j )

public bool Equals(bool o b j )


public override bool
Equals(object o b j )
public override int
G e t H a s h C o d e ()
public TypeCode
G e t T y p e C o d e ()
public static bool
Parse(string s )

public override string


T o S t r i n g ()
public string
ToString(IFormatProvider
provider)

public static bool


TryParse(string s , out
bool r e s u l t )


v a l u e . ,
;
,
false, v a l u e
true; , , ,
true,
value false

o b j . ,
;
,
false, o b j
true; , , ,
true,
o b j false
true,
o b j
true,
o b j
-
T y p e C o d e
Boolean, .. TypeCode .Boolean
b o o l
s. s B o o l e a n .
TrueString, B o o l e a n .F al seString,
F o r m a tE xc ep ti on ,
,
:
,
,
TrueString, FalseString

,
TrueString, FalseString.
p r o v i d e r

s bool.

r e s u l t
true. s B o o l e a n .
TrueString, B o o l e a n .FalseString,
false,
, :
, Parse (),

750

II. C#

A r r a y
Arr ay
System. #. ,
C#
. , Array,
. 2 1 .1 1 , . 2 1 .1 2 .
Ar ra y : ICloneable, ICollection,
IEnumerable, IStructuralComparable, IStructuralEquatable, IList.
, I C l on ea bl e, System.
Collections, 25.
I C o m p a r e r
I C o m p a re r< T> . I C o m p a r e r System.
Collections. Co m p a r e ()
, .
int Compare(object , object )

, ;
, ; , , , .
IComparer<T> System. Collections .
Generic. Compare (), .
int Compare( , )

, ,
, , , , ,
, . IComparer<T>
, .
, ,
.

.

21.11. , A r r a y

.
true, ,
false,

public bool isReadOnly
.
{ get; }
true, Ar ra y
, false.
true
public bool
. IsSynchroniz
Lzed { get; } true,
,
false.
true
public bool
{ get; }

isFixedSize

21. System

751

. 21.11

public
{ get;
public
public
{ get;

. int
long LongLength . long
}

int Rank { get; } .
object SyncRoot . , }__________________ __________

public int Length


get; }
-

21.12. , A r r a y

public static
ReadOnlyCollection<T>
A s R e a d O n l y < T > ([] a r r a y )
public static int
BinarySearch(Array a r r a y ,
object v a l u e )


, ,
a r r a y
v a l u e
a r r a y .
. ,
. a r r a y

v a l u e
a r r a y .
. ,
. a r r a y

v a l u e
, a r r a y ,
,
c o m p a r e r .
. ,
. a r r a y

v a l u e
a r r a y , ,
c o m p a r e r .
.
, .
a r r a y
v a l u e
a r r a y . ,
i n d e x ,
, l e n g t h .

. ,
. a r r a y
______________

public static int


Bi n a r y S e a r c h < T > ( T [
T value)

array,

public static int


BinarySearch(Array a r r a y ,
object v a l u e , IComparer
comparer)

public static int


B i n a r y S e a r c h < T > ( T [] a r r a y ,
T v a l u e , IComparer<T>
comparer)

public static int


BinarySearch(Array a r r a y ,
int i n d e x , int l e n g t h ,
object v a l u e )

752

II. C#
. 21.12

public static int


B i n a r y S e a r c h < T > ([] a r r a y ,
int i n d e x , int l e n g t h , T
value)

public static int


Bina ry Se ar ch (A rra y a r r a y ,
int i n d e x , int l e n g t h ,
object v a l u e , IComparer
comparer)

public static int


BinarySear ch <T >( T [] a r r a y ,
int i n d e x , int l e n g t h ,
T v a l u e , Icomparer<T>
comparer)

public static void


C le ar (Array a r r a y , int
i n d e x , int l e n g t h )

public object Clone ()

public static void


ConstrainedCopy(Array
s o u r c e A r r a y , int s o u r c e l n d e x ,
Array d e s t i n a t i o n A r r a y , int
d e s t i n a t i o n l n d e x , int l e n g t h )

v a l u e
a r r a y . ,
i n d e x ,
, l e n g t h .

. ,
. a r r a y

v a l u e
a r r a y , ,
c o m p a r e r .
, i n d e x ,
,
l e n g t h .
. ,
. a r r a y

v a l u e
a r r a y , ,
c o m p a r e r .
, i n d e x ,
,
l e n g t h .
. ,
. a r r a y

a r r a y
, null
false
: , .
, ,
,
i n d e x , ,
l e n g t h
.
, ,
".
, , ,
,

,
l e n g t h ,
s o u r c e A r r a y , ,
s o u r c e l n d e x , d e s t i n a t i o n A r r a y , ,

21. System

public static []
Convert 1 1 < I n p ut ,
TTo>(TFrom[] a r r a y ,
Converter<TOutput, TTo>
converter)

public static void


Copy(Array s o u r c e A r r a y ,
Array d e s t i n a t i o n A r r a y ,

int

length)

public static void


Copy(Array s o u r c e A r r a y ,
Array d e s t i n a t i o n A r r a y ,
length)

public static void


Copy(Array s o u r c e A r r a y ,
int s o u r c e l n d e x , Array
d e s t i n a t i o n A r r a y , int
d e s t i n a t i o n l n d e x , int
length)

long

7 53

______________ . 21.12

d e s t i n a t i o n l n d e x .
,
ConstrainedCopy ()
",
.
,
d e s t i n a t i o n A r r a y
a r r a y Tlnput
T O u t p u t
. .
,
c o n v e r t e r
,
length, s o u r c e A r r a y
d e s t i n a t i o n A r r a y ,
.
, ()
",
.
,
d e s t i n a t i o n A r r a y

,
l e n g t h , s o u r c e A r r a y
d e s t i n a t i o n A r r a y ,
.
, ()
,
.
,
d e s t i n a t i o n A r r a y

,
l e n g t h , s o u r c e A r r a y ,
,
s o u r c e A r r a y [ s o u r c e l n d e x ] ,
d e s t i n a t i o n A r r a y , ,
d e s t i n a t i o n A r r a y [ d e s t i
n a t i o n l n d e x ] .
, ()
,
.
,
d e s t i n a t i o n A r r a y
_________________

754

II. C#
. 21.12

public static void


C op y(Array s o u r c e A r r a y ,
long s o u r c e l n d e x , Array
d e s t i n a t i o n A r r a y , long
d e s t i n a t i o n l n d e x , long
length)

public voi d Co pyTo(Array


a r r a y , int i n d e x )

public v oi d CopyTo(Array
a r r a y , long i n d e x )

public static Array


C re at elnstance(Type
e l e m e n t T y p e , int l e n g t h )
public static Array
C re at elnstance(Type
e l e m e n t T y p e , int l e n g t h l ,
int l e n g t h 2 )
public static Array
Cr ea te lnstance(Type
e l e m e n t T y p e , int l e n g t h l ,
int l e n g t h 2 , int l e n g t h 3 )
public static Array
Cr ea te lnstance(Type
e l e m e n t T y p e , params i n t []

,
l e n g t h , s o u r c e A r r a y ,
,
s o u r c e A r r a y [ s o u r c e I n d e x ] ,
d e s t i n a t i o n A r r a y , ,
d e s t i n a t i o n A r r a y [ d e s t i
n a t i o n l n d e x ] .
, ()
,
.
,
destinationArray


a r r a y , ,
a r r a y [ i n d e x ] .
,
array


a r r a y , ,
a r r a y [ i n d e x ] .
,
array

,
e l e m e n t T y p e ,
l e n g t h

l e n g t h l * l e n g t h 2 .
e l e m e n t T y p e
^
l e n g t h l * l e n g t h 2 * l e n g t h 3 .
e l e m e n t T y p e
,
l e n g t h s .

lengths)

elem entType

public static Array


Cr ea te lnstance(Type
e l e m e n t T y p e , params long[]

,
l e n g t h s .

lengths)

e l e m e n t T y p e ______________________________

21. System

public static Array


Createlnstance(Type
elem entType, int[ ] le n g th s ,
i n t [] l o w e r B o u n d s )

public static bool


E x i s t s < T > ( T [] a r r a y ,
Predicate<T> m a t c h )

public static T Find<T>(T[]


a r r a y , Predicate<T> m a t c h )

public static T[]


F i n d A l l < T > ( T [] a r r a y ,
Predicate<T> m a t c h )
public static int
F in d I n d e x < T > ( T [] a r r a y ,
Predicate<T> m a t c h )
public static int
F i n d I n d e x < T > ( T []a r r a y , int
s t a r t l n d e x , Predicate<T>
match)

public static int


F in d I n d e x < T > ( T [] a r r a y ,
int s t a r t l n d e x , int c o u n t ,
Predicate<T> m a t c h )

public static T
F i n d L a s t < T > ( T [] a r r a y ,
Predicate<T> m a t c h )

755

______________ . 21.12

,
l e n g t h s .

e l e m e n t T y p e .
l o w e r B o u n d s .
, ,
,

true,
a r r a y ,
,
m a t c h ,
false
a r r a y ,
,
m a t c h ,
default ()
a r r a y ,
,
m a t c h ,


a r r a y , ,
m a t c h ,
-1

a r r a y ,
, m a t c h .
,
a r r a y [s t a r t I n d e x ] .
, ,
, -1

a r r a y ,
, m a t c h .
,
a r r a y [ s t a r t l n d e x ] ,
, c o u n t .
,
, , -1
array,
,
m a t c h ,
default ()

756

II. C#
. 21.12

public static int


F i n d L a s t I n d e x < T > ([] a r r a y ,
.Predicate<T> m a t c h )
public static int
F i n d L a s t I n d e x < T > ( T [] a r r a y ,
int s t a r t l n d e x , Predicate<T>
match)

public static int


F i n d L a s t I n d e x < T > ( T [] a r r a y ,
int s t a r t l n d e x , int c o u n t ,
Predicate<T> m a t c h )

public static void


F o r E a c h < T > ( T []a r r a y ,
Action <T > a c t i o n )
public IEnumerator
G e t E n u m e r a t o r ()

public override int


G e t H a s h C o d e ()
public int GetLength(int
dimension)

public long GetLongLength(int


dimension)

public int GetLowerBound(int


dimension)


array, ,
match,
-1

a r r a y , ,
m a t c h .
,
a r r a y [ s t a r t l n d e x ] ,
a r r a y [0] . ,
, ,
-1

a r r a y , ,
v.
,
a r r a y [ s t a r t ] ,
, c o u n t .
,
, , -1
,
a c t i o n , a r r a y

.
.
25
-
.
,

0
d i m e n s i o n ,
1 ..

long.
,

0 d i m e n s i o n ,
1 ..

, . d i m e n s i o n

21. System

public int GetUpperBound(int


dimension)

public object GetValue(int


index)

public object GetValue(long


index)

public object GetValue(int


i n d e x l , int i n d e x 2 )
public object GetValue(long
i n d e x l , long i n d e x 2 )
public object GetValue(int
i n d e x l , int i n d e x 2 , int
index3)

public object GetValue(long


i n d e x l , long i n d e x 2 , long
idx3)

public object G e t V a l u e ( i n t []
indices)

public object
G e t V a l u e ( l o n g [] i n d i c e s )

public static int


IndexOf(Array a r r a y ,
value)

object

757

______________ . 21.12

,

0 d i m e n s i o n ,

1 ..

. d i m e n s i o n
,

0
d i m e n s i o n ,
1 ..

i n d e x .


i n d e x .


[ i n d e x l , i n d e x 2 ] .


[ i n d e x l , i n d e x 2 ] .


[ i n d e x l , i n d e x 2 ,
i n d e x 3 ] .

[ i n d e x l , i n d e x 2 ,
i n d e x 3 ] .

.

i n d i c e s

.

i n d i c e s
,
v a l u e a r r a y .
,
-1. (
,
, 1.)

758

II. C#
. 21.12

public static int


I n d e x O f < T > ( T [] a r r a y ,

value)

public static int


IndexOf(Array a r r a y , object
v a l u e , int s t a r t l n d e x )

public static int


I n d e x O f < T > ( T [] a r r a y , T
v a l u e , int s t a r t l n d e x )

public static int


IndexOf(Array a r r a y , object
v a l u e , int s t a r t l n d e x , int
count)

public static int


I n d e x O f < T > ( T [] array, T
v a l u e , int s t a r t l n d e x , int
count)

public v o i d 4-Initialize ()

public static int


Lastlnd ex Of (A rr ay a r r a y ,
object v a l u e )

,
v a l u e a r r a y .
,
-1
,
va lu e a r r a y .
,
a r r a y [ s t a r t I n d e x ] .
-1, . (
,

, 1.)
,
v a l u e a r r a y .
,
a r r a y [ s t a r t l n d e x ] .
-1,
,
v a l u e a r r a y .
,
a r r a y [ s t a r t l n d e x ] ,
,
c o u n t . -1,
. (
,

, 1.)
,
v a l u e a r r a y .
,
a r r a y [ s t a r t I n d e x ] ,
,
c o u n t . -1,


,
.


,
v a l u e a r r a y .
,
-1. (
,
, 1.)

21. System

public static int


LastIndexOf-<T> (T []a r r a y ,

value)

public static int


LastlndexOf(Array a r r a y ,
object v a l u e , int s t a r t l n d e x )

public static int


L a s t I n d e x O f < T > ( T [] a r r a y ,
v a l u e , int s t a r t l n d e x )

public static int


LastlndexOf(Array a r r a y ,
object v a l u e , int s t a r t l n d e x ,
int c o u n t )

public static int


L as t l n d e x O f < T > ( T []a r r a y , T
v a l u e , int s t a r t l n d e x , int
count)

public static void


Resize<T>(ref T[] a r r a y ,

7 59

______________ . 21.12

,
v a l u e
a r r a y . ,
-1
,
v a l u e a r r a y .
,
a r r a y [ s t a r t l n d e x ],
a [0].
-1, . (
,

, 1.)
,
value a r r a y .

, a [ s t a r t I n d e x ] ,
[ 0].
-1,
,
v a l u e array.
,
a r r a y [ s t a r t I n d e x ],
,
c o u n t . -1,

. (
,
, 1.)
,
v a l u e a r r a y .
,
a r r a y [ s t a r t I n d e x ] ,
,
count. -1,

n e w S i z e a r r a y

int

newSize)

public static void


Reverse(Array a r r a y )
public static void
Reverse(Array a r r a y ,
i n d e x , int l e n g t h )

int


a r r a y

a r r a y ,
,
a r r a y [ i n d e x ] , ,
l e n g t h ____________

760

II. C#
. 21.12

public void SetValue(object


v a l u e , int i n d e x )
public void SetValue(object
v a l u e , long i n d e x )
public void SetValue(object
v a l u e , int i n d e x l , int i n d e x 2 )
public void SetValue(object
v a l u e , long i n d e x l , long i n d e x 2 )
public void SetValue(object
v a l u e , int i n d e x l , int
4
i n d e x 2 , int i n d e x 3 )
public void SetValue(object
v a l u e , long i n d e x l , long
i n d e x 2 , long i n d e x 3 )
public void SetValue(object
v a l u e , i n t [] i n d i c e s )

public voi d SetValue(object


v a l u e , l o n g []indices)

public static void


Sort(Array a r r a y )
public static void
S o r t < T > ( T []a r r a y )
public static voi d
Sort(Array a r r a y , IComparer
comparer)

public static void


S o r t < T > ( T [] a r r a y ,
Comparison<T> c o m p a r e r )
public static voi d
S o r t < T > ( T [] a r r a y ,
IComparer<T> c o m p a r e r )
public static voi d
Sort(Array k e y s , Array
i terns)

value
i n d e x .

value
i n d e x .

v a l u e
[ i n d e x l ,
i n d e x 2 ] .
v a l u e
[ i n d e x l ,
i n d e x 2 ] .
v a l u e
[ i n d e x l , i n d e x 2 ,
i n d e x 3 ].
value
[ i n d e x l , i n d e x 2 ,
i n d e x 3 ] .
v a l u e
.

i n d i c e s
v a l u e
.

i n d i c e s
a r r a y .

a r r a y .

a r r a y ,
,
c o m p a r e r .
a r r a y ,
,
c o m p a r e r .
a r r a y ,
,
c o m p a r e r .

. k e y s
, i t e m s ,
. ,
-.

__________________

21. System

public static void


Sort<TKey, T V a l u e > ( T K e y []
k e y s , T V [] i t e m s )

public static void


Sort(Array k e y s , Array
i t e m s , Icomparer c o m p a r e r )

public static void


SortCTKey* T V a l u e > ( T K e y []
k e y s , TValue[] i t e m s ,
IComparer<TKey> c o m p a r e r )

public static void


Sort(Array a r r a y , int i n d e x ,
int l e n g t h )

public static void


Sort<T>(T[] a r r a y , int
i n d e x , int l e n g t h )

public static void Sort(Array


a r r a y , int i n d e x , int l e n g t h ,
IComparer c o m p a r e r )

public static void


S o r t < T > ( T [] a r r a y , int
i n d e x , int l e n g t h ,
Icomparer<T> c o m p a r e r )

761

_____________ . 21.12


. k e y s
, i t e m s ,
. ,
-.



, , -,
c o m p a r e r . k e y s
, i terns ,
. ,
-.



, ,
c o m p a r e r . k e y s
, i t erns ,
. ,
-.


a r r a y
, ,
a r r a y [ i n d e x ] ,
, l e n g t h .

a r r a y
, ,
a r r a y [ i n d e x ] ,
, l e n g t h .

a r r a y
, ,
a r r a y [ i n d e x ] ,
, l e n g t h ,
,
v.
a r r a y
, ,
a r r a y [i n d e x ] ,
, l e n g t h ,
, comparer.

762

II. C#
. 21.12

public static void


Sort(Array k e y s , Array
i t e m s , int i n d e x , int
length)

public static void


Sort<TKey, T V a l u e > ( T K e y []
k e y s , TValue[] i t e m s , int
i n d e x , int l e n g t h )

public static void


Sort(Array k e y s , Array
i t e m s , int i n d e x , int
l e n g t h , IComparer c o m p a r e r )

public static voi d


Sort<TKey, T V a l u e > ( T K e y []
k e y s , TV i t e m s , int i n d e x ,
int l e n g t h , Icomparer<TKey>
comparer)


. , ,
i n d e x ,
, l e n g t h .
k e y s ,
i t erns ,
. ,
-".



, ,
i n d e x ,
, l e n g t h .
k e y s ,
i t erns ,
. ,
-".



, ,
i n d e x ,
, l e n g t h ,
,
c o m p a r e r . k e y s
, i t e m s ,
. ,
".



, ,
i n d e x ,
, l e n g t h ,
,
c o m p a r e r . k e y s
,, i t e m s ,
. ,
. ".
____________________

21. System

763

. 21.12

public static bool


TrueForAll<T> ( [ ] a r r a y ,
Predicate<T> m a t c h )

true,
a r r a y
, m a t c h .

,
false


.
A r r a y . ,
Sort ()

,
" -".
, B i n a r yS ea rc h ().
, S o r t ()
BinarySearch () int.
// .
using System;
class SortDemo {
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 6 3 14 9 8 17 1 2 4 - 1 0
: - 1 0 1 3 4 5 6 8 9 1 4 1 7 2 4
14: 9

764

II. C#

int,
. , Array,
C# .
.
,
IComparable IComparable<T>.
,

. , ,
IComparable IComparable<T>, .
IComparable .
int CompareTo(object ob j)

,
o b j . ,
o b j , ;
, , o b j ,
.
I C o m p a r a b l e < T >
IComparable.
C o m p a r e T o ().
int CompareTo( o th er)

CompareTo ()
.
, o t h e r .
, o t h e r , ;
, ,
o t h e r , . IComparable<T>
, ' ,
, ,
object .
,
.
// ,
using System;
class MyClass : IComparable<MyClass> {
public int i;
public MyClass(int x)

{ i = x; }

// IComparable<MyClass>.
public int CompareTo(MyClass v) {
return i - v.i;

}
public bool Equals(MyClass v)
return i == v.i;

21. System

765

class SortDemo {
static void Main() {
MyClass[] nums = new MyClass[5];
nums[0]
nums[l]
nums[2]
nums[3]
nums[4]

=
=
=
=
=

new
new
new
new
new

MyClass(5);
MyClass(2);
MyClass(3);
MyClass(4);
MyClass(1);

// .
Console.Write(" : ");
foreach(MyClass in nums)
Console.Write(.i + " ");
Console.WriteLine ();
// .
Array.Sort(nums);
// .
Console.Write(" : ");
foreach(MyClass in nums)
Console.Write(.i + " ");
Console.WriteLine ();
// MyClass (2).
MyClass x = new MyClass (2);
int idx = Array.BinarySearch(nums, x);
Console.WriteLine(" MyClass(2): " +
idx) ;

}
}

.
: 5 2 3 4 1
: 1 2 3 4 5
MyClass(2): 1


. ,
,
, , ,
. ,
,
.
StringComparer IComparer,
Sort () BinarySearch ().

22.

766

II. C#

S t r i n g C o m p a r e r S y s t e m ,
, IComparer I Comparer <>.
S t r i n g C o m p a r e r
IComparer. , S tr in gC om pa re r
, StringComparer
.
.

public static StringComparer


C urrentCulture {get; }
public static StringComparer
CurrentCul tu re lg no re Ca se {get;

public static StringComparer


InvariantCulture {get; }
public static StringComparer
I nv ar iantCulturelgnoreCase {get;

public static StringComparer Ordinal


{get; }
public static StringComparer
O rd inallgnoreCase {get; }


_____________________________

StringComparer,
.
,
S t r i n g C o m p a r e r .Ordinal.
string[] strs = { "xyz",

//

"one" , "beta", "Alpha" };

...

Array.Sort(strs, StringComparer.Ordinal);
int idx = Array.BinarySearch(strs, "beta", StringComparer.Ordinal) ;


, ,
, .
R ev er se ().
.
.
// .
using System;
class ReverseDemo {
static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
// .
Console.Write(" : ");

21. System

767

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

");

}
}
.
: 1 2 3 4 5
: 5 4 3 2 1
: 5 2 3 4 1



.
().
.
() .
// .

using System;
class CopyDemo {
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 ();

768

II. C#
// .
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();
// .
Array.Copy(source2, 2, target, 3, 2);
// .
Console.Write(" : ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();

}
}
.
: 1 2 3 4 5
: 11 12 13 14 15
: 1 2 3 4 5
: 1 2 3 - 3 - 4


System. Predicate,
true false .
.
public delegate bool Predicate<T>

(T ob j)

, ,
o b j . o b j ,
true, false.
Array, : Exists ( ) , Find ( ) ,
F i n d l n d e x () F i n d A l l ().

,
. ,
, .
E x i s t s () F i n d ().
// .
using System;

21. System

769

class PredDemo {
// , true,
// v ,
static bool IsNeg(int v) {
if (v < 0) return true;
return false;

}
static void Main() {
int[] nums = { 1, 4, -1, 5, -9 };
Console.Write(" nums: ");
foreach(int i in nums)
Console.Write (i + " ");
Console.WriteLine();
// , nums ,
if(Array.Exists(nums, PredDemo.IsNeg)) {
Console.WriteLine(" nums .");
// " ,
int = Array.Find(nums, PredDemo.IsNeg);
Console.WriteLine(" : " + x);

}
else
Console.WriteLine(" nums .");

}
}
.
nums: 1 4 - 1 5 - 9
nums .
: -1

E x i s t s () F i n d ()
I s N e g ( ) .
Is N e g ().
static bool IsNeg (int v)

E x i s t s () F i n d ()
v. , IsNeg ()
v .

A c t i o n
A c t i o n A r r a y . F o r E a c h ()
. A c t i o n ,
. .
public delegate void Action<T>

(T ob j)

, ,
o b j . A c t i o n
A r r a y . F o r E a c h ( ), o b j .

770

II. C#

, A c t i o n F o r E a c h ( ) ,
.

A c t i o n F o r E a c h ( ) . M y C la s s ,
S how () ,
. N e g ().
, Show ()
. F o r E a c h ( ) .
// Action.
using System;
'class MyClass {
public int i;
public MyClass(int x) { i = x; }

}
class ActionDemo {
// Action, , ,
static void Show(MyClass ) {
Console.Write(.i + " ");

}
// Action,
// , .
static void Neg(MyClass ) {
o.i = -o.i;

}
static void Main() {
MyClass[] nums = new MyClass[5];
nums[0]
nums[l]
nums[2]
nums[3]
nums[4]

=
=
=
=
=

new
new
new
new
new

MyClass(5);
MyClass(2);
MyClass(3);
MyClass(4);
MyClass(1);

Console.Write(" nums: ");


// .
Array.ForEach(nums, ActionDemo.Show);
Console.WriteLine();
// .
Array.ForEach(nums, ActionDemo.Neg);
Console.Write(" nums : ");
// .
Array.ForEach(nums, ActionDemo.Show);
Console.WriteLine ();

21. System

771

.
nums: 5 2 3 4 1
nums : -5 -2 -3 -4 -1

B it C o n v e r t e r

. ,
, , .
,
,
. .NET
B i t C o n v e r t e r .
B i t C o n v e r t e r . ,
. 21.13. , .
public static readonly bool IsLittleEndian

t r u e ,
, .
.
, , I s L i t t l e E n d i a n
f a l s e . .
Intel Pentium .

21.13. , B itC o n v e rte r

p u b lic s t a t i c lo n g
v a l u e
D o u b l e T o I n t 6 4 B i t s ( d o u b le l o n g
v alu e)
p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s (b o o l valu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s (c h a r v alu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e t B y t e s ( d o u b le v a l u e )

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s ( f l o a t v alu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s ( i n t v alu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s (lo n g v alu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s ( s h o r t v alu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e tB y te s ( u in t valu e)

p u b lic s t a t i c b y te [ ]
v a l u e
G e t B y t e s ( u l o n g v a l u e ) _____ ____________________________

772

II. C#
. 21.13

public static b y t e []
GetBytes(ushort v a l u e )
public static double
I nt 64BitsToDouble(long

v a l u e

v a l u e double

v alu e)
public static bool
T o B o o l e a n ( b y t e [] v a l u e ,
int s t a r t l n d e x )

public static char


T o C h a r ( b y t e [] v a l u e ,

int

in d ex )
public static double
T o D o u b l e ( b y t e [] v a l u e ,
int s t a r t l n d e x )
public static short
T o l n t l 6 ( byte[] v a l u e ,
int s t a r t l n d e x )
public static int
T o I n t 3 2 ( b y t e [] v a l u e ,
int s t a r t l n d e x )
public static long
T o I n t 6 4 ( b y t e [] v a l u e ,
int s t a r t l n d e x )
public static float
T o S i n g l e ( b y t e [] v a l u e ,
int s t a r t l n d e x )
public static string
T o S t r i n g ( b y t e [] v a l u e )
public static string
T o S t r i n g ( b y t e [] v a l u e ,
int s t a r t l n d e x )
public static string
T o S t r i n g ( b y t e [] v a l u e ,
int s t a r t l n d e x , int

len g th )
public static ushort
T o U I n t l 6 (b yt e[] v a l u e ,
int s t a r t l n d e x )
public static uint
T o U I n t 3 2 ( b y t e [] v a l u e ,
int s t a r t l n d e x )

,
v a l u e [ s t a r t l n d e x ] ,
bool .
true,
false
,
v a l u e [ i n d e x ] , char

,
v a l u e [ s t a r t l n d e x ] ,
double
,
v a l u e [ s t a r t l n d e x ] ,
short
,
v a l u e [ s t a r t l n d e x ] ,
int
,
v a l u e [ s t a r t l n d e x ] ,
long
,
v a l u e [ s t a r t l n d e x ] ,
float
v a l u e
. ,

v a l u e
, v a l u e [ s t a r t i n d e x ] .
,

v a l u e
, v a l u e [s t a r t l n d e x ]
,
l e n g t h . ,

,
v a l u e [ s t a r t l n d e x ] ,
ushort
,
v a l u e [ s t a r t l n d e x ] ,
uint ______________________

21. System

773

. 21.13

public static ulong


T o U I n t 6 4 ( b y t e [] v a l u e ,
int s t a r t l n d e x )

,
v a l u e [ s t a r t l n d e x ] ,
ulong

Random
Random.
,
.
,
.
Random .
public Random()
public Random(int seed)

Random,
.
seed, .
, Random, . 21.14.

21.14. , Random

public virtual int Next()

,
0 Int32 .
M a x V a l u e - 1
,
0 m a x V a l u e - 1

,
m i n V a l u e
m a x V a l u e - 1
b u f f e r
.
0 Byte . M a x V a l u e - 1


,
, 0,0 1,0

,
, 0,0 1,0.

public virtual int Next(int


maxValue)

public virtual int Next(int


m i n V a l u e , int m a x V a l u e )
public virtual void
N e x t B y t e s ( b y t e [] b u f f e r )

public virtual double


N e x t D o u b l e ()
protected virtual double
S a m p l e ()

774

II. C#

, Random
.
// /
.
using System;
class RandDice {
static void Main() {
Random ran = new Random();
Console.Write(ran.Next(1, 7) + " ");
Console.WriteLine(ran.Next(1, 7));

}
}
,
, .
5 2
4 4
1 6

Random.
1 6 .

GC
GC " ". ,
, . 21.15.

21.15. , GC

public static
v oi dA dd Me mo ry Pr es su re (l ong

b y t e s A l l o c a t e d
,

b y tesA llo ca ted )


public static void
CancelFullGC No ti fi ca tio n ()
public static v oi d Collect ()
public static void Collect(int

g en era tio n )



0
g en era tio n

public static void Collect (int


g e n e r a t i o n , GCCollectionMode

mode)
public static int
C ol lectionCount (int g e n e r a t i o n )
public static int
GetGeneration (object o b j )


0
g e n e r a t i o n ',
mode

,
g e n e r a t i o n

, o b j ____________

21. System

public static int


GetGeneration(WeakReference wo)

public static long


GetTotalMemory(bool
forceF ullC ollection )

public static void


KeepAlive(object o b j )

77 5

______________ . 21.15


, " ,
wo. "

( ),
.
f o r c e F u l l C o l l e c t i o n
true,

obj,
.

K e e p A l i v e ()

public static void Regist


erForFullGCNotification(in
t m a x G e n e r a t i o n T h r e s h o l d , int
largeObj ectHeapThreshold)

public static void


RemoveMemoryPressure(long
bytesA llocated)

public static void


ReRegisterForFinalize(object

.
m a x G e n e r a t i o n T h r e s h o l d

",
.
l a r g e O b j e c t H e a p T h r e s h o l d
",
.
1 99
b y t e s A l l o c a t e d
,

o b j .

obj)

S u p p r e s s F i n a l i z e ()

public static void


SuppressFinalize(object o b j )

public static
GCNotificationStatus
W a i t F o r F u l l G C A p p r o a c h ()

,
".
G C N o t i f i c a t i o n S t a t u s ,
System
,
",
,
m i l l i s e c o n d s T i m e o u t .
G C N o t i f i c a t i o n S t a t u s ,
System

".
G C N o t i f i c a t i o n S t a t u s ,
System

public static
GCNotificationStatus
WaitForFullGCApproach(int
m illisecondsTim eout)

public static
GCNotificationStatus
WaitForFullGCComplete ()

obj

776

II. C#
. 21.15

public static
GCNotificationStatus
WaitForFu ll GC Co mp le te (i nt
mi 1 1 i s e c o n d s T i m e o u t )


" ,
m i l l i s e c o n d s T i m e o u t .
G C N o t i f i c a t i o n S t a t u s
,
System

public static void


W a i t F o r P e n d i n g F i n a l i z e r s ()


, ______

, GC
:
public static int MaxGeneration { get;

M ax G e n e r a t i o n ,
. .
, .
" ".
GC .
. ,
" " C o ll ec t ()
. , " " ,
. ,
, ,
. , " "
.
" ".

GC: Ad dM em oryPressure () RemoveMemoryPressure ().
,
. ,
.
,
,
.
A d d M e m o r y P r e s s u r e (), CLR
.
RemoveMemo ry Pr es su re (), CLR
. , ,
, RemoveMem ory Pr es su re ()
,
AddMem or yP re ssu re ( ) .

21. System

777

o b je c t
o b j e c t C# object. O b j e c t
11, #,
. 21.16. o b j e c t

public Object()

21.16. , O b je c t

public virtual bool


Equals(object o b j )

true,
,
, o b j .
false
true,
o b j ,
o b j B .
false

. C# F i na li ze ()

-,

.
, ,

true,
o b j o b j B
.
false
,

public static bool Equals(object


o b j A, object o b j B )

protected F i n a l i z e ()

public virtual
G e t H a s h C o d e ()

int

public Type G e t T y p e ()
protected object
M e m b e r w i s e C l o n e ()
public static bool
ReferenceEquals(object o b j A ,
object o b j B )
public virtual string
T o S t r i n g ()_____________________

T u p le
.NET Framework 4.0
( ). Tuple,
C re a te ()
, T u p le < . . . >,
.
C re a te (), .

778

II. C#

public static Tuple<Tl, T2, T3>


Create<Tl, 2, 3> (Tl i t e m l , 2 ite m 2 , item 3)

, Tuple<Tl, 2, 3>,
i t e m l , i t e m 2 i t e m 3 . ,
,
. , ,
.

IC o m p a ra b le IC om parable< T>
IC o m p a ra b le
IComparable<T>, ,
, .NET Framework. IComparable
IComparable<T> 18,
,
. , A rray
.
, .
ICom parable ,
.
int CompareTo(object ob j)

,
o b j . ,
ob j, ;
, , obj,
.
IC om p arab le
.
public interface IComparable<T>


. CompareTo ()
, .
int CompareTo( oth er)

, CompareTo (),
. , IComparable<T>
.
#, IComparable.

IE q u a ta b le < T >
IE q u atab le< T > ,
.
, Eq u als (), .

21. System

779

bool Equals( oth er)

true,
o t h e r ,
false.
IEquatable<T>
.NET Framework, String.
I E q u a t a b l e < T >
Equals (Object) GetHashCode (), Object.

I C o n v e r t ib le
IConvertible , String
DateTime. .
, , .

IC lo n e a b le
ICloneable,
. ICloneable , Clone (),
.
object Clone()

,
. ,
: . ,
. ,
, .
,
, . ,
, ,
,
, . , Clone ()
.
MemberwiseClone (), Obj ect.
,
ICloneable. Test,
X. Test Clone () .
// ICloneable.
using System;
class X {
public int a;
public X(int x) { a = x; }

}
class Test : ICloneable {

780

II. C#

public X ;
public int b;
public Test (int x, int y) {
= new X (x );
b = y;

}
public void Show(string name) {
Console.Write(" " + name + ": ");
Console.WriteLine(".a: {0}, b: {1}", o.a, b);

}
// ,
public object Clone() {
Test temp = new Test(o.a, b) ;
return temp;

}
}
class CloneDemo {
static void Main() {
Test obi = new Test(10, 20);
obi.Show("obi");
Console.WriteLine(" ob2 obi.");
Test ob2 = (Test) obi.Clone ();
ob2.Show("ob2");
Console.WriteLine(" obi.. 99, " +
" obl.b 88.");
obi..a = 99;
obl.b = 88;
obi.Show("obi");
ob2.Show("ob2");

}
}
, .
: .: 10, : 20
2 .
2: .: 10, : 20
obi.. 99, obl.b 88.
: .: 99, : 88
2: .: 10, : 20

, 2
, .
.
Test, X .
X ,
X .

21. System

781

M e m b e r w i s e C l o n e (),
Object Clone ().
Clone () .
// ,
public object Clone () {
Test temp = (Test) MemberwiseClone();
return temp;

}

.
: .: 10, : 20
2 .
2: .: 10, : 20
. . 99, . 88.
: .: 99, : 88
2: .: 99, : 20

, obi 2
X.
. b int ,
.

I Forma t P r o v i d e r I F o rm a t t a b le
IForma tProvider Get Format (),
,
. Get Format ():
object GetFormat(Type form atType)

f o r m a t T y p e , .
I Format table
. :
string ToString(string form at,

IFormatProvider form a tP rovid er)

f o r m a t , a f o r m a t P r o v i d e r
.

22.

IO b s e rv a b le < T > IO b s e rv e r< T >


.NET Framework 4.0 ,
: I O b s e r v a b l e < T > IObserver<T>.
( ) (

782

II. C#

).
. Subscribe (),
IObservable<T>
IObserver<T>, .
.
,
IObserver<T>. , OnNext () ,
OnError () , OnCompleted () ,
.

_________________


String,
C# string.
,
.
S t r i n g
, ,

.
.
,
C# ,
, .

#
7,
.
#,
String.

,
.
, C++,
, C#
string.
, s t r i n g . ,
string .NET
System. String. , C#
, , ,
String.

784

II. C#


. C#
. ,
.
, ,
, "" , .

" '7, ''77
. , , , ,
, , .
.
, , C#
StringBuilder, System. Text.
string, StringBuilder.

S t r in g
String System.
: IComparable, IComparable<string>, ICloneable, IConvertible,
IEnumerable, IEnumerable<char> IEquatable<string>. , String
, , . String

#. C# string
.NET Framework.
String.

S t r in g
S t r i n g ,
.
.
public String(char[ ] value)
public String(char[ ] v a lu e , int s t a r t l n d e x ,

int len g th )

,
v a l u e . v a l u e
( l e n g t h ) , ,
sta rtln d ex .
,
, , :
public String(char ,

int count)

; a c o u n t .
, ,
.
public String(char* value)
public String(char* v a lu e , int s t a r t l n d e x ,

int len g th )

22.

785

,
v a l u e . , ,
v a l u e , , .
,
v a l u e , ( l e n g t h ) , ,
s t a r t l n d e x . ,
.
, ,
.
public String(sbyte* value)
public String(sbyte* v a lu e , int s t a r t l n d e x ,
public String(sbyte* v a lu e, int s t a r t l n d e x ,

int len g th )
int le n g th , Encoding enc)


, v a l u e . ,
, v a l u e , .
, v a l u e ,
( l e n g t h ) , ,
s t a r t l n d e x .
. Encodi ng
System. Text. ,
.
.

, .
string str = " ";

, S t r in g
String .
public static readonly string Empty

Empty , .. ,
. String,
.
, String ,
.
public char this[int in d e x ] { get;

.
, , . String
, , String
, .
, String ,
.
public int Length { get;

Length .

786

II. C#

S t r in g
String : == ! =. ==
* . ==
, ,
. == String,
.
! =. String,
. ,
< >=, String ,
. ,
, Compare (), String.
,
. = = ! =.
. ( ,
,
, .. .) ,
.


,
. -
, :
.NET Framework . -,
,
, .
, . -,

, . ,

( ), , ,
.
.


,
, Microsoft.

, , , .

. ,
,
(, ,
). ,
,

22.

787

, , , - ,
, . ,

.
String ,
. 22.1. C om pa re ().
,
, , StringComparison,
,
Culture Info. Compare (),
StringComparison,
. ,
Culture Inf ,
. , ,
Cult ur el nf ,
StringComparison.

22.1.

public static int


Compare(string s t r A ,
string s t r B )

s t r A s t r B .
, s t r A s t r B ;
, s t r A
s t r B ; , s t r A s t r B .

s t r A s t r B .
, s t r A s t r B ;
, s t r A
s t r B ; , s t r A s t r B .
i g n o r e C a s e true,

.
.
s t r A s t r B .
, s t r A s t r B ;
, s t r A strB-, ,
strA s t r B . c o m p a r i s o n T y p e

s t r A s t r B ,
, c u l t u r e .
, s t r A
s t r B ; , s t r A
s t r B ; , s t r A s t r B .
i g n o r e C a s e
true,
.
. Culturelnfo System.Globalization________________

public static int


Compare(string s t r A ,
string s t r B , bool
ignoreC ase)

public static int


Compare(string
s t r A , string s t r B ,
StringComparison
comparisonType)

public static i n t .
Compare(string
s t r A , string s t r B ,
bool i g n o r e C a s e ,
Culturelnfo c u l t u r e )

788

II. C#
. 22.1

public static int


Compar e( st ri ng s t r A ,
int i n d e x A , string
s t r B , int i n d e x B ,
int l e n g t h )

public static int


Compare (s tr in g s t r A ,
int i n d e x A , string
s t r B , int i n d e x B ,
int l e n g t h , bool
ignoreCase)

public static int


Co mp ar e(string
s t r A , int i n d e x A ,
string s t r B , int
i n d e x B , int l e n g t h ,
StringComparison
comparisonType)

public static int


C om pa re(string
s t r A , int i n d e x A ,
string s t r B , int
i n d e x B , int l e n g t h ,
bool i g n o r e C a s e ,
Culturelnfo c u l t u r e )

s t r A s t r B .
s t r A [ i n d e x A ] s t r B [ i n d e x B ]
,
l e n g t h . ,
s t r A s t r B ]
, s t r A
s t r B ; , s t r A s t r B
.

s t r A s t r B .
s t r [ i n d e x A ] s t r B [ i n d e x B ]
,
l e n g t h . ,
s t r A s t r B ;
, s t r A
s t r B ; , s t r A s t r B
. i g n o r e C a s e
true,
.
.

s t r A s t r B .
s t r A [ i n d e x A ] s t r B [ i n d e x B ]
,
l e n g t h . ,
s t r A s t r B ;
, s t r A
s t r B ; , s t r A s t r B
. c o m p a r i s o n T y p e

s t r A s t r B ,
,
c u l t u r e .
s t r A [ i n d e x A ] s t r B [ i n d e x B ]
, l e n g t h .
, s t r A
s t r B ; ,
s t r A s t r B ; ,
s t r A s t r B .
i g n o r e C a s e true,

.
. Culturelnfo
System.Globalization________________________

22.
______________

public static int


Compare(string
s t r A f string s t r B ,
Culturelnfo c u l t u r e ,
CompareOptions
options)

789

. 22.1

s t r A s t r B ,
,
c u l t u r e , ,
o p t i o n s .
, s t r A s t r B ;
, s t r A s t r B ; ,
s t r A s t r B . C u l t u r e l n f o
C o m p a r e O p t i o n s
System.Globalization

public static int


Compare(string
s t r A , int i n d e x A ,
string s t r B , int
i n d e x B , int l e n g t h ,
Culturelnfo c u l t u r e ,
CompareOptions
options)

public static int


CompareOrdinal(string
s t r A , string s t r B )

public static int


CompareOrdinal(string
s t r A , int i n d e x A ,
string s t r B , int
i n d e x B , int c o u n t )

public int
CompareTo(object
value)

public int
CompareTo(string
strB)

strA s t r B ,
, c u l t u r e ,
,
o p t i o n s .
s t r A [ i n d e x A ] s t r B [ i n d e x B ]
, l e n g t h .
,
s t r A s t r B ; ,
s t r A s t r B ; ,
s t r A s t r B .
Culturelnfo CompareOptions
System.Globalization
s t r A c o s t r B
, .
, s t r A
s t r B ; , s t r A
s t r B ; , s t r A s t r B
s t r A s t r B
, .
s t r [ i n d e x A ] s t r B [ i n d e x B ]
,
c o u n t . ,
s t r A s t r B ;
, s t r A s t r B ; ,
s t r A s t r B

v a l u e . ,
v a l u e ;
,
v a l u e ; ,
s t r B .
,
s t r B ; ,
s t r B ; , ___________________________________

790

II. C#
. 22.1

public override bool


E quals(object o b j )

public bool
Equals(st ri ng v a l u e )

public bool
Equals(s tri ng v a l u e ,
StringComparison

com p arison T y p e)
public static bool
Equal s( st ri ng a ,
string b)
public static bpol
Equals(s tr in g a ,
string b ,
StringComparison

true,
,
o b j .
,

true,
,
v a l u e .
,
true,
,
v a l u e . c o m p a r i s o n

true,
, .
,

true,
, .
c o m p a r i s o n T y p e

co m p a riso n Type)
StringComparison ,
, . 22.2. ,
, .
, S t r i n gC om pa ri so n
Compare () , , Equals ().
.

.
, , StringComparison
, .

22.2. , S tring C om p arison



CurrentCult ur el gn or eC as e

,

invariantCulture

, ..
______________________________ _______________________________________
CurrentCulture

22.

791

. 22.2


, ..

Ordinal

.
,
,
,
OrdinallgnoreCase

,
.
, ,
______________________________ , __________
InvariantCulturelngoreCase

Compare () ,
; ,
; , ,
. Compare () ,
, , ,
Equals () = =. , Compare ()
. ,
,
, .
Equals (),
. ,
,
, = =.
Compare (),
Com pareOrdinal ().
, , CompareTo ()
.
,
.
Compare (),
Equals ( ) , CompareOrdinal (), = = ! =
. ,

.
// .
using System;
class CompareDemo { 1
static void Main() {
string strl = "alpha";
string str2 = "Alpha";

792

II. C#
string str3 = "Beta";
string str4 = "alpha";
string str5 = "alpha, beta";
int result;
//
// .
result = String.Compare(strl, str2, StringComparison.CurrentCulture)
Console.Write(" : ");
if(result < 0)
Console.WriteLine(strl + " " + str2);
else if(result > 0)
Console.WriteLine(strl + " " + str2);
else
Console.WriteLine(strl + " " + str2);
result = String.Compare(strl, str2, StringComparison.Ordinal);
Console.Write(" : ");
if(result < 0)
Console.WriteLine(strl + " " + str2);
else if(result > 0)
Console.WriteLine(strl + " " + str2);
else
Console.WriteLine(strl + " " + str4);
// CompareOrdinal().
result = String.CompareOrdinal(strl, str2);
Console.Write(" CompareOrdinal():\n");
if(result < 0)
Console.WriteLine(strl + " " + str2) ;
else if(result > 0)
Console.WriteLine(strl + " " + str2);
else
Console.WriteLine(strl + " " + str4);
Console.WriteLine();
// = = .
// ,
if(strl == str4) Console.WriteLine(strl + " == " + str4);
// !=.
if(strl != str3) Console.WriteLine(strl + " != " + str3);
if(strl != str2) Console.WriteLine(strl + " != " + str2);
Console.WriteLine();
// ,
// Equals().
if(String.Equals(strl, str2, StringComparison.OrdinallgnoreCase))
Console.WriteLine(" Equals() " +
" OrdinallgnoreCase:\n" +
strl + " " + str2);

22.

793

Console.WriteLine ();
// ,
if (String.Compare(str2, 0, str5, 0, 3,
StringComparison.CurrentCulture) > 0 ) {
Console.WriteLine(" :" +
"\ " + str2 +
" , 3 " + str5);

}
}
}
.
: alpha Alpha
: alpha Alpha
CompareOrdinal():
alpha Alpha
alpha == alpha
alpha != Beta
alpha != Alpha
Equals() OrdinallgnoreCase:
alpha Alpha
:
3 Alpha , 3 alpha, beta

, .. , . -,
+, 7. -,
, String. ,
+,
.
, , C o n c a t ().
.
public static string Concat(string str O ,

string s t r l )

, s t r l ,
s t r O . Concat (),
.
public static string Concat(string str O ,

string s t r l ,string s tr 2 )

Concat () ,
s t r O , s t r l s t r 2.
Concat (), .
public static string Concat(string str O ,

string s t r l , string s t r 2 ,

string s tr 3 )

Concat () ,
.

794

II. C#

neat ()
:
public static string Concat(params string[] va lu es)

v a l u e s ,
. Concat ()
, ?
.
,
.

Concat () .
// Concat().
using System;
class ConcatDemo {
static void Main() {
string result = String.Concat(" ", " ", " ",
" ", " ",
" ", "String." );
Console.WriteLine(": " + result);

}
}
.
: String.

, C o n c a t ( ) ,
, .
C o n c a t () ,
, . (
T o S t r i n g O ,
.) Concat ().
public
public
public
public
public

static
static
static
static
static

string
string
string
string
string

Concat(object
Concat(object
Concat(object
Concat(object
Concat(params

argO)
argO, object a rg l)
argO, object a r g l , object arg2)
argO, object a r g l, object a rg 2 , object arg3)
object[] args)

Concat () , argO,
,
. Concat (), .. obj ect,
,
.
Concat ().
.// Concat()."
using System;
class MyClass {

22.

795

public static int Count = 0;


public MyClass() { Count++;

}
class ConcatDemo {
static void Main() {
string result = String.Concat(" " + 19);
Console.WriteLine(": " + result);
result = String.Concat(" ", 88, " ", 20.0,
" ", false, " ", 23.45M);
Console.WriteLine(": " + result);
MyClass me = new MyClass();
result = String.Concat(me, " ",
MyClass.Count);
Console.WriteLine(": " + result);

}
}
.
: 19
: 88 20 False 23.45
: MyClass 1

Concat ()
.
ToString (), .
, Concat ():
string result = String.Concat(" " + 19);

Int32.ToString()
19, Concat () .

MyClass Concat ().
result = String.Concat(me, " ",
MyClass.Count);

MyClass,
. .
ToString (), MyClass
.
.
public override string ToString() {
return " MyClass";

}

, .
: MyClass 1

796

II. C#

4.0 .NET Framework Concat (),


.
public static string Concat<T>(IEnumerable<T> va lu es)
public static string Concat(IEnumerable<string> va lu es)

,
, ,
v a l u e s ,
IEnumerable<T>. ,
v a l u e s . (, , ,
,
StringBuilder.)


String .
, , , ,
. , , ,
.

IndexOf (). .

.
public int IndexOf(char value)

IndexOf () v a l u e
. v a l u e , j o -1.
.
, . .
IndexOf (),
.
public int IndexOf(String value)
public int IndexOf(String v a lu e, StringComparison comparisonType)

,
v a lu e , .
StringComparison,
. ,
- 1 .

Last IndexOf ().
.
.
public int LastlndexOf(char value)

LastlndexOf () ,
v a l u e
- 1 , .
LastlndexOf (),
.

22.
public int LastlndexOf(string value)
public int LastlndexOf(string v a lu e,

797

StringComparison com parisonType)


, v a l u e ,
.
StringComparison, .
, -1.
S t r i n g :
IndexOf Any () LastlndexOf Any (). ,
.
.
public int IndexOfAny(char[] anyOf)
public int LastlndexOfAny(char[] anyOf)

IndexOf An y ()
a n y O f , , Lastlnd ex Of An y ()
a n y O f ,
. ,
-1. ,
.
,
.
StartsWith () EndsWith (). .
public bool StartsWith(string value)
public bool EndsWith(string value)

S t a r t s W i t h () true,
, v a l u e .
EndsWith () true,
, v a l u e .
false.

. ,

StringComparison.
public bool StartsWith(string v a lu e, StringComparison comparisonType)
public bool EndsWith(string v a lu e, StringComparison comparisonType)

,
.
.

.
// .
using System;
class StringSearchDemo {
static void Main() {

798

II. C#
string str = "C# .";
int idx;
Console.WriteLine(" str: " + str);
idx = str.IndexOf('o');
Console.WriteLine(" 'o': " + idx);
idx = str.LastlndexOf(' ');
Console.WriteLine(" 'o': " + idx);
idx = str.IndexOf("", StringComparison.Ordinal);
Console.WriteLine(" \"\": " + idx);
idx = str.LastlndexOf("", StringComparison.Ordinal);
Console.WriteLine(" \"\": " + idx);
char[] chrs = { 1a ', '6', 1 ' };
idx = str.IndexOfAny(chrs);
Console.WriteLine(" " +
" ' 1, '' '': " + idx);
if(str.StartsWith("C# ", StringComparison.Ordinal))
Console.WriteLine(" str \"C# \"");
if(str.EndsWith(".", StringComparison.Ordinal))
Console.WriteLine(" str \".\"") ;

}
}
.

str: C# .
' ': 3
'': 49
"": 22
"": 33
1 ', ' ' ' ': 4
str "C# "
str "."

C o n ta in s ().
.
public bool Contains(string value)

C o n tain s () tru e ,
, v a l u e ,
f a l s e .
. , ,
.
C on tain s ().
// Contains().
using System;

22.

799

class ContainsDemo {
static void Main() {
string str = "C# .";
if(str.Contains(""))
Console.WriteLine(" \"\".");
if(str.Contains(""))
Console.WriteLine(" \"\".");
i f (!str.Contains(""))
Console.WriteLine(" \"\" .");

}
}
.
"".
"".
"" .

,
Contains ()

, .
"", "".
"", .
,

. . 22.3 ,
String.

22.3. , S t r in g

public bool Contains(string v a l u e )

true,

v a l u e . v a l u e
,
false
* true,

v a l u e .
false
true,

v a l u e .
false.
c o m p a r i s o n T y p e

true,
v a l u e ,

public bool EndsWith(string v a l u e )

public bool EndsWith(string v a l u e ,


StringComparison c o m p a r i s o n T y p e )

public bool EndsWith(string v a l u e ,


bool i g n o r e C a s e , Culturelnfo
culture)

800

II. C#
. 22.3

public int IndexOf(char v a l u e )

public int IndexOf(string v a l u e )

public int IndexOf(char v a l u e ,

int

sta rtln d ex )

public int I n d e x O f (string v a l u e ,


int s t a r t l n d e x )

public int IndexOf(char v a l u e ,


s t a r t l n d e x , int c o u n t)

int

public in.t IndexOf (string v a l u e ,


int s t a r t l n d e x , int c o u n t)

public int I n d e x O f (string v a l u e ,


StringComparison c o m p a r i s o n T y p e )

false.
i g n o r e C a s e
true,

.
.

,
c u l t u r e

v a l u e .
,
-1

v a l u e .
,
-1

v a l u e .
,
s t a r t l n d e x .
-1,


v a l u e .
,
s t a r t l n d e x .
-1,


v a lu e .
,
s t a r t l n d e x ,
,
c o u n t . -1,


v a l u e .
,
s t a r t l n d e x ,
,
c o u n t . -1,


v a l u e .

22.

801

_____________________________________________________________ . 22.3

public int IndexOf(string v a l u e ,


int s t a r t l n d e x , StringComparison
comparison Type)

public int IndexOf(string v a l u e ,


int s t a r t l n d e x , int c o u n t ,
StringComparison c o m p a r i s o n T y p e )

public int LastlndexOf(char v a l u e )

public int IndexOfAny(char[] a n y O f )

public int IndexOfAny(char[] a n y O f ,


int s t a r t l n d e x )

public int IndexOfAny(char[] a n y O f ,


int s t a r t l n d e x , int c o u n t )

c o m p a r i s o n T y p e
.
-1,


v a l u e .
,
s t a r t l n d e x .
c o m p a r i s o n T y p e
.
-1,


v a l u e .
,
s t a r t l n d e x ,
,
c o u n t . c o m p a r i s o n T y p e

. -1,


v a l u e .
,
-1

a n y O f ,
.
-1,

a n y O f .


a n y O f ,
.
,
s t a r t l n d e x
-1,
a n y O f .


a n y O f ,
.
, ^
s t a r t l n d e x ,

802

II. C#

______________________________________________________________ . 22.3

public int LastlndexOf(string v a lu e )

public int L astlndexOf(char v a l u e ,


int s t a r t l n d e x )

public int LastlndexOf(string v a l u e ,


int s t a r t l n d e x )

public int La stlndexOf(char v a l u e ,


int s t a r t l n d e x , int c o u n t )

public int LastlndexOf(string v a l u e ,


int s t a r t l n d e x , int c o u n t )

public int LastlndexOf(string v a l u e ,


St ringComparison c o m p a r i s o n T y p e )

,
c o u n t . -1,

anyOf.


v a l u e .
,
-1

v a l u e .
,
,
s t a r t l n d e x ,
.
-1,

v a l u e
.
, ,
s t a r t l n d e x ,
.
-1,


v a l u e
.
, ,
s t a r t l n d e x ,
,
c o u n t . -1,


v a l u e
.
, ,
s t a r t l n d e x ,
,
c o u n t . -1,


v a l u e .
c o m p a r i s o n T y p e
.
-1, _________

22.

public int LastlndexOf(string v a l u e ,


int s t a r t l n d e x , StringComparison
comparisonType)

public int LastlndexOf(string v a l u e ,


int s t a r t l n d e x , int c o u n t ,
StringComparison c o m p a r i s o n T y p e )

public int L a s t l n d e x O f A n y ( c h a r []
anyOf)

public int L a s t l n d e x O f A n y ( c h a r []
a n y O f , int s t a r t l n d e x )

public int L a s t l n d e x O f A n y ( c h a r []
a n y O f , int s t a r t l n d e x , int c o u n t )

803

______ . 22.3


v a l u e
.
, ,
s t a r t l n d e x ,
.
c o m p a r i s o n T y p e
.
-1,


v a l u e
.
, ,
s t a r t l n d e x ,
,
c o u n t . c o m p a r i s o n T y p e

. -1,


a n y O f ,
.
-1,

a n y O f .


a n y O f ,
.

, s t a r t l n d e x ,

. -1,

a n y O f .


a n y O f ,
.
,
,
s t a r t l n d e x ,
, c o u n t ,
,
c o u n t . -1,

804

II. C#

________________________________________________________________ . 22.3

public bool StartsWith(string v a l u e )

public bool StartsWith(string v a l u e ,


StringComparison c o m p a r i s o n T y p e )

public bool StartsWith(string v a l u e ,


bool i g n o r e C a s e , Culturelnfo
culture)


a n y O f .

true,

v a l u e .
false
true,

v a l u e .
false.
c o m p a r i s o n T y p e

true,

v a l u e .
false.
i g n o r e C a s e
true,

.
.

,
c u l t u r e __________________


.
,
. String
Split (), Join ().
Sp lit ().
, , C# 1.0.
public string[ ] Split(params char[ ] sep a ra to r)
public string[ ] Split(params char[ ] s e p a r a to r , int count)

Sp li t ()
. , ,
. , ,
s e p a r a t o r . s e p a r a t o r ,
. .
, c o u n t .
Join (). ,
, 2.0 .NET Framework.

22.

805

public static string Join(string s e p a r a to r , string[] value)


public static string Join(string se p a r a to r , string[] v a lu e,
int s t a r t l n d e x , int count)

J o i n () ,
, v a l u e .
, , value,
c o u n t , v a l u e [ s t a r t l n d e x ] .

, s e p a r a t o r .

S p l i t () J o i n ().
// .
using System;
class SplitAndJoinDemo {
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);

}
}
.
:

:
| | | | | |

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

806

II. C#

S p l i t (),
StringSplitOptions. ,
. Split ().
public string[] Split(params char[] s e p a r a t o r , StringSplitOptions o p tio n s)
public string[] Split(string[] s e p a r a to r , StringSplitOptions o p tio n s)
public string[] Split(params char[] s e p a r a to r , int co u n t,
StringSplitOptions o p tio n s)
public string[] Split(string[]se p a r a to r , int coun t,
StringSplitOptions o p tio n s)

Split ()
, ,
. , , s e p a r a t o r .
s e p a r a t o r , .
,
co u n t. o p t i o n s
, ,
. StringSplitOptions
: None RemoveEmptyEntries. o p t i o n s
None,
, . o p t i o n s
RemoveEmptyEntries,
.
,

string[] parts = str.Split (seps);

.
string[] parts = str.Split(seps, StringSplitOptions.RemoveEmptyEntries) ;

.
:

:
| | | | |

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

Sp lit () " 100"
, "" "100".
, "" (
), " ".

22.

807

, ,
, 10 + 5, ,
.
// .
using System;
class TokenizeDemo {
static void Main() {
string[] input = {
"100 + 19",
"100 / 3,3",
_3 * 9..r
"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
Console.WriteLine (n
break;
case
Console.WriteLine(n
break;
case "/":
Console.WriteLine(n
break;

+ n2);

- n2);

* n2);

/ n2);

}
}
}
}
.
:
:
:
:

100 +
100 /
-3*9
100 -

19 , : 119
, : 30,3030303030303
, : -27
87 , : 13
3, 3

4.0, .NET Framework


Joi n ().

808

II. C#

public static string Join(string se p a r a to r , params object[] valu es)


public static string Join(string se p a r a to r , IEnumerable<string>[] valu es)
public static string Join<T>(string s e p a r a to r , IEnumerable<T>[] valu es)

,
v a l u e s .
, ,
v a l u e s . ,
, v a l u e s .

, s e p a r a t o r .


.
. ,
"print",

.
. , ,
. ,
,
, .
C# .
T r i m ( ) .
public string Trim()
public string Trim(params char[] trimChars)

T r i m ()
.
t r i m C h a r s .
.
.
P a d L e f t ( ) .
public string PadLeft(int tota lW id th )
public string PadLeft(int to ta lW id th ,

char paddingChar)

P a d L e f t ()
, t o t a l W i d t h .
, p a d d i n g C h a r ,
,
t o t a l W i d t h .
. t o t a l W i d t h ,
.
P a d R ig h t ( ) .
public string PadRight(int tota lW id th )
public string PadRight(int to ta lW id th ,

char paddingChar)

P a d L e f t ()
, t o t a l W i d t h .

22.

809

, p a d d i n g C h a r ,
,
t o t a l W i d t h . B
. t o t a l W i d t h ,
.

.
// .
using System;
class TrimPadDemo {
static void Main() {
string str = "";
Console.WriteLine(" : " + str);
// ,
str = str.PadLeft(10);
Console.WriteLine("I" + str + "I");
// ,
str = str.PadRight(20);
Console.WriteLine("I" + str + "I");
// ,
str = str.Trim();
Console.WriteLine("|" + str + "I");
// # ,
str = str.PadLeft(10, '#');
Console.WriteLine ("|" + str + "I");
// # ,
str = str.PadRight(20, '#');
Console.WriteLine("|" + str + "I");
// #.
str = str.Trim('#');
Console.WriteLine("|" + str + "|");

}
}

.
:
I
|
|

|
||
I######|
|################|
I|

810

II. C#

,
Insert ():
public string Insert(int s t a r t l n d e x ,

string value)

v a l u e ,
s t a r t l n d e x . .
Remove (). .
public string Remove(int s ta r tln d e x )
public string Remove(int s t a r t l n d e x , int count)

Remove () , ,
s t a r t l n d e x , .
,
c o u n t , , s t a r t l n d e x .
.
Replace (). .
public string Replace(char oldChar, char newChar)
public string Replace(string o ld V a lu ef string newValue)

Replace () o l d C h a r
n e w C h a r .
o l d V a l u e n e w V a l u e .
.
Insert (),
R e m o v e () R e p l a c e ().
// , .
using System;
class InsRepRevDemO {
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);

22.

811

.
:

_


String ,
, T o U p p e r () T o L o w e r ().
.
public string ToLower()
public string ToUpper()

T o L o w e r () ,
ToUpper () .
. ,
.
public string ToLower (Culturelnfo c u ltu r e )
public string ToUpper(Culturelnfo c u ltu r e )


.
.
, T o U p p e r I n v a r i a n t ( )
T o L o w e r l n v a r i a n t ().
public string ToUpperlnvariant ()
public string ToLowerlnvariant()

ToUpper () ToLower (), ,



.

S u b s tr in g ()
S u b s t r i n g O .
.
public string Substring(int s ta r tln d e x )
public string Substring(int s t a r t l n d e x , int len g th )

S u b s t r i n g () , ,
s t a r t l n d e x , .
,
, le n g t h , ,
s t a r t l n d e x . .

S u b s t r i n g ().

812

II. C#

// Substring().
using System;
class SubstringDemo {
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(0, 15): ");
substr = str.Substring(0, 15);
Console.WriteLine (substr);

}
}
.
str: ABCDEFGHIJKLMNOPQRSTUVWXYZ
str.Substring(15): PQRSTUVWXYZ
' str.Substring (0, 15): ABCDEFGHIJKLMNO

S t r in g
, S t r i n g
I E n u m e r a b l e < T > . , , C# 3.0,
S t ring , E numerable
Queryable, System. Linq.
LINQ,
, .
. 19.

C# , int double,
,
. C#
, ,
. , I ,
.
C# ,
Console . WriteLine (), S t r i n g . Format () ToString ().
. ,
.


:
.

22.

8 13

. ,
,
. ,
(.. ^ ) .
,
. ,
, .
C#
. ,
.
I Format Provide , Get Format ().
.NET Framework
. ,
, ,
.
,
, .
3,
.
Console . WriteLin e (),
, .

W r i t e L i n e ().
WriteLine(" ", argO, a r g l,

... , argN) ;

WriteLine () , +.
:
, , .
:
{argnum, w idth: fmt}

a r g n u m , ; w i d t h
, a f m t . w i d t h f m t
.
. ,
{0 } , {1} a r g l ..

,
, argn u m . ,
,
.
.
f m t ,
. ,
. w i d t h ,

. w i d t h
, .

.

814

II. C#


,
. 22.4. ,
. ,

, F2.

22.4.

,
(
)
.

d
, D

- ( - .
)

( .
)

F
-

f
, F
G
. F
: F
g
. f
: f
N
-
( -
)

, N

,
R
, -
Parse ()
. (
)
X
(
-F) .

(
-F)
.
_____________________________________________

22.

815

,
. ,

,
.

.
, .

.
//
// .
using System;
class FormatDemo {
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 }", v2);
Console.WriteLine("{0:X}", x);
Console.WriteLine("{0:D12}", x);
Console.WriteLine("{0:C}",

189.99);

}
}
.
17688.66
17.688.65849
1.768866+004
17688.65849
15.00 %
15
000000000021

$189.99


, , ,
, . ,

816

II. C#


W r i t e L i n e O . ,
, .
.
using System;
class FormatDemo2 {
static void Main()

// .
Console.WriteLine("{0:F 2 } {0:F 3 } {0:}", 10.12345);
// .
Console.WriteLine("{2:d} {0:d } {l:d}", 1, 2, 3) ;

}
}
.
10.12 10.123 1.012345+001
3 12

WriteLine () 1 0 .1 2 3 4 5
. ,
.
W r i t e L i n e O .
, - ,
, .
.

S t r in g . Format ()
T o S trin g ()

WriteLine (), ,
, .
,
.
, Windows, -
, -.
,
.
S t r i n g . Form at ,
T o S trin g O , C# .
.

S t r i n g . F o rm a t ()
Format (),
String, .

22.

817

. 22.5. Format () W r i t e L i n e (),


, ,
.

22.5. F o rm a t ()

public static string


Format(string fo r m a t ,
object argO)

argO
,
fo r m a t . f o r m a t ,


argO
,
f o r m a t , a r g l
. f o r m a t ,


argO , a r g l 2
,
fo r m a t . f o r m a t ,


, a r g s ,
,
f o r m a t .
f o r m a t ,

, a r g s ,
,
f o r m a t ,
p r o v i d e r . f o r m a t ,
______________________________

public static string


Format(string f o r m a t ,
object argO , object a r g l )

public static string


Format(string f o r m a t ,
object argO , object a r g l ,
object a rg 2 )
public static string
Format(string f o r m a t ,
params o b j e c t [] a r g s )

public static string


F o r m a t (IFormatProvider
p r o v i d e r , string f o r m a t ,
params o b j e c t [] a r g s )

,
S t r i n g . Format ().
, .
// String.Format() ,
using System;
class FormatDemo {
static void Main() {
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
string str = String.Format("{0:F2 }", v) ;

818

II. C#
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 }", v2);
Console.WriteLine(str
str = String.Format(" 0 :X }", x);
Console.WriteLine(str
str = String.Format(" 0 :D12 }11, x);
Console.WriteLine(str
str = String.Format(" 0 : }", 189.99);
Console.WriteLine(str

W rite L in e (), S t r i n g . Form at ()


,
.
,
1 1 0 .
// Format().
using System;
class FormatDemo2 {
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);

}
}
.

22.
:
:
:
:
:
:
:
:
:
:

1
3
6
10
15
21
28
36
45
55

819

1
:
2
:
6
:
24
:
:
120
720
:
:
5040
40320
:
: 362880
: 3628800

.
str = String.Format(":{0,3 :D } :{1,8:D }", sum, prod);

F o r m a t ()
: ( sum),
( prod). ,
, W r i t e L i n e ( ) , n
Format () , , , " : ".
.

T o S t r in g ()

, ,
Int32 Double, ToString ().
T o S t r i n g O .
public string ToString(" ")

T o S trin g ()
, "
", . ,
188.99
.
string str = 189.99.ToString("");

,
ToString () . ,
W r i t e L i n e () Format (),
, ToString ()

.
,
ToString ()
. , .
// ToStringO
using System;
class ToStringDemo {
static void Main() {

820

II. C#
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
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 = v 2 .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);

}
}



, C# ,
.. , , ,
. ,
,
(.. ) . I
, .

-
I

,
( ) , .
, . 22.6.
.
.
- # , .
.
, #,
.

22.

821

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

22.6. -
-
#
,
%
0

;
0

+ 0

-0

+0

-0


, ,

- 0
,
.
, . ,
:
Console.WriteLine("{0:00##.#00}", 21.3);

.
0021.300

, ,
, .

, ,
#. , :
Console.WriteLine("{0:#,###.#}", 3421.3);

.
3,421.3.

.
,
. ,
:

822

II. C#

Console.WriteLine ("{0 :#,###.#}", 8763421.3);

.
8,763,421.3.

.
, .
1000. ,
:
Console.WriteLine(" :

{0:#,###,.#}", 8763421.3);

.
: 8,763.4

,
.
-,
,
, . ,
:
Console.WriteLine(" :

{0:##.# }", 21.3);

.
: 21.3


, \t \.
-
.
, .
.
. ,
"". ,
"". ,
+ +.
, , - -.
; ,
.
, ;.
_; _; _

.
Console.WriteLine("{0:#.##; (#.##);0.00}", num);

num ,
. num ,
,
. nu m ,
0 . 0 0 . ,
. ,

22.

823

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

, .
// ,
using System;
class PictureFormatDemo {
static void Main() {
double num = 64354.2345;
Console.WriteLine(" : " + num);
// 2 .
Console.WriteLine(" 2 : " +
"{0:#.##}", num);
// 2
// .
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
2 : 64354.23
: 64,354.23

824

II. C#

: 6.435+04
: 64
- , .
64354.2
(64354.23)

0.00
: 17%


,
: D a t e T i m e . , .
.
.
06/05/2005
Friday, January 1, 2010
12:59:00
12:59:00 PM

, -
. .NET Framework
.

. . 22.7.

.

22.7.

D
d
F
f
G

gg

s
T
t





,


,
, . ,
0,
.
,

, R


22.

825

. 22.7

;
(UTC)


, Y


.
// , ,
using System;
class TimeAndDateFormatDemo {
static void Main() {
DateTime dt = DateTime.Now; //
Console.WriteLine(" d: {0:d}", dt)
Console.WriteLine(" D : {0:D}", dt)
Console.WriteLine(" t: {0 :t }", dt)
Console.WriteLine("' : {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}" t dt
Console.WriteLine(" : {0 : }", dt)
Console.WriteLine(" 0: {0:0}", dt)
Console.WriteLine (" r : {0 :r }", dt)
Console.WriteLine(" R: {0:R}", dt)
Console.WriteLine (" s : {0 :s }", dt)
Console.WriteLine(" u : {0 :u }", dt)
Console.WriteLine(" U: {0 :U }", dt)
Console.WriteLine(" : {0:y}", dt)
Console.WriteLine("Y format: {0 :Y }" , dt)

}
}
, , ,

.

II. C#

826

d:
D:
t:
:
f:
F:
:
G:
:
:
:
:
:
R:
s:
:
U:
:
Y:

2 / 11/2010
Thursday, February 11, 2010
11:21 AM
11:21:23 AM
Thursday, February 11, 2 0 1 0 11:21 AM
Thursday, February 11, 2010 11:21:23 AM
2/11/2010 11:21 AM
2/11/2010 11:21:23 AM
February 11
February 11
2010-02-11T11:21:23.3768153-06:00
2010-02-11T11:21:23.3768153-06:00
Thu, 11 Feb 2010 11:21:23 GMT
Thu, 11 Feb 2010 11:21:23 GMT
2010-02-llTll:21 23
2 0 1 0 - 0 2 - 1 1 1 1 : 2 1 23Z
Thursday, February 11, 2010 5:21:23 PM
February, 2010
February, 2010

.
, .

T o S t r i n g O DateTime.

, , .
// .
using System;
class SimpleClock {
static void Main()
string t;
int seconds;

DateTime dt = DateTime.Now;
seconds = dt.Second;

for(;;) {
dt = DateTime.Now;
//
if(seconds != dt.Second) {
seconds = dt.Second;
t = d t .ToString("T");
if(dt.Minute==0 && d t .Second==0)
t = t + "\a"; //
Console.WriteLine(t);

22.

827



,
.

. , (.. ) ,
.
-, . 2 2 .8 .

22.8. -
-

d
dd

1 31
1 31.
1 9



,
.
f

1 12
1 12.
1 9
0 23
0 23.
1 9
, .

(UTC)
D a t e T i m e .Kind. (
Z . )

. 1 9

1 12
1 12.
1 9

. 1 9

, .. ( )
P.M. ( )

ddd
dddd

f, f f , f f f , f f f f ,
fffff, ffffff, fffffff
g
h
hh
H
HH

m
mm
M
MM

MMMM
s
ss
t

828

II. C#
. 22.8

-
t t

z
zz

zzz

:
/
% fm t

A.M. P.M.
,
. 1
9




.
1 9



,
f m t

. 22.8, , - d , f , g , m, , s t
, - . 22.7.
, ,
. . ,
-,
%.

.

// , ,
using System;
class CustomTimeAndDateFormatsDemo {
static void Main() {
DateTime dt = DateTime.Now;
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);

22.

829

(

).
: 11:19 AM
24- : 11:19
: Thu Feb 11, 2010
: A.D.
: 11:19:40 AM
m: February 11
: 19


4.0, .NET Framework
Time Span , .
Time Span ,
DateTime .
Time Span ,
.
Time Span
: , g G.
,
( ). ,
Time Span ,
. 22.9. ,
, %.

22.9. -
-

d, dd,
ddddd,

. -
, ,
,
( , ).
hh,
,
( , ).
mm,
,
( , ).
ss,
,
. -
f ,

. -
F ,
________

ddd, dddd,
dddddd, ddddddd

h, hh

m, mm

s,

ss

f, ff, fff, ffff,


fffff, ffffff, fffffff
F, FF, FFF, FFFF,
FFFFF, FFFFFF, FFFFFFF

d,

830

II. C#


T imeSpan ,
1 0 0 0 for.
// TimeSpan.
using System;
class TimeSpanDemo {
static void Main() {
DateTime start = DateTime.Now;
//
for(int i = 1; i <=
Console.Write(i +
i f ((i % 10) == 0)

1 1000.
1000; i++) {
" ");
Console.WriteLine();

}
Console.WriteLine();
DateTime end = DateTime.Now;
TimeSpan span = end - start;
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("

: {0:c}", span);
: {0:g}", span);
: {0:G}", span);
: 0.{0:fff} ", span);

}
}
,

,
.
981 982 983 984 985 986 987 988 989 990
991 992 993 994 995 996 997 998 999 1000
: 00:00:00.0140000
: 0:00:00.014
: 0:00:00:00.0140000
: 0.014


C# , .
, ,
. . 22.10.
G F. ,
, Flags. ,
,

22.

831

2. Flags
, , , ,
G. F
,
, .

22.10.


, D
F
.
,
,
, , Flags

f
, F
G
.
Flags,
, , ,

g
, G
X
.

( )
___________ , X___________________________________________________
D


.
// .
using System;
class EnumFmtDemo {
enum Direction { North, South, East, West }
[Flags] enum Status { Ready=0xl, OffLine=Ox2,
Waiting=0x4, TransmitOK=Ox8,
ReceiveOK=OxlO, OnLine=0x20 }
static void Main() {
Direction d = Direction.West;
Console.WriteLine("{0:G}", d);
Console.WriteLine("{0:F}", d);
Console.WriteLine("{0:D }", d);
Console.WriteLine("{0:X }", d) ;
Status s = Status.Ready | Status.TransmitOK;

832

II. C#
Console.WriteLine("{0:G }",
Console.WriteLine("{0:F}",
Console.WriteLine("{0:D}",
Console.WriteLine("{0:X }",

s);
s);
s);
s);

}
}
.
West
West
3
00000003
Ready, TransmitOK
Ready, TransmitOK
9
00000009

D n

.
:
C#

.
, .

. ,

.

,
#, , .NET
Framework. C#

,

. , C#

.
4.0 .NET Framework
,
. TPL
(Task Parallel Library
), PLINQ (Parallel LINQ
).

,
()
. , TPL
.
,

834

II. C#

TPL,
.
- . -,
,
.
, , . -,
, TPL, -
, . -,
TPL , ,
- ,
. TPL
, .
, ,
,
.
. ,

.


:
. .
.
,
. ,
,
.
,
.
.
" '7.

, . ,
. ,
, ,
.

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

23. . :

835


- .
-
. ,
,
, ,
.
. , <:
; ,
; , .. ;
; ;
, .
.NET Framework :
.
, .
, ,
.

,
.
C# ,
.
,
, . ,
.
.
C# .NET Framework
: . C#
, , .
,
,
. C#
, ,
C#
.
, ,
S y s t e m . T h r e a d i n g . C#
.
using System.Threading;

T h re a d
T h r e a d ,
. T h r e a d , ..
. T h r e a d ,
.
.

836

II. C#


Thread,
.. , System.Threading.
Thread:
public Thread(ThreadStart )

, ,
a T h r e a d S t a r t , .NET Framework,
.
public delegate void ThreadStart()

, , ,
void .
,
Start (), Thread.
Start (). .
public void Start()

, ,
, . ,
.
Start () , ,
ThreadStateException.

.
// .
using System;
using System.Threading;
class MyThread {
public int Count;
string thrdName;
public MyThread(string name)
Count = 0;
thrdName = name;

}
// ,
public void R u n () {
Console.WriteLine(thrdName + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrdName + ", Count = " + Count);
Count++;
} while(Count < 10);
Console.WriteLine(thrdName + " .");

23. . :

837

}
class MultiThread {
static void Main() {
Console.WriteLine(" .");
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(mt.Run);
// , .
newThrd.Start();
do {
Console.Write(".");
Thread.Sleep(100);
} while (mt.Count != 10);
Console.WriteLine(" .");

}
}
.
MyThread,
. Run () 0 9.
Sleep (), Thread.
, ,
, .
, .
Sleep ():
public static void Sleep(int _)

_ ,
. _
, ,
, .
M ain () T h r e a d
.
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(mt.Run);
// , .
newThrd.Start();

,
MyThread.
Thread,
m t . Run (). , Start ().

838

II. C#

m t .Run () .
Start () Main (),
do-while. ,
, .
. ( ,
.)
.
#1 .
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
.... #1,
#1 .
.

Count
Count
Count
Count
Count
Count
Count
Count
Count
Count

=
=
=
=
=
=
=
=
=
=

1
2
3
4
5
6
7
8
9

,
, .
, .
, ,
.
, .

. Count
do-while Main (),
1 0 , Sleep ( ).
,

.


,
, , (to-,
, .
Thread MyThread.
-, MyT h r e a d ,
Thread Name.
public string Name { get; set;

Name
, .
,
.

23. . :

839

// .
using System;
using System.Threading;
class MyThread {
public int Count;
public Thread Thrd;
public MyThread(string name) {
Count = 0;
Thrd = new Thread(this.Run);
Thrd.Name = name; //
Thrd.Start(); //

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep (500);
Console.WriteLine (" " + Thrd.Name + ", Count = " + Count);
Count++;
} while(Count < 10);
Console.WriteLine(Thrd.Name + " .");

}
}
class MultiThreadlmproved {
static void Main() {
Console.WriteLine(" .");
// MyThread.
MyThread mt = new MyThread(" #1");
do {
Console.Write (".");
Thread.Sleep (100);
} while (mt.Count != 10);
Console.WriteLine(" .");

}
}
, .
, Thrd MyThread.


.
, . ,
.
// .

840

II. C#

using System;
using System.Threading;
class MyThread {
public int Count;
public Thread Thrd;
public MyThread(string name) {
Count = 0;
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start() ;

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep (500);
Console.WriteLine(" " + Thrd.Name + ", Count = " + Count);
Count++;
} while(Count < 10);
Console.WriteLine(Thrd.Name + " .");

}
}
class MoreThreads {
static void Main() {
Console.WriteLine(" .");
//
MyThread mtl = new
MyThread mt2 = new
MyThread mt3 = new

.
MyThread(" #1");
MyThread(" #2") ;
MyThread(" #3");

do {
Console.Write(".");
Thread.Sleep(100) ;
} while (mtl.Count < 1 0 I |
mt2.Count < 1 0 ||
mt3.Count < 10);
Console.WriteLine(" .");

}
}

.
. #1 .
#2 .
#3 .
.... #1, Count = 0
#2, Count = 0
#3, Count = 0

23. . :

841

.... #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 = 6
#2, Count = 6
#3, Count = 6
.... #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 .
.

, ,
.
, ,
.


, .
Count.
. ,
Thread
. , ,
Is A liv e, .
public bool IsAlive { get;

I s A liv e tr u e , ,
, - . "" I s A liv e
More T h read
, .

842

II. C#

// IsAlive ,
class MoreThreads {
static void Main() {
Console.WriteLine(" .");
//
MyThread mtl = new
MyThread mt2 = new
MyThread mt3 = new

.
MyThread(" #1");
MyThread(" #2");
MyThread(" #3");

do {
Console.Write(".");
Thread.Sleep(100);
} while (mtl.Thrd.IsAlive &&
mt2 .Thrd.IsAlive &&
m t 3 .Thrd.IsAlive);
Console.WriteLine(" .");

}
}
,
. ,
Is A liv e .

Jo in (). .
public void Join()

J o i n () , , ,
. ,
. ,
T h re a d S ta te E x c e p tio n . Jo in ()
,
.
J o i n () ,
.
// Join().
using System;
using System.Threading;
class MyThread {
public int Count;
public Thread Thrd;
public MyThread(string name) {
Count = 0;
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start ();

}
// ,
void R u n () {

23. . :

843

Console.WriteLine(Thrd.Name + " .");


do {
Thread.Sleep(500);
Console ._WriteLine (" " + Thrd.Name + ", Count = " + Count);
Count++;
} Vhile(Count < 10);
Console.WriteLine(Thrd.Name + " .");

}
}
// Join() ,
// ,
class JoinThreads {
static void Main() {
Console.WriteLine(" .");
//
MyThread mtl = new
MyThread mt2 = new
MyThread mt3 = new

.
MyThread(" #1");
MyThread(" #2");
MyThread(" #3");

mt l .Thrd.Join();
Console.WriteLine(" #1 .");
mt2.Thrd.Join();
Console.WriteLine(" #2 .");
m t 3 .Thrd.Join();
Console.WriteLine(" #3 .");
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

=
=
=
=
=
=
=
=
=
=
=

0
0
0
1
1
1
2
2
2
3
3

844

II. C#

#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
#1 .
#2, Count
#2 .
#3, Count
#3 .
#1 .
#2 .
#3 .
.

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

3
4
4
4
5
5
5
6
6
6
7
7
7
8
8
8
9

= 9
= 9

,
Join ().


.NET Framework ,
, , ,
. - ,
,
. ,
.
Start (), Thread, ,
.
Start ().
public void Start(object )

, ,
, . ,
, Start ().
Start ()
Thread:
public Thread(ParameterizedThreadStart )

,
. ,

23. . :

845

Parameter izedTh r e a d S tart, T h r e a d s tart, ,


. Parameter izedThreadS tart
, .
public delegate void ParameterizedThreadStart(object ob j)

, obj ect.
T h r e a d ,
, obj ect.

.
// .
using System;
using System.Threading;
class MyThread {
public int Count;
public Thread Thrd;
// ,
// MyThread int.
public MyThread(string name, int num) {
Count = 0;
// ParameterizedThreadStart
// .
Thrd = new Thread(this.Run);
Thrd.Name = name;
// num Start ()
// .
Thrd.Start(num);

}
// , Run()
// object.
void Run(object num) {
Console.WriteLine(Thrd.Name + " " + num);
do {
Thread.Sleep (500);
Console.WriteLine(" " + Thrd.Name + ", Count = " + Count);
Count++;
} while(Count < (int) num);
Console.WriteLine(Thrd.Name + " .");

}
}
class PassArgDemo {
static void Main()

846

II. C#

// ,
// MyThread.
MyThread mt = new MyThread(" #1", 5);
MyThread mt2 = new MyThread(" #2", 3);
do {
Thread.Sleep(100);
} while (mt.Thrd.IsAlive'| m t 2 .Thrd.IsAlive);
Console.WriteLine(" .");

,
.
#1 5
#2 3
#2, Count =
#1, Count =
#1, Count =
#2, Count =
#2, Count =
#2 .
#1, Count =
#1, Count =
#1, Count =
#1 .
.

0
0
1
1
2
2
3
4

, ,
. MyThread
Run (), ,
ParameterizedThreadStart Start ().

Is B a c k g ro u n d
, .NET Framework
: .
, , ,

. .
, IsBackground,
Thread, .
public bool IsBackground { get; set;

,
true IsBackground. false ,

23. . :

847


, ,
. ,
, . ,

, . , ,
,
, .
, , ,
. ,
, , ,
.
,
. ,
,
.
, ,
.
Priority, Thread.
:
public ThreadPriority Priority{ get; set;

ThreadPriority ,
.
ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest

T h r eadPriority.
Normal.

,
, :
. MyThread.
Run () ,
. , 1000000000
stop true.
stop false. ,
1000000000, true
stop.
. c u r r e n t N a m e
. ,
, . ,
,
currentName. .
.

848

II. C#

// .
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(this.Run) ;
Thrd.Name = name;
currentName = name;

}
// ,
void R u n () {
Console.WriteLine(" " + Thrd.Name + " .");
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 {
static void Main() {
MyThread mtl = new MyThread(" ");
MyThread mt2 = new MyThread(" ");
// .
m t l .Thrd.Priority = ThreadPriority.AboveNormal;
m t 2 .Thrd.Priority = ThreadPriority.BelowNormal;
// ,
m t l .Thrd.Start();
m t 2 .Thrd.Start() ;
m t l .Thrd.Join ();
m t 2 .Thrd.Join();
Console.WriteLine();
Console.WriteLine(" " + m t l .Thrd.Name +

23. . :

849

" " + mtl.Count);


Console.WriteLine(" " + m t 2 .Thrd.Name +
" " + mt2.Count);

}
}
.
.

.










.
.
1000000000
23996334

, 98% ,
. ,
,
, Windows.
- ,
.
, ,

, .
, , ,
.

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

850

II. C#

,
.
,
. ,
.
#.
. lock .
C# ,
, .
C# .
:
lock (lock O bj) {
//

}
lo c k O b j .
, . lo ck
, , ,
, .
, .
.
,
.
, . , ,
, ,
,
.
lo ck ( t h i s ).
, t h i s .
,
lo c k ( t h i s ) , .
, .
, .
C# lo c k ( t h i s ) .
,
.

Sumlt (),
.
// .
using System;
using System.Threading;
class SumArray {
int sum;
object lockOn = new object(); // ,
//
public int Sumlt(int[] nums) {

23. . :

851

lock(lockOn) { //
sum = 0 ; //
for(int i=0; i < nums.Length; i++) {
sum +- nums[i ];
Console.WriteLine(" " +
Thread.CurrentThread.Name + " "
Thread.Sleep(10); //

sum) ;

}
return sum;

}
}
}
class MyThread {
public Thread Thrd;
int[] a;
int answer;
// SumArray
// MyThread.
static SumArray sa = new SumArray();
// ,
public MyThread(string name, int [] nums)
a = nums;
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start(); //

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
answer = sa.Sumlt(a);
Console.WriteLine(" " + Thrd.Name + "
Console.WriteLine(Thrd.Name + " .");

}
}
class Sync {
static void Main() {
int[] a = {1, 2, 3, 4, 5};
MyThread mtl = new MyThread (" #1", a);.
MyThread mt2 = new MyThread(" #2", a);
mtl.Thrd. Jo in ();
m t 2 .Thrd.Jo in () ;

}
}

+ answer);

852

II. C#

,
.
#1 .

#2 .






#1 .





#2 .

#1 1
#1
#1
#1
#1
#2
#1 15

3
6
10
15
1

#2
#2
#2
#2
#2 15

3
6
10
15

,
, 15.
. .
SumArray, Sumlt (),
. MyThread,
sa SumArray. ,
SumArray MyThread.
.
, sum SumArray.
Sumlt () ,
sum, .
, Sumlt ()
. , , Sync, ,
.
lock Sumlt ()
. , lock
lockOn . ,
. Sleep ()
, ,
. Sumlt () ,
. ,
, Sumlt () ,
.
.
,
Sumlt ().
Su mlt () , , _
.
sum, ,
Sumlt (). ,
Sumlt () ,

23. . :

853

, sum
.
Sumlt ().
#1 .


#2 .










#1 .

#2 .

#1 1
#2
#1
#2
#1
#2
#1
#2
#1
#2
#1 2 9

1
3
5
8
11
15
19
24
29

#2 29

,
Sumlt () ,
sum.
.
,
.
,
, ,
.
,
.


,
,
. , ,
- .
,
. lo c k
. ? ,
:
,
lock .
. , Sumlt ()
, lockOn .
Sumlt () MyThread.
// ,
using System;

854

II. C#

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 {
public Thread Thrd;
int[] a;
int answer;
/* SumArray
MyThread. */
static SumArray sa = new SumArray();
// ,
public MyThread(string name, int[] nums)
a = nums;
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start(); //

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
// Sumlt().
lock(sa) answer = sa.Sumlt(a);
Console.WriteLine(" " + Thrd.Name +
" " + answer);
Console.WriteLine(Thrd.Name + " .");

}
}
class Sync {
static void Main() {
i nt[] a = {1, 2, 3, 4, 5};
MyThread mtl = new MyThread(" #1", a);
MyThread mt2 = new MyThread(" #2", a);
m t l .Thrd.Join();
m t 2 .Thrd.Join();

}
}

23. . :

855

sa . S u m It (),
Sum It (). ,
.
// Sumlt() .
lock(sa) answer = sa.Sumlt(a);

sa ,
.
, .

M o n ito r
lo c k C#
, Monitor,
System. Threading. , ,
. ,
Enter (), Exit ().
:
public static void Enter(object ob j)
public static void Exit (object o b j)

o b j . ,
Enter () ,
. E n ter () Exit () ,
lock
. lock " "
#.
, M o n i t o r .
TryEnter (), .
public static bool TryEnter(object ob j)

true,
o b j , false.
.
TryEnter ()
, .
, Monitor Wait (), Pulse () PulseAll (),
.


W a it (), P u ls e () P u ls e A ll ()
. lock,
R, .
7? ,
R, ,
. ,

856

II. C#

. ,
.
,
,
. C#
Wait (), Pulse () PulseAll ().
W ait ( ) , P u ls e () P u ls e A ll () M o n i t o r
.
. ,
Wait (). ,
,
. ,
, P u lse () P u lseA ll ().
P u lse () ,
. P u ls e A ll ()
.
Wait ().
public static bool Wait(object ob j)
public static bool Wait(object o b j ,

int _)


, ,
, _ .
o b j , .
Pulse () PulseAll ():
public static void Pulse(object ob j)
public static void PulseAll(object ob j)

o b j .
Wait(),Pulse() n P u l s e A l l ( ) ,
, lock,
SynchronizationLockException.

W a it () P u ls e ()
Wait () Pulse (),
,
"" "". TickTock,
: T i c k () ( ) . T i c k ()
"", () "".
: Tick (), ().
, ,
"" "",
"-", /
// Wait() Pulse()
using System;
using System.Threading;

23. . :
class TickTock {
object lockOn = new object ();
public void Tick(bool running) {
lock(lockOn) {
i f (!running) { //
Monitor.Pulse(lockOn); //
return;

}
Console.Write(" ");
Monitor.Pulse(lockOn); // Tock()
Monitor.Wait(lockOn); // Tock()

}
}
public void Tock(bool running) {
lock(lockOn) {
i f (!running) { //
Monitor.Pulse(lockOn); //
return;

}
Console.WriteLine("");
Monitor.Pulse(lockOn); // Tick()
Monitor.Wait(lockOn); // Tick()

class MyThread {
public Thread Thrd;
TickTock ttOb;
// ,
public MyThread(string name, TickTock tt)
Thrd = new Thread(this.Run);
ttOb = tt;
Thrd.Name = name;
Thrd.Start(); '

}
// ,
void R u n () {
if(Thrd.Name == "Tick") {
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);

}
}

85 7

858

II. C#

class TickingClock {
static void Main() {
TickTock tt = new TickTock ();
MyThread mtl = new MyThread("Tick", tt);
MyThread mt2 = new MyThread("Tock", tt) ;
m t l .Thrd.Join();
mt2.Thrd.Join();
Console.WriteLine(" ");

}
}
.





. Main () tt
TickTock, .
Run () M y T h r e a d Tick,
"", Tick (). Tock,
"", Tock ().
true
. , true,
, false.

T ick () Tock (). Ti c k (),
.
public void Tick(bool running) {
lock(lockOn) {
i f (!running) { //
Monitor.Pulse(lockOn); //
return;

}
Console.Write(" ");
Monitor.Pulse(lockOn); // Tock()
Monitor.Wait(lockOn); // Tock()

}
}
Tick () lock. ,
Wait () Pulse ()
. Tick () ,
. false,
. Pulse (),
, .
. Tick (),
"" , Pulse (),

23. . :

859

W a i t ( ) . P u l s e ()
, W a i t () T i c k ()
, P u l s e () .
, T i c k ( ) , "" ,
,
.
() T i c k ( ) , ,
"". , ()
"", P u l s e ( ) , ()
. T i c k () ()
, .. .
, P u l s e () ,
Wait ( ) . , Wai t ()
, Tick () ( ) , .
, ,
. P u l s e () ,
.
P u l s e () , .
, "",
<C trl+ C > . , Wait ()
( ) , P u l s e () , ,
() ,
.
, , ,
, , , Wait () P u l s e ( ) ,
.
Tic k T o c k .
Wait () P u l s e () .
// TickTock.
class TickTock {
object lockOn = new object ();
public void Tick(bool running) {
lock(lockOn) {
if (!running) { //
return;

}
Console.Write(" ") ;

}
}
public void Tock (bool running) {
lock(lockOn) {
i f (!running) { //
return;

}
Console.WriteLine("");

860

II. C#

, Tick () Tock () !


,
. ,
, ,
, , , -
. , ,
. ,
, !
,
, .
TickTock . ,
Pulse () Tick () Tock ()
, ""
. -
, ,
.

. , "
", .
,
. ,
,
.
, :

. , " ",
, .
, , .
,
.

M e th o d lm p lA ttrib u te

M e t h o d l m p l A t t r i b u t e .
l o c k , .

23. . :

861

S y s t e m . R u n t i m e .
,

M e t h o d l m p l A t t ibute
CompilerServices.

:
public MethodlmplAttribute(MethodlmplOptions m ethodlm plO ptions)

m e th o d lm p lO p tio n s .
M e t h o d l m p l O p t i o n s . Synchronized.
,
this. static, .
.
, ,
TickTock, M e t h o d l m p l O p t i o n s
.
// MethodlmplAttribute .
using System;
using System.Threading;
using System.Runtime.CompilerServices;
// TickTock,
// MethodlmplOptions.Synchronized,
class TickTock {
/* Tick(). */
[MethodlmplAttribute(MethodlmplOptions.Synchronized)]
public void Tick (bool running) {
i f (!running) { //
Monitor.Pulse(this); //
return;

}
Console.Write(" ");
Monitor.Pulse(this); // Tock()
Monitor.Wait(this); // 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;

862

II. C#

// .
public MyThread(string name, TickTock tt)
Thrd = new Thread(this.Run);
ttOb = tt;
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
if(Thrd.Name == "Tick") {
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 {
static void Main() {
TickTock tt = new TickTock();
MyThread mtl = new MyThread("Tick", tt) ;
MyThread mt2 = new MyThread("Tock", tt) ;
m t l .Thrd.Join();
mt2.Thrd.Join();
Console.WriteLine(" ");

}
}
, .

, l o c k
M ethodlm plA ttribute .
. lo c k
#, , , .

M eth o d lm p lA ttrib u te
. lo ck ,
, .


, ,
lock . , , ,

23. . :

863

, ,
.NET Framework.
: .


. , .
,
. ,
,
.
.
System. T h r e a d i n g .Mutex.
. .
public Mutex()
public Mutex(bool in itia lly O w n e d )

,
.
, i n i t i a l l y O w n e d true.
.
,
WaitOne () . WaitOne () Mutex
Thread. WaitHandle. .
public bool WaitOne ();

WaitOne () , ,
. ,
, .
true.
,
ReleaseMutex (), .
public void ReleaseMutex()

ReleaseMutex () ,
, .

WaitOne () R e l e a s e M u t e x () ,
.
Mutex myMtx = new Mutex();

//

. . .

myMtx.WaitOne() ; //
// .
myMtx.ReleaseMutex(); //

864

II. C#

W a i t O n e ()
, .
R ele a s e M u t e x ()
.
.

.
I n c T h r e a d n DecThread, :
S h aredRes .Count. I n c T h r e a d SharedRes .Count
, D e c T h r e a d .
SharedRes .Count
Mtx, SharedRes.
// .
using System;
using System.Threading;
/ / ( Count),
// (Mtx), .
class SharedRes {
public static int Count = 0;
public static Mutex Mtx = new Mutex();

}
// SharedRes.Count ,
class IncThread {
int num;
public Thread Thrd;
public IncThread(string name, int n) {
Thrd = new Thread(this.Run);
num = n;
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
// .
SharedRes.M t x .WaitOne();
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep (500);
SharedRes.Count++;
Console.WriteLine(" " + Thrd.Name +
", SharedRes.Count = " + SharedRes.Count);
num ;
} while(num > 0);

23. . :

Console.WriteLine(Thrd.Name + " .");


// .
SharedRes.Mt x .ReleaseMutex();

}
}
// SharedRes.Count ,
class DecThread {
int num;
public Thread Thrd;
public DecThread(string name, int n) {
Thrd = new Thread(new ThreadStart(this.Run));
num = n;
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
// .
SharedRes.Mt x .WaitOne();
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep(500) ;
SharedRes.Count ;
Console.WriteLine(" " + Thrd.Name +
", SharedRes.Count = " + SharedRes.Count);
num ;
} while(num > 0);
Console.WriteLine(Thrd.Name + " .");
// .
SharedRes.Mtx.ReleaseMutex();

}
}
class MutexDemo {
static void Main()

// .
IncThread mtl = new IncThread(" ", 5);
Thread.Sleep(1); //
DecThread mt2 = new DecThread(" ", 5);
mtl.Thrd.Join();

865

866

II. C#
m t 2 .Thrd.Join ();

.
.
.
.
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
.
.
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
, SharedRes.Count
.

=
=
=
=
=

1
2
3
4
5

=
=
=
=
=

4
3
2
1

, (
S h a redRes .Count) ,
.
,
, W a i t O n e ()
R e l e a s e M u t e x () .
,
.

,
,
,
,
,
,
,
,
,

SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count

=
=
=
=
=
=
=
=
=

,
SharedRes .Count , ,
, .
, , ,
. ,
- . .
, .
public Mutex(bool in itia lly O w n e d , string )
public Mutex(bool in itia lly O w n e d , string , out bool createdNew)

.
i n i t ia l l y O w n e d

23. . :

867

true, .
,
false.
c r e a t e d N e w true,
, false,
. Mutex,
MutexSecurity.
.
: , ,
Wai t One ()
ReleaseM utex (),
. , Wait One ()
, . Wai t One ()
R eleaseM utex ()
.

, ,
, .
.
, .
, . ,
. .
, .
, ,
. ,
, .
, .
, ,
. ,
.
. , ,
, .
,
. ,
, . ,
, , .

.
System. T h r e a d i n g .Semaphore,
.
:
public Semaphore(int in i t ia lC o u n t ,

int maximumCount)

i n i t i a l C o u n t
, .. ; m a x im u m C o u n t
, .. ,
.

868

II. C#

, .
Wait One ()
. Semaphore WaitHandle.
Wa itOne () , ,
. , ,
.
, ,
Release (). .
public int Release()
public int Release(int relea se C o u n t)

R e l e a s e () ,
, r e l e a s e C o u n t .
,
.
WaitOne ()
R e l e a s e ( ) . W a i t O n e ()
R e l e a s e () .
, Releas e ( i n t ) ,
,
WaitOne ().

,
. M y Thread
MyThread. ,
.
// .
using System;
using System.Threading;
//
// ,
class MyThread {
public Thread Thrd;
// ,
// ,
static Semaphore sem = new Semaphore(2, 2);
public MyThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd. Start () ;

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
sem.WaitOne();

23. . :

869

Console.WriteLine(Thrd.Name + " .");


for(char ch='A'; ch < 'D'; ch++) {
Console.,WriteLine (Thrd.Name + " : " + ch + " ");
Thread.Sleep(500);

}
Console.WriteLine(Thrd.Name + " .");
// ,
sem.Release();

}
}
class SemaphoreDemo {
static void Main() {
//
MyThread mtl = new
MyThread mt2 = new
MyThread mt3 = new

.
MyThread(" #1");
MyThread(" #2");
MyThread(" #3");

mt l .Thrd.Join();
mt2.Thrd.Join() ;
mt3.Thrd.Join() ;

}
}
MyThread sem, .
static Semaphore sem = new Semaphore(2f 2);

,
.
, M y T h r e a d .Run ()
, sem .
, .
, . In Main ()
. ,
.
, .

#1
#1
#1
#2
#2
#2
#3
#1
#2
#1
#2
#1

.
.
:
.
.
:
.
:
:
:
:

870

II. C#
#3
#3
#2
#3
#3
#3

.
:

:
:

, , ,
. ,
- . .
Semaphore, .
public Semaphore(int i n i t ia lC o u n t , int maximumCountf string )
public Semaphore(int in i t ia lC o u n t , int maximumCount, string ,
out bool createdNew)

, .
, , ,
, i n i t i a l C o u n t maxim umCount.
, i n i t i a l C o u n t m a x im u m C o u n t
. c r e a t e d N e w
true, .
i n i t i a l C o u n t m a xim um C ou nt .
c r e a t e d N e w false, ,
i n i t i a l C o u n t m a x im u m C o u n t
. Semaphore,
SemaphoreSecurity.
.


C# : .
:
. ManualResetEvent AutoResetEvent
. EventWaitHandle,
, ,
.
, ,
.
ManualResetEvent AutoResetEvent.
public ManualResetEvent(bool i n i t i a l S t a t e )
public AutoResetEvent(bool i n i t i a l S t a t e )

i n i t i a l S t a t e true,
. false,
.
. , Ma n u a l R e s e t E v e n t
. , ,
W aitOne () , .
,

23. . :

8 71

WaitOne ().
, .
,
, Set ( ) . Set ()
, .

WaitOne (), .
Reset () .
A u t o Re s e t E v e n t M a n u a l R e s e t E v e n t
.
ManualResetEvent ,
Re s e t ( ) , A u t o R e s e t E v e n t
, ,
,
. A utoResetEvent,
Reset () .

ManualResetEvent.
// ,
// .
using System;
using System.Threading;
// , ,
class MyThread {
public Thread Thrd;
ManualResetEvent mre;
public MyThread(string name, ManualResetEvent evt)
Thrd = new Thread(this.Run);
Thrd.Name = name;
,
mre = evt;
Thrd.Start();

}
// .
void R u n () {
Console.WriteLine(" " + Thrd.Name);
for(int i=0; i<5; i++) {
Console.WriteLine(Thrd.Name);
Thread.Sleep(500) ;

}
Console.WriteLine(Thrd.Name + " !");
// .
mr e .Se t ();

872

II. C#

class ManualEventDemo {
static void Main() {
ManualResetEvent evtObj = new ManualResetEvent(false);
MyThread mtl = new MyThread(" 1", evtObj);
Console.WriteLine(" .");
// .
evtObj.WaitOne();
Console.WriteLine(" " +
" .");
// .
evtObj.Reset();
mtl = new MyThread(" 2", evtObj);
// .
evtObj.WaitOne();
Console.WriteLine(" " +
" .");

}
,
.
1
1
.
1
1
1
1
1 !
.
2
2
2
2
2
2
2 !
.

, M a n u a l R e s e t E v e n t
MyThread.
Run () MyThread, Set (),
. Main ()
evtObj ManualResetEvent,
, .

23. . :

8 73

MyThread, evtObj.
. evtObj

,
, M y T h r e a d
Set () ^ evtObj .
.
, ,
. ,
,
. ,
WaitOne () Main ().

AutoResetEvent ManualResetEvent,
Reset () Main () .
,
, , .

ManualResetEvent AutoResetEvent
Reset (). , .

In t e r lo c k e d
, , Interlocked.
,
. ,
Interlocked, , ,
. ,
. Interlocked
, ,
, 64- . .

Interlocked: Increment () Decrement ().
:
public static int Increment(ref int lo c a tio n )
public static int Decrement(ref int lo c a tio n )

l o c a t i o n ,
.
// .
using System;
using System.Threading;
// ,
class SharedRes {
public static int Count = 0;

874

II. C#

// SharedRes.Count ,
class IncThread {
'
public Thread Thrd;
public IncThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
for(int i=0; i<5; i++) {
Interlocked.Increment(ref SharedRes.Count);
Console.WriteLine(Thrd.Name + " Count = " + SharedRes.Count);

}
}
// SharedRes.Count ,
class DecThread {
public Thread Thrd;
public DecThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
for(int i=0; i<5; i++) {
Interlocked.Decrement(ref SharedRes.Count);
Console.WriteLine(Thrd.Name + " Count = " + SharedRes.Count);

}
}
}
class InterlockedDemo {
static void Main() {
// .
IncThread mtl = new IncThread(" ");
DecThread mt2 = new DecThread(" ");
mtl.Thrd.Join();
mt2.Thrd.Join();

}
}

, .NET Framework 4.0


, S e m a p h o r e
A u t o R e s e t E v e n t , .NET Framework, 1.1.

23. . :

875

, .NET
Framework. .NET Framework 4.0
. .

Barrier
CountdownEvent
ManualResetEventSlim
semaphoreslim


,
,
M a n u a l R esetEvent
Semaphore

, ,
,
.


. ,
- .
.
Thread.
Abort (). .
public void Abort()

A b o r t ()
ThreadAbortException , .
,
, .
Abort () ,
, ,
Abort () Join (). ,
Abort () . ,
, , finally .

Abort () .
// Abort().
using System;
using System.Threading;
class MyThread {
public Thread Thrd;
public MyThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();

876

II. C#

// ,
void R u n () {
Console.WriteLine(Thrd.Name + " .");
for (int i = 1; i <= 1000; i++)
Console.Write(i + " ");
if ( (i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);

}
}
Console .WriteLine (Thrd.Name + 11 .");

}
}
class StopDemo {
static void Main() {
MyThread mtl = new MyThread(" ");
Thread.Sleep (1000); //
Console.WriteLine(" .");
mtl.Thrd.Abort();
m t l .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
.
.

A b o r t () ,
.
, , .

A b o r t ()
A b o r t () ,
:

23. . :

877

public void Abort(object s t a t e l n f o )

s t a t e l n f o ,
, .
ExceptionState ThreadAbortException.
.
Abort ().
// Abort (object s t a t e l n f o ) .
using System;
using System.Threading;
class MyThread {
public Thread Thrd;
public MyThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
try {
Console.WriteLine(Thrd.Name + " .");
for (int i = 1; i <= 1000; i++)
Console.Write(i + " ");
i f ((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);

}
}
Console.WriteLine(Thrd.Name + " .");
} catch(ThreadAbortException exc) {
Console.WriteLine(" , " +
exc.ExceptionState);

}
class UseAltAbort {
static void Main() {
MyThread mtl = new MyThread(" ");
Thread.Sleep(1000) ; //
Console.WriteLine(" .");
mtl.Thrd.Abort(100);
mt l .Thrd.Join(); //

878

II. C#
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
.
, 100
.

, 100
A b ort () .
ExceptionState ThreadAbortException,

A b o r t ()

.
T h r e a d A b o r t E x c e p t i o n , R e s e t A b o r t ().

, .
R e s e t A b o r t ().
public static void ResetAbort()

ResetAbort () ,
.

R e s e t A b o r t ().
// ResetAbort().
using System;
using System.Threading;
class MyThread {
public Thread Thrd;
public MyThread(string name) {
Thrd = new Thread(this.Run);
Thrd.Name = name;
Thrd.Start();

}
// ,
void R u n () {
Console.WriteLine(Thrd.Name + "..");
for(int i = 1; i <= 1000; i++)

23. . :

879

try {
Console.Write(i + " ");
i f ((i %10)==0) {
Console.WriteLine ();
Thread.Sleep (250);

}
} catch(ThreadAbortException exc) {
i f ((int)exc.ExceptionState = = 0 ) {
Console.WriteLine(" ! " +
" " + exc.ExceptionState);
Thread.ResetAbort();

}
else
Console.WriteLine(" , " +
exc.ExceptionState);

'

}
}
Console.WriteLine(Thrd.Name + " .");

}
}
class ResetAbort {
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(" .");

}
}
.

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
.

880

II. C#

Abort ( )
, ,
Re set Abort (), .
.


.NET Framework
Thread. S u s p e n d () Thread.
R esume ().
. , , ,
Suspend () ,
, ,
, , .
.

, .


Threadstate,
Thread. .
public ThreadState ThreadState{ get;

,
ThreadState. , .
T h r e a d S t a t e .Aborted
T h r e a d S t a t e .Backgro u n d
T h r e a d S t a t e .Stopped
T h r e a d S t a t e .Suspended
T h r e a d S t a t e .Unstarted

T h r e a d S t a t e .AbortRequested
T h r e a d S t a t e .Running
T h r e a d S t a t e .StopRequested
T h r e a d S t a t e .SuspendRequested
T h r e a d S t a t e .WaitSleepJoin

, .
T h r e a d S t a t e .W a i t s l e e p J o i n ,
Wait (), Sleep () Join ().


, C#
, .
, .
, .
Thread,
. CurrentThread,
Thread. .
public static Thread CurrentThread{ get;

23. . :

881

, .
C u r r e n t T h r e a d
, .
, ,
.

, .
// .
using System;
using System.Threading;
class UseMain {
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

, , ,
. , M a i n () J o i n ():
Thrd.Join ();

,
!

882

II. C#

,
.NET Framework 4.0
.NET Framework 4.0 ,
.
. ,
.
,
. CancellationTokenSource
CancellationToken.
(TPL),
TPL 24.
System. Threading SpinWait,
SpinOnce () SpinUntil (),
. , SpinWait
.
. ,
, SpinLock,
, . Thread Yield ( ) ,
, .
.
public static bool Yield()

true,
. , ,
.



, . ,
, ,
.
, ,
,. .
, . ,
,
, ! , ,
,
(TPL), .



#. , ,
.

23. . :

883

. C#
Process, System.
Diagnostics.
.

Start (), Process.
:
public static Process Start(string _)

_ ,
.
, Close (),
, .
Close ().
public void Close ()

.
Windows ,
C l o s e M a i n W i n d o w (),
.
public bool CloseMainWindow()

, .
true, ,
false,
. , , , Cl o seMainWindow ()
.
, .
Kill (),
.
public void Kill()

Kill () ,
. ,
, , , .
,
WaitForExit (). .
public void WaitForExit()
public bool WaitForExit(int )

, ,
.
WaitForExit () true,
, false, .
,
.
Windows: WordPad.exe,
WordPad .

884

II. C#

// .
using System;
using System.Diagnostics;
class StartProcess {
static void Main() {
Process newProc =r Process.Start("wordpad.exe");
Console.WriteLine(" .");
newProc.WaitForExit();
newProc.Close(); //
Console.WriteLine(" .");

}
}
WordPad,
" . ".
WordPad. WordPad
" .11.

.
: TPL
, ,
4.0 .NET Framework,
(TPL).

. -,
. -,

. , TPL


. TPL

.

, 4.0 .NET Framework,

(PLINQ). PLINQ
,
, ,
. ,
.
, PLINQ
.
,
TPL PLINQ,
.
.
,
. , ,
,

886

II. C#


. ,
- .
, , TPL PLINQ.
( ) .
TPL S y s t e m .T h r e a d i n g .Tasks.
System.
Threading,
, , Interlocked.
TPL, PLINQ. , , ,
.
TPL PLINQ.
,
TPL PLINQ.
, .NET Framework
.

TPL PLINQ
,
Thread, 23, -
. , , 23, TPL.
23
#.


TPL,
. .

, . ,
, , ,
.
,
.

Thread,
. TPL,

.
.
. ,
,
Thread. ,
TPL,
.

24. . : TPL

887

T a s k
TPL Task.
TPL Task, Thread. Task
Thread , , .
Thread . ,
- ,
.
Task -.
, ,
. , , ,
. Task ( TPL)
Syste m . T h r e a d i n g .Tasks.


Task
. Task
, Start (). Task
. ,
:
public Task(Action )

, ,
A c t i o n , System.
Action, , .
public delegate void Action()

, ,
. ( ,
Action .)
, ,
Start (). .
public void Start()

S t a r t () .

. M yTask ( ) .
Main (),
. MyTask () Main () .
// .
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// .

888

II. C#

static void MyTask() {


Console.WriteLine("MyTask() ");
for(int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTask(), " + count);

}
Console.WriteLine("MyTask ");

}
static void Main() {
Console.WriteLine(" .");
// .
Task tsk = new Task(MyTask);
// ,
tsk.Start ();
// M a i n () MyTask().
for(int i = 0; i < 60; i++) {
Console.Write(".");
Thread.Sleep(100);

}
Console.WriteLine(" .");

}
}
. (
, .)
.
.MyTask()
MyTask () ,
. MyTask() ,
MyTask () ,
. MyTask () ,
MyTask() ,
MyTask () ,
. MyTask() ,
. MyTask () ,
. MyTask(),
. MyTask(),

0
1
2
3
4
5
6
7
8
9

, .
, .
Thread. S l e e p )
,
M y T a s k (). ,
, .

24. . : TPL

889

,
, .
. , ,
, M y T a s k (),
, .
// .
using System;
using System.Threading;
using System.Threading.Tasks;
class MyClass {
// ,
public void MyTask() {
Console.WriteLine("MyTask() ");
for(int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTask(), " + count);

}
Console.WriteLine("MyTask ");

}
}
class DemoTask {
static void Main() {
Console.WriteLine(" .");
// MyClass.
MyClass me = new MyClassO;
// me.MyTask().
Task tsk = new Task(me.MyTask);
// ,
tsk.Start();
// Main() MyTask().
for(int i = 0; i < 60; i++) {
Console.Write (".");
Thread.Sleep (100);

}
Console.WriteLine(" .");

}
}
, .
, MyTask ()
MyClass.

890

II. C#

: ,
, . ,
, , .


Thread; Task Name
. Id
, . Td
int. .
public int Id { get;

, .
, .
, .

Currentld. ,
static .
public static Nullable<int> CurrentID { get;

,
.
,
.
// Id Currentld.
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// , ,
static void MyTaskO {
Console.WriteLine("MyTask() " + Task.Currentld + " ");
for (int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTaskO #" + Task.Currentld +
", " + count );

}
Console.WriteLine("MyTask " + Task.Currentld + " ");

}
static void Main()

Console.WriteLine(" .");
// .
Task tsk = new Task(MyTask);
Task tsk2 = new Task(MyTask);

24. . : TPL

891

// ,
tsk.Start();
tsk2.Start();
Console.WriteLine(" tsk: " + tsk.Id);
Console.WriteLine(" tsk2: " + tsk2.Id);
// Main() ,
for(int i = 0; i < 60; i++) {
Console.Write(".");
Thread.Sleep (100);

}
Console.WriteLine(" .");

}
}
.

tsk: 1
tsk2: 2
.MyTask() 1
MyTask() 2
.... MyTask() 1,
MyTaskO 2, 0
.... MyTaskO 2,
MyTaskO 1, 1
.... MyTaskO 1,
MyTaskO 2, 2
.... MyTaskO 2,
MyTaskO 1, 3
.... MyTaskO 1,
MyTaskO 2, 4
.... MyTaskO 1,
MyTaskO 2, 5
.... MyTaskO 2,
MyTaskO 1, 6
.... MyTaskO 2,
MyTaskO 1, 7
.... MyTaskO 1,
MyTaskO 2, 8
.... MyTaskO 1,
MyTask 1
MyTaskO 2, 9
MyTask 2
........ .

0
1
2
3
4
5
6
7
8
9


, ,
M a i n ( ) , ,
T h r e a d . S l e e p ( ) . .

892

II. C#

,
, Task.
Wait (),
, .
.
public void W a i t ()

.
Ob j e c t D i s p o s e d E x c e p t i o n .
, Dispose ().
, AggregateException, ,
. ,
.
, , , ,
AggregateException.
, ,
, .
, ,
.
,
Wait () .
Main (), ,
tsk tsk2.
// Wait().
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// , ,
static void MyTaskO {
Console.WriteLine("MyTaskO " + Task.Currentld + " ");
for(int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTaskO #" + Task.Currentld +
", " + count );

}
Console.WriteLine("MyTask " + Task.Currentld + " ");

}
static void Main()

Console.WriteLine(" .");
// .
Task tsk = new Task(MyTask);
Task tsk2 = new Task(MyTask);

24. . : TPL

893

// ,
tsk.Start();
tsk2.Start() ;
Console.WriteLine(" tsk: " + tsk.Id);
Console.WriteLine(" tsk2: " + tsk2.Id);
// Main() ,
// tsk tsk2
tsk.Wait () ;
tsk2 .Wait () ;
Console.WriteLine(" .");

}
}
.

tsk: 1
tsk2: 2
MyTask() 1
MyTask() 2
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2 ,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask() 2,
MyTask() 1,
MyTask 1
MyTask() 2,
MyTask 2
.

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

, Main ()
, tsk ts k 2 . , ,
,
ts k tsk 2 W ait (). ,
ts k 2 , t s k . W ait () -
tsk . tsk 2 . Wait ()
, t s k 2 .

894

II. C#

W a i t ( ) ,
,
W a i t ( ) . .
, .
.
public static void WaitAll(params Task[]

ta sks)

, ,
t a s k s . p a ra m s ,
T a s k
. ,
A g g re g a te E x c e p tio n .
, W a i t A l l () ,
.
tsk.Wait ();
tsk2.Wait ();

Task.WaitAll(tskf tsk2);

,
.
,
, . ,
, W a i t A l l () .
,
, . , W a i t A l l ()
, ,
. ( W a i t ( ) ,
, .)
,
. W a i t ( ) .
.
public static int WaitAny(params Task[]

ta sks)

, ,
t a s k s T a s k
T a s k . , .
.
W a i t A n y () ,
.
Task.WaitAny(tsk, tsk2);

, M a in () , ,
.
W a i t ( ) , W a i t A l l ( )
W a i t A n y ( ) , ,
. (
.)

24. . : TPL

895

D is p o s e ()
Task IDisposable,
Dispose (). .
public void Dispose ()

D ispose () Task, ,
. , , Task,
" " ( ).
, Dispose ().
, ,
.
, , , D ispose ()
. ,
, D ispose (),
, , W ait ().
W ait ( ) , D isp ose () .
D ispose () ,
In v a lid O p e ra tio n E x c e p tio n .
, , ,
, Dispose ()
. ( Dispose ()
.
, ,
.)
- Dispose ()
Task
. D ispose ()
, , . ,
, , Dispose ()
.

T a s k F a c to ry
,
, ,
StartNew (), TaskFactory. T a s kFactory
, .
TaskFactory Factory,
Task. ,
TaskFactory. S t a r t N e w ()
. :
public Task StartNew(Action a ction )

a c t i o n . StartNew ()
Task ,
a c t i o n , . ,
Start () .

896

II. C#

, StartNew ()
ts k .
Task tsk = Task.Factory.StartNew(MyTask);

MyTask ().
StartNew () ,
.
.

-
, ,
: - .
, - .
. -
,
. -
. , -
.
. MyTask ()
-.
// - .
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoLambdaTask {
static void Main() {
Console.WriteLine(" .");
// - .
Task tsk = Task.Factory.StartNew( () => {
Console.WriteLine(" ");
for (int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" " + count );

}
Console.WriteLine(" ");

} );
// tsk.
tsk.Wait();
/ tsk.
tsk.Dispose();

24. . : TPL

897

Console.WriteLine(" .");

}
}
.
.

0
1
2
3
4
5
6
7
8
9

.

- ,
, t s k . D ispose ()
, t s k . W ait ().
, D ispose () .
, t s k . Dispose ()
ts k .W ait ().
, .


TPL
. ,
.
, , C o n t i n u e W i t h (), Task.
:
public Task ContinueWith(Action<Task> _)

_ ,
. Action
Task. , Action,
, .
public delegate void Action<in T>(T obj)

Task.
.
// .
using System;
using System.Threading;

898

II. C#

using System.Threading.Tasks;
class ContinuationDemo {
// , ,
static void MyTaskO {
Console.WriteLine("MyTask() ");
for(int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTaskO " + count )

}
Console.WriteLine("MyTask ");

// , ,
static void ContTask(Task t) {
Console.WriteLine(" ");
for(int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" " + count );

}
Console.WriteLine(" ");

static void Main()

Console.WriteLine(" .");
// .
Task tsk = new Task(MyTask);
/ / .
Task taskCont = tsk.ContinueWith(ContTask);
// ,
tsk.Start () ;
// .
taskCont.Wait();
tsk.Dispose();
taskCont.Dispose();
Console.WriteLine(" .");

}
}
.
.
MyTas ()
MyTaskO 0

24. . : TPL
MyTaskO
MyTaskO
MyTaskO
MyTaskO
MyTask()


1
2
3
4

.

899

1
2
3
4

,
, . , Main ()
. ,
MyTask () Co n t T a s k
. , M y T a s k ()
, , .
, .
.
/ / -.
Task taskCont = tsk.ContinueWith((first) =>

{
Console.WriteLine(" ");
for(int count = 0; count < 5; count++) {
Thread.Sleep (500);
Console.WriteLine(" " + count );

}
Console.WriteLine(" ");

}
);
first (
tsk ).
ContinueWith (), Task ,
, TaskFactory.
ContinueWhenAny () ContinueWhenAll (),
,
.


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

900

II. C#

, ,
T a s k <TResult> Task.
Task:
public Task(Func<TResult> )
public Task(FuncCObject, TResult> , Object )

. ,
Func, Action. Func ,
. ,
, Object,
. .
, S tar t N e w (),
TaskFactory<TResult>
. ,

Task.
public Task<TResult> StartNew(Func<TResult> )
public Task<TResult> StartNew(Func<Object,TResult> , Object )

, , Result
Task, .
public TResult Result { get; internal set;

set ,
, , . ,
,
.

. . , MyTask (),
, true bool. ,
Sum It (), , int,
, .
// .
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// , ,
static bool MyTask() {
return true;

}
// ,
//
static int Sumlt(object v) {
int x = (int) v;
int sum = 0;

24. . : TPL

901

for(; > 0; )
sum += ;
return sum;

}
static void Main()

Console.WriteLine(" .");
// .
Task<bool> tsk = Task<bool>.Factory.StartNew(MyTask);
Console.WriteLine(" MyTask: " +
tsk.Result);
// .
Task<int> tsk2 = Task<int>.Factory.StartNew(Sumlt, 3);
Console.WriteLine(" Sumlt: " +
tsk2.Result);
tsk.Dispose();
tsk2.Dispose ();
Console.WriteLine(" .");

}
}
.
.
MyTask: True
Sumlt: 6
.

T a s k < T R e s u l t >
StartNew<TResult>, .
.

A g g re g a te E x c e p tio n
4.0 .NET Framework ,
, .
.
Task, , StartNew ().

,
, TPL PLINQ.
.

902

II. C#

, , .
.
,
. (
.) , .
,
T hrowIfCanc e l l a t i o n R e q u e s t e d () .
, .
.
' C a n c e l l a t i o n T o k e n ,
.. , S y s t e m .Threading.
C a n c e l l a t i o n T o k e n ,
. -,
IsCancellation Re quested, .
public bool IsCancellationRequested { get;

true,
, false. -,
ThrowIfCancellationRequested (), .
public void ThrowIfCancellationRequested()

, ,
, OperationCanceledException.
.
,
. ,
A g g r e g a t eException,
InnerException InnerExceptions. (
InnerExceptions .
25.)
,
C a n c e l l a t i o n T o k e n S o u r c e ,
System. Threading. ,
C a n c e l l a t i o n T o k e n S o u r c e . (

CancellationTokenSource.) , ,
Token,
.
public CancellationToken Token { get;

, .

.
: ,
. ,
.
I s C a n c e l l a t i o n R e q u e s t e d .
true, , ,

24. . : TPL

903

. ,
. , ,
IsCancellationRequested ,
.
, ThrowIfCancellationRequested (),
, ,
Task,
StartNew ().
.
StartNew ( ) .
public Task StartNew(Action<Object> action, Object ,
CancellationToken _)

,
_ . ,
, , Task.
, Action.
public delegate void Actioncin T>(T ob j)

Object.
o b j Cancel lationToken.
:
, Dispose ().
.
: IsCanceled
Task. true, .
.
.
, T h r o w I f C a n c e l l a t i o n R e q u e s t e d ()
MyTask (). ,
. Is C a n c e l l a tionRequested.
true,
Cancel () ,
T h r o w I f C a n c e l l a t i o n R e q u e s t e d ()
.
// .
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoCancelTask {
// , ,
static void MyTask(Object ct) {
CancellationToken cancelTok = (CancellationToken)

ct;

// , , .
cancelTok.ThrowIfCancellationRequested();

904

II. C#
Console.WriteLine("MyTask() ");
for(int count = 0; count < 10; count++) {
// ,
if(cancelTok.IsCancellationRequested) {
Console.WriteLine(" .");
cancelTok.ThrowIfCancellationRequested();

}
Thread.Sleep(500);
Console.WriteLine(" MyTaskO

" + count );

}
Console.WriteLine("MyTask ");

}
static void Main()

Console.WriteLine(" .");
// .
CancellationTokenSource cancelTokSrc = new CancellationTokenSource();
// , .
Task tsk = Task.Factory.StartNew(MyTask, cancelTokSrc.Token,
cancelTokSrc.Token);
// .
Thread.Sleep(2000);
try {
// .
cancelTokSrc.Cancel();
// Main() ,
// tsk.
tsk.Wait();
} catch (AggregateException exc) {
if(tsk.IsCanceled)
Console.WriteLine(" tsk \");
// :
// Console.WriteLine(exc);
} finally {
tsk.Dispose();
cancelTokSrc.Dispose();

}
Console.WriteLine(" .");

}
}
.
2 .
.
MyTaskO

24. . : TPL
MyTask()
MyTask()
MyTask()
MyTask()

905

0
1
2
3
:.

tsk
.

, M y T a s k ()
M a i n () . ,
M y Task () .
AggregateException, . tsk ,
,
. , , , A g g r e g a t e E x c e p t i o n
, ,
, .
,
A g g regateException.
,
,
.



. . ,
, ,
,
.
A g g r e g a t e
Exception, ,
. Flatten (),
AggregateException
AggregateException. , Handle (),
, AggregateException.

, .
TaskCreationOptions Task
StartNew (). , TaskFactory
FromAsync (),
( Asynchronous Programming Model).
,
TaskScheduler. ,
, .NET Framework.
. ,
.

906

II. C#

P a r a l l e l
, , ,
TPL , Thread.
, TPL
. Parallel,
, :
.
P a r a l l e l , F or ( ) ,
For Each () Invoke (). .
, For () for, ForEach ()
foreach,
. Invoke ()
. ,
,
.
.

In v o k e ()
I nvoke ( ) , Parallel,
, .
, , .
.
public static void Invoke(params Action[] a c tio n s )


Action. , Action .
public delegate void Action()

, , Invoke ()
, , .
a c t i o n s params,
.
Action,
.
Invoke () ,
. , , (
) Wait ().
Wait () . ,
, , ,
. ,
,
, .

Invoke () . MyMeth () MyMeth2 ()
Invoke ().
.

24. . : TPL

907

// Parallel.Invoke() .
using System;
using System.Threading;
using System.threading.Tasks;
class DemoParallel {
// , ,
static void MyMeth() {
Console.WriteLine("MyMeth ");
for (int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyMeth " + count );

}
Console.WriteLine("MyMeth ");

}
// , ,
static void MyMeth2() {
Console.WriteLine("MyMeth2 ");
for(int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyMeth2, " + count );

}
Console.WriteLine("MyMeth2 ");

}
static void Main()

Console.WriteLine(" .");
// .
Parallel.Invoke(MyMeth, MyMeth2);
Console.WriteLine(" .");

}
}
.
.
MyMeth()
MyMeth2()
MyMeth() 0
MyMeth2() 0
MyMeth() 1
MyMeth2() 1
MyMeth() 2
MyMeth2() 2
MyMeth() 3

908

II. C#

MyMeth2() 3
MyMethO 4
MyMeth()
MyMeth2() 4
MyMeth2()
.


: M a i n () ,
Invoke (). , M a i n (),
MyMeth () MyMeth2 (), .
Invoke () , ,
.
,
I n v o k e () .
,
I n v o k e () -.
// Parallel.Invoke() .
// -.
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoParallel {
static void Main()

Console.WriteLine(" .");
// , -.
Parallel.Invoke( () => {
Console.WriteLine(" #1 ");
for(int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" #1 " + count );

}
Console.WriteLine(" #1 ");

},
=> {
Console.WriteLine(" #2 ");
for (int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" #2 " + count );

}
Console.WriteLine(" #2 ");

24. . : TPL

909

Console.WriteLine(" .");

}
}
,
.

F o r ()
TPL , , For (),
Parallel. .
, :
public static ParallelLoopResult
For(int fr o m ln c lu s iv e ,

int to E x c lu s i v e , Action<int> body)

f r o m l n c l u s i v e ,
; , ,
; a t o E x c l u s i v e , .
. ,
f r o m l n c l u s i v e
t o E x c l u s i v e .
, b o d y .
Action<int>, .
public delegate void Action<in T>(T ob j)

For () , , int.
, o b j ,
. , b o d y ,
. For ()
ParallelLoopResult, .
. (
.)
For () , ,
, . , ,
. ,
,
. , , ,
-
, - ,
, .

For () . data,
1000000000 . For (), ""
MyTransf ( ) . ,
data.
. ,
,
- .
.

910

II. C#

1 1 Parallel.F o r ()

// .
using System;
using System.Threading.Tasks;
class DemoParallelFor {
static int[] data;
// , .
// ,
static void MyTransform(int i) {
data[i] = data[i] / 10;
if(data[i]
if(data[i]
if(data[i]
if(data[i]

<
>
>
>

10000)
10000
20000
30000)

data[i] = 0;
& data[i] < 20000) data[i] = 100;
& data[i] < 30000) data[i] = 200;
data[i] = 300;

}
static void Main() {
Console.WriteLine(" .");
data = new int[100000000];
// for.
for (int i=0; i < data.Length; i++) data[i] = i;
// For().
Parallel.F o r (0, data.Length, MyTransform);
Console.WriteLine(" .");

}
}
. , , for
data. ,
For (), data .
,
. F or ()
M y T r a n s f o r m () ,
. ,
,
For () .
, , ,
, . , , ,
,
, . for
For () .
,
, , ,
, ,
.

24. . : TPL

911

fo r,
.
//
/ / for.
using System;
using System.Threading.Tasks;
using System.Diagnostics;
class DemoParallelFor {
static int[] data;
// , .
// ,
static void MyTransform(int i) {
data[i] = data[i] / 10;
if(data[i]
if(data[i]
if(data[i]
if(data[i]

<
>
>
>

1000)
1000
2000
3000)

data[i] = 0;
& data[i] < 2000) data[i] = 100;
& data[i] < 3000) data[i] = 200;
data[i] = 300;

}
static void Main()

Console.WriteLine(" .");
// Create Stopwatch
// .
Stopwatch sw = new Stopwatch ();
data = new int[100000000];
// ,
sw.Start ()';
// .
Parallel.F o r (0, data.Length, (i) => data[i] = i );
sw.Stop () ;
Console.WriteLine(" : " +
"{0} ", sw.Elapsed.TotalSeconds);
sw.Reset () ;
sw.Start () ;
// ,
for(int i=0; i < data.Length; i++) data[i] = i;
sw.Stop ();
Console.WriteLine(" :
"{0} ", sw.Elapsed.TotalSeconds);
Console.WriteLine() ;

" +

912

II. C#
// ,
sw.Start();
// .
Parallel.F o r (0, data.Length, MyTransform);
sw.Stop();
Console.WriteLine(" : " +
"{0} ", sw.Elapsed.TotalSeconds);
sw.Reset () ;
sw.Start();
// ,
for(int i=0; i < data.Length; i++) MyTransform(i);
sw.Stop ();
Console.WriteLine(" : " +
"{0} ", sw.Elapsed.TotalSeconds);
Console.WriteLine(" .");

}
}

.
.
: 1.0537757
: 0.3457628
: 4.2246675
: 5.3849959
.

, ,
,
. ,
,
, . ,
,
.
.

, ,
, Microsoft.
, ,
,
.

24. . : TPL

913

,
. -, ,
-,
.
Parallel.F o r (0, data.Length,

(i) => data[i] = i );

"" -. (, .) ,
For () .
-, S t o p w a t c h
. System.
Diagnostics. ,
, Start (), ,
Stop (), . Reset ()
.
.
Elapsed, TimeSpan.
TotalSeconds ,
. , Stopwatch
.
, F o r ()
ParallelLoopResult. , .
public bool IsCompleted { get; }
public Nullable<long> LowestBreaklteration { get;

I s C o m p l e t e d true,
. ,
true.
, false.
L o w e s t B r e a k l t e r a t i o n
,
P a r a l l elLoopState.B r e a k ().
ParallelLoopState
For (),
. For () .
public static ParallelLoopResult For(int fr o m ln c lu s iv e , int to E x c lu s i v e ,
Action<int, ParallelLoopState> body)

Action, ,
.
public delegate void Action<in Tl, in T2>(T a r g l, T2 arg2)

For () Tl int,
2 ParallelLoopState. , Action
, 2 .
Break (),
P a r a l l e l L o o p S t a t e ,
body. Break () .
public void Break()

914

II. C#

Break ()
,
Break (). Break ()
. , ,
. , 10 , ,
1 0 1 0 .
, For (),
. , ,
.
,
.

B r e a k () , For ( ) .
, ,
M y Transform () ParallelLoopState
, Brea k ()
. ,
, data M a i n ().
. I sCompleted
false, data
. , .
( ,
, :
.)
// ParallelLoopResult ParallelLoopState,
/ Break() For() .
using System;
using System.Threading.Tasks;
class DemoParallelForWithLoopResult {
static int[] data;
// , .
// ,
static void MyTransform(int i, ParallelLoopState pis) {
// ,
if(data[i] < 0) pis.Break();
data[i] = data[i] / 10;
if(data[i]
if(data[i]
if(data[i]
if(data[i]

<
>
>
>

1000)
1000
2000
3000)

data[i] = 0;
& data[i] < 2000) data[i] = 100;
& data[i] < 3000) data[i] = 200;
data[i] = 300;

}
static void Main()

24. . : TPL

915

Console.WriteLine(" .");
data = new int[100000000];
// .
for(int i=0; i < data.Length; i++) data[i] = i;
// data,
data[1000] = -10;
// .
ParallelLoopResult loopResult = Parallel.F o r (0, data.Length, MyTransform);
// , ,
i f (!loopResult.IsCompleted)
Console.WriteLine("\ - , " +
" \" +
" " +
loopResult.LowestBreaklteration + ".\n");
Console.WriteLine(" .");

}
}
, ,
.
.
- ,
1000
.

,
1000 . , Break ()
MyTransform ()
.
For ()
.
, long int
. For (),
, , , ,
.
, : ,
For (), ,
,
Stop (), Break ().

F o rE a c h ()
ForEach (),
foreach. ForEach ().
:

916

II. C#

public static ParallelLoopResult


ForEach<TSource>(IEnumerable<TSource> so u r c e ,
Action<TSource> body)

s o u r c e , , a b o d y ,
.
, , ( 25)
IEnumerable<T>. ,
b o d y ,
, .
.