The
Complete
Reference
C# 4.0
HERBERT SCHILDT
Learn more.
Do more.
MHPROFESSIONAL.COM
C# 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.
Authorized translation from the English language edition published by McGraw-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
23
25
I. #
29
1. C#
31
2. C#
41
3. ,
67
4.
97
5.
121
6. ,
147
7.
177
8.
209
9.
269
10.
303
11.
329
12. ,
375
13.
403
14. -
431
15. , -
473
16. ,
513
17. ,
537
18.
575
19. LINQ
637
20. , ,
II. C#
681
717
21. System
719
22.
783
23. . :
833
24. . : TPL
885
25. ,
26.
.
923
1011
1039
1044
22
22
23
25
27
27
27
27
28
28
I. C#
29
1. C#
C#
C++
Java
C#
C#
# .NET Framework
NET Framework
CLR
31
32
32
33
33
34
36
37
37
38
38
39
2. C#
-
csc.exe
Visual Studio
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
9
117
117
119
119
5.
if
if
if-else-if switch
switch
for
for
while
do-while
foreach
break
continue
return
goto
121
121
122
124
125
129
129
131
137
138
139
139
142
143
143
6. ,
Building
Building
Building
new
new
" "
this
147
147
148
149
153
154
155
156
158
159
162
164
166
166
168
169
170
170
171
172
174
7.
177
177
10
Length
Length
foreach
switch
8.
ref out
ref
out
ref out
this
Main()
Main()
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
11
255
257
260
265
266
9.
C#
true false
269
270
270
273
277
281
283
286
286
10.
303
303
304
307
310
311
313
318
319
320
320
324
11.
base
329
329
333
336
337
339
343
344
346
349
351
288
292
297
298
12
sealed
object
object
355
359
360
363
367
368
370
372
12. ,
.NET Framework
375
375
377
381
383
385
387
388
388
391
391
391
395
397
399
399
399
13.
System.Exception
try catch
""
catch
try
finally
Exception
403
404
404
404
405
407
408
410
411
412
413
414
415
416
418
420
checked unchecked
13
422
426
428
14. -
- C#
Stream
-
-
ReadKey()
FileStream -
-
FileStream
-
StreamWriter
StreamReader
BinaryWriter
BinaryReader
-
MemoryStream
StringReader StringWriter
File
()
Exists() GetLastAccessTime()
431
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. , -
473
473
476
477
478
481
14
System.Delegate
-
-
-
-
-
.NET Framework
EventHandler<TEventArgs> EventHandler 508
16. ,
using
using
::
#define
#if #endif
#else #elif
#undef
#error
#warning
#line
#region #endregion
#pragma
internal
483
483
483
484
484
485
486
488
488
489
492
494
496
497
500
504
504
506
509
513
513
514
516
518
520
521
523
524
524
528
529
529
531
533
533
534
534
534
534
535
internal
15
536
17. ,
is
as
typeof
System.Type
AttributeUsage
Conditional
Obsolete
537
537
538
539
540
541
541
543
544
548
550
555
560
562
563
566
570
570
571
572
18.
new()
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
LINQ
626
626
630
633
635
636
637
638
where
orderby
select
639
641
642
643
644
646
649
from
group
653
655
into
let
join
657
659
660
663
666
,
:
669
669
670
673
673
675
676
678
PLINQ
680
17
20. , , 681
unsafe
fixed
??
,
lock
readonly
const volatile
using
extern
II. C#
21. System
System
Math
.NET,
Decimal
Char
Boolean
Array
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
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>
766
767
768
769
771
773
774
776
777
778
778
779
779
781
781
22.
C#
String
String
, String
String
,
Substring()
String
String.Format() ToString()
String.Format()
ToString()
-
783
783
784
784
785
786
808
810
811
811
812
812
812
814
815
23. . :
833
834
816
816
819
820
820
824
827
829
830
Thread
IsBackground
Monitor
Wait(),
Pulse() PulseAll()
Wait() Pulse()
MethodImplAttribute
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
cookie-
LastModified
MiniCrawler
WebClient
21
1006
1008
1009
1011
1012
1013
1014
1015
1017
1018
1018
1021
1021
1022
1022
1022
1024
1025
1026
1027
1029
1030
1034
.
XML-
XML
1039
1039
1041
1041
1044
(Herbert Schildt)
#, C++, Java.
. ,
Java, C++, (
"" 2007 2008 .).
,
, ,
.
.
. , -
www.HerbSchildt.com.
(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 ( ).
,
, ,
, www.mhprofessional.com.
28
"" ,
. ,
.
Java .
Java ( " ", 2007 .)
Java: ( " ", 2008 .)
SWING: ( "", 2007 .)
Java ( "", 2005 .)
Java. ( "", 2008 .)
C++
.
C++ ( "", 2007 .)
C++. ( "", 2005 .)
STL Programming From the Ground Up
++
++. ( "", 2009 .)
,
,
( "", 2007 .)
, , .
, ,
.
, .
.
, Web-
. , ,
, ,
.
, ,
.
.
:
E-mail:
info@williamspublishing.com
WWW:
http://www.williamspublishing.com
:
:
:
127055, . , . , . 43, . 1
03150, , /152
C#
I
#, ,
.
, #,
- .
1 C#
2
C#
3 ,
4
5
6 ,
7
8
9
10
11
12 ,
13
14
-
15 ,
16
,
17
,
18
19 LINQ
20
, ,
C#
C#
.NET
Microsoft.
,
.
, ,
XXI .
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
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
C++
Java
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 #.
NET Framework
.NET Framework
.
, ,
Windows.
#, .NET Framework
. (Common
Language Runtime CLR). , .
CLR .NET Framework
,
.
38
I. C#
.NET Framework .
. ,
-, - ,
.NET. ,
, .
, , , .
, .NET,
,
.NET. C# .NET ,
# .NET
Framework.
CLR
CLR .NET.
. C# ,
, , Microsoft Intermediate Language,
MSIL ( Microsoft). MSIL
, . , MSIL
. , , , ,
MSIL - Java, .
CLR
. , ,
MSIL, , CLR.
.NET Framework.
MSIL JIT-.
JIT
. .
CLR JIT-,
MSIL
. , C#
, , MSIL.
, , ,
,
MSIL.
MSIL, #
, , ,
.
, MSIL.
, C#
. ,
CLR, ,
. :
1. C#
39
MSIL,
CLR, .NET,
#. , ,
,
, ,
.
, CLR.
, .NET Framework Windows
. ,
, , #
,
- .
, CLR ,
,
, (Common
Language Specification CLS),
.NET- . CLS
, . CLS
(Common Type System CTS),
, . , C#
CLS, CTS.
C#
,
.
, .
C# .
#,
#,
. ,
#.
,
,
I.
C# -
().
#, C#
-
.
,
#.
.
42
I. #
, , ,
. , , ,
. ,
.
,
,
.
, , , 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, -, csc..
.
2. C#
45
csc.
, ,
Visual Studio,
, ,
,
. ,
. ,
, .
, (Command Prompt)
Windows,
,
.
, ,
Visual Studio.
C# - ,
, .
C#
.
1. , .
2. csc..
3. .
, ,
www.mhprofessional.com.
.
, Notepad. ,
, , ,
, ,
#. ,
Example.cs.
C#
csc., .
:\>csc Example.cs
csc Example., MSIL
. MSIL ,
.. CLR
JIT- Example.. , ,
, Example. (
46
I. C#
, MSIL) , .NET
Framework , ,
CLR.
csc.,
, Visual Studio. Visual Studio
Visual
Studio
Visual
Studio
(Visual
StudioVisual
Studio ToolsVisual Studio Command Prompt) (StartAII
Programs) Windows. ,
, vsvars32.bat,
Visual Studio.
.
:\>ml
.
#.
Visual Studio
Visual Studio ,
Microsoft. ,
, #,
. Visual Studio
, .
,
, , ,
.
,
C# Visual Studio 2010.
, Visual
Studio 2010 Professional. Visual Studio
.
1.
() #,
(FileNewProject). Windows
(Installed Templates) (Empty Project),
.
, .
2. C#
47
, .
2.
Visual Studio ,
.
Project1 - Microsoft Visual Studio
Debug
Create
"Project1" (: 1)
Project1
...
- (Solution Explorer)
,
(ViewSolution Explorer).
48
I. C#
3. ,
#.
( Project1) ,
(Add) . ,
.
4.
(New Item),
(Add New Item). (Code)
,
(Code File) Example.cs, .
2. C#
5.
49
, .
, .
6. Example.cs,
. ( ,
, www.mhprofessional.com,
.)
, .
50
I. #
7. ,
(BuildBuild Solution).
8. , (DebugStart
Without Debugging). ,
.
,
.
.
#. .
.
.
.
, , Visual Studio
,
. ,
.
.
, Visual Studio.
Example.cs ,
, #.
, .
, Java,
, C#
.
Example.cs, , C#
. ,
Sample.cs, Test.cs X.cs.
2. C#
51
C# .cs,
. ,
,
.
Example.cs. C# ,
,
. .
, .
/*
C#.
Example.cs.
*/
.
, C#
. . ,
,
, .
, Example.cs.
,
.
C# .
.
/* */. ,
, .
, .
.
using System;
, System.
C# .
, .
.
, , ,
, .
System, ,
.NET Framework, #.
using ,
. (
, ,
.)
.
class Example {
class
. ,
#, a Example .
({) (}). ,
, .
52
I. #
, , C# ,
, .
.
// C# Main().
, #.
//.
,
,
. ( , #,
.)
.
static void Main() {
Main(). , C#
. , ,
. C#
Main().
,
#. ,
, .
static. ,
static, .
, Main() .
void , Main() .
, .
Main ,
. Main() ,
.
{, Main(). ,
, .
. ,
Main().
Console.WriteLine(" #.");
"
C#. WriteLine().
WriteLine() , .
, , . ,
WriteLine() .
Console ,
- . Console WriteLine()
, WriteLine() Console.
C#
- .
, , WriteLine(),
, , ,
using System. , C# .
, {
2. C#
53
}.
.
.
} Main(),
Example.
, C# .
. ,
main Main writeline WriteLine,
. , C#
, Main(), .
Main,
, , Example.
.
,
( ) ,
.
.
,
. , - ,
.
, ,
.
,
, . C#
- , .
, ,
.
Main()
csc. (
Visual
Studio.)
EX1.CS(12, 21) : CS1002: ;
1.CS(13, 22) : CS1519: '('
,
EX1.CS(15, 1) : CS1022:
, ,
, .
.
,
, ,
.
54
I. C#
. ,
, ,
.
, .
, , .
using System;
. , C#
,
. ,
Console.WriteLine(" #.");
.
System.Console.WriteLine(" #.");
, .
// "using System;".
class Example {
// C# Main().
static void Main() {
// Console.WriteLine .
System.Console.WriteLine(" #.");
}
}
System ,
, ,
C# using System ,
, . , ,
, , ,
.
, , ,
. ,
. ,
. ,
.
.
2. C#
55
// .
using System;
class Example2 {
static void Main() {
int x; //
int ; //
= 100; // 100
Console.WriteLine(" " + );
= / 2;
Console.Write(" / 2: ");
Console.WriteLine(y);
}
}
.
100
/ 2: 50
. ,
int ; //
. C#
. ,
, . .
, .. .
C#
int. ,
int.
.
int ; //
, , ,
, .
, :
_;
, _
. int, C# .
100.
= 100; // 100
C# (=).
,
, , .
56
I. C#
" " .
Console.WriteLine(" " + );
+ ,
. ,
+
WriteLine().
, 2.
= / 2;
2,
. ,
50. .
, C#
, .
+
*
.
Console.Write(" / 2: ");
Console.WriteLine();
. -,
" / 2: " Write().
. ,
. Write()
WriteLine(), ,
. -, ,
WriteLine() . , Write()
WriteLine(),
C# .
,
.
. . ,
.
int , ; //
C# , .
,
. 3.
2. C#
57
int.
int .
, . , int
18, 18,3. , int
, #. ,
, C# : float double.
.
double.
double
double result;
result double. result
,
, , , 122,23, 0,034 -19,0.
int double
.
/*
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: " + ivar);
Console.WriteLine(" dvar: " + dvar);
Console.WriteLine(); //
// 3.
ivar = ivar / 3;
dvar = dvar / 3.0;
Console.WriteLine(" ivar : " + ivar);
Console.WriteLine(" dvar : " + dvar);
}
}
.
ivar: 100
dvar: 100
58
I. C#
ivar : 33
dvar : 33.3333333333333
, ivar int 3
33, .
dvar double 3 .
,
. ,
100 # , 100,0 .
.
WriteLine() .
, . ,
, 3,1416 "".
// .
using System;
class Circle {
static void Main() {
double radius;
double area;
radius = 10.0;
area = radius * radius * 3.1416;
Console.WriteLine(" " + area);
}
}
.
314.16
,
, .
(.. )
, .. .
,
#.
, ,
.
if C#
. if C# ,
IF . ,
2. C#
59
if , C++ Java.
.
if() ;
, .. , ,
: "" "". ,
. , ,
. .
if(10 < 11) Console.WriteLine("10 11");
,
10 11, WriteLine() .
.
if(10 < 9) Console.WriteLine(" ");
10 9. , WriteLine()
.
C# ,
. .
<
<=
>
>=
==
!=
,
if.
// 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.WriteLine();
c = a - b; // -1
60
I. #
Console.WriteLine(" -1");
if( >= 0) Console.WriteLine(" ");
if( < 0) Console.WriteLine(" ");
Console.WriteLine();
= b - ; // 1
Console.WriteLine(" 1");
if( >= 0) Console.WriteLine(" ");
if( < 0) Console.WriteLine(" ");
}
}
.
b
-1
1
.
int , b, ;
, , b , , .
,
, , .
. C#
. for. if,
for C# , C++ Java.
.
for(; ; ) ;
.
, .
, . ,
.
, .
, for.
// for.
using System;
class ForDemo {
2. C#
61
0
1
2
3
4
count .
for
. , , count < 5.
, ,
WriteLine(). 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.WriteLine("j / i " + d);
}
}
}
.
i
j / i 2
if ,
. , if, ,
.
i, , .
,
1 10.
// 1 10.
using System;
2. C#
63
class ProdSum {
static void Main() {
int prod;
int sum;
int i;
sum = 0;
prod = 1;
for(i=1; i <= 10; i++) {
sum = sum + i;
prod = prod * i;
}
Console.WriteLine(" " + sum);
Console.WriteLine(" " + prod);
}
}
.
55
3628800
.
.
:
. , { }, ,
.
, ,
,
.
C# . ,
.
,
, . ,
.
.
#
.
. , C#
= ;
= + 1;
Console.WriteLine( + " " + );
,
= ; = + 1; Cons1.WriteLine( + " " + );
64
I. C#
, .
, C# .
Console.WriteLine(" " +
+ + z +
" ");
,
.
.
, ,
. C#
. ,
.
,
. ,
.
( )
.
, .
C#
,
, . C#
: .
, .
.
. ,
. 4.0 # 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
protected
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
join
select
yield
get
let
set
global
orderby
value
C# , ,
.
.
.
, .
, , , line_count.
, , , max__value,
. C#
. , myvar MyVar .
.
Test
up
x
_top
2
my_var
MaxLoad
sample23
, . , 12
.
, .
, C#
@ . , @for
.
for, @ .
, @.
// @.
using System;
class IdTest {
static void Main() {
int @if; // if
66
I. C#
//
for(@if = 0; @if < 10; @if++)
Console.WriteLine("@if " + @if);
}
}
, @if
.
@if
@if
@if
@if
@if
@if
@if
@if
@if
@if
0
1
2
3
4
5
6
7
8
9
, @
, . , @
,
.
.NET Framework
, ,
: WriteLine() 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
sbyte
8
short
16
ushort 16
int
32
uint
32
long
64
ulong
64
0-255
-128-127
-32 768-32 767
0-65 535
-2 147 483 648-2 147 483 647
0-4 294 967 295
-9 223 372 036 854 775 808-9 223 372 036 854 775 807
0-18 446 744 073 709 551 615
, C#
: .
. , ,
C# ,
. , 0,
, 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
I. C#
,
int. int
, .
,
int, . ,
, uint,
long,
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 + " .");
}
}
.
: 5892480000000 .
, int
uint.
byte sbyte. byte
0 255. byte
,
, .
sbyte. ,
byte ,
1 100.
// byte.
using System;
class Use_byte {
static void Main() {
byte x;
int sum;
sum = 0;
3. ,
71
. #
: float double.
.
, float 32 ,
5-45 3,4+38. double
64 , 5-324
1,7+308.
# 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 = Math.Sqrt(area / 3.1416);
Console.WriteLine(" " + r);
}
}
72
I. C#
.
1.78412203012729
Sqrt(). , Sqrt() Math,
Math .
Console WriteLine() .
, , ,
.
, 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 +
" " + Math.Sin(theta));
Console.WriteLine(" " + theta +
" " + Math.Cos(theta));
Console.WriteLine(" " + theta +
" " + Math.Tan(theta));
Console.WriteLine();
}
}
}
.
0.1 0.0998334166468282
0.1 0.995004165278026
0.1 0.100334672085451
0.2 0.198669330795061
0.2 0.980066577841242
0.2 0.202710035508673
0.3 0.29552020666134
0.3 0.955336489125606
0.3 0.309336249609623
,
Math.Sin(), Math.Cos() Math.Tan().
Math.Sqrt(),
double .
.
3. ,
73
, C#
decimal, .
128 1-28
7,9+28. , , ,
.
decimal,
28 ( 29) .
,
, .
, decimal
.
.
// 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.WriteLine(" : $" + discounted_price);
}
}
.
: $16.9575
, decimal
m. ,
m
, decimal.
decimal m, 10. (
.)
decimal.
.
/*
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.WriteLine(" : $" + amount);
Console.WriteLine(" : " + rate_of_return);
Console.WriteLine(" " + years + " ");
for(i = 0; i < years; i++)
amount = amount + (amount * rate_of_return);
Console.WriteLine(" $" + amount);
}
}
.
: $1000
: 0.07
10
$1967.151357289565322490000
,
, ..
, ! ,
"" .
C# 8- ,
, C++, 16- ,
(Unicode). ,
.
, , ,
, , ,
,
8- . C# char,
16- 0 65 535.
8- ASCII
0 127. , ASCII -
#.
,
(.. ) . ,
ch X.
3. ,
75
char ch;
ch = 'X';
char WriteLine().
, ch.
Console.WriteLine(" ch : " + ch);
char C# ,
. , C#
.
, .
char ch;
ch = 88; // ,
, 88
, .
.
, ,
.
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.WriteLine(".");
b = false;
if (b) Console.WriteLine("He .");
76
I. C#
//
// .
Console.WriteLine("10 > 9 " + (10 > 9));
}
}
.
b False
b True
.
10 > 9 True
. -, bool
WriteLine() "True" "False". -,
bool if.
, , if .
if(b == true) ...
-,
. 10 > 9
"True." , 10 > 9 ,
+ , >.
WriteLine()
, . .NET Framework
,
. -
,
. ,
WriteLine().
. , , ,
, ,
.
+, .
Console.WriteLine(" " + 2 +
" $" + 3 + " .");
, ,
. ,
.
Console.WriteLine(" 10/3 : " + 10.0/3.0);
.
10/3 : 3.33333333333333
3. ,
77
,
. ,
.
WriteLine(), ,
.
WriteLine(" ", arg0, arg1, ... , argN);
WriteLine() , +.
: ,
, .
:
{argnum, width: fmt}
argnum , ; width
; fmt . width fmt .
, ,
argnum. ,
. width fmt . ,
. , {0} arg0,
{1} arg1 ..
.
Console.WriteLine(" {0} {1} .", 28, 29);
.
28 29
, 28 {0}, 29
{1}. ,
, (
28 29). , ,
, +.
,
.
Console.WriteLine(" {0,10} {1,5} .", 28, 29);
.
28
29 .
, . ,
width. ,
.
, , ,
. ,
.
.
78
I. C#
// .
using System;
class DisplayOptions {
static void Main() {
int i;
Console.WriteLine("\t\t");
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.WriteLine(" 10/3 : (0:#.##)", 10.0/3.0);
.
10/3 : 3.33
#.## WriteLine()
. , , ,
WriteLine() ,
.
.
Console.WriteLine("{0:###,###.##}", 123456.56);
.
123,456.56
, ,
.
3. ,
79
decimal balance;
balance = 12323.09m;
Console.WriteLine(" {0:}" , balance);
,
.
$12,323.09
,
.
//
// .
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:}", discounted_price);
}
}
.
: 16,96 .
C# ,
. , 100 .
,
.
.
# .
. ,
. , '' '%' .
. ,
10 -100 .
. ,
11.123 .
C# .
80
I. C#
, C#
. :
, 2,123987 0.23? ,
C# .
-,
, , int. ,
: int, uint, long
ulong . -,
double.
,
. , long
l L. , 12 int, a 12L
long.
u 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, short ushort, ,
.
, , ,
16, 10.
16 . 0 9,
F, 10, 11, 12, 13,
14 15. , 16 10.
, C#
. 0,
.. "".
.
count = 0xFF; // 255
incr = 0x1; // 26
,
, ,
. , ,
, #,
3. ,
81
. C#
,
(. 3.2). ,
.
3.2.
\a
\b
\f
\n
\r
\t
\v
\0
\'
\"
\\
()
( )
( )
, ch
.
ch = '\t';
ch
.
ch = '\'';
# .
, .
:
" "
.
.
,
, .
,
\n \t.
//
// .
using System;
class StrDemo {
static void Main() {
82
I. C#
Console.WriteLine(" \n \n ");
Console.WriteLine("\t\t");
Console.WriteLine("\t\t");
// .
Console.WriteLine("\"3?\", .");
}
}
.
"?", .
,
\n.
WriteLine()
\n
( ),
. ,
.
,
. @,
.
. ,
, ,
.
("),
("").
.
// .
using System;
class Verbatim {
static void Main() {
Console.WriteLine(@"
,
.
");
Console.WriteLine(@" :
1 2 3 4
5 6 7 8
");
Console.WriteLine(@" : "" #.""");
}
}
.
3. ,
83
,
.
:
1
2
3
4
5
6
7
8
: " #."
,
, .
,
,
. ,
.
, ,
.
, .
: . ,
'X', char. ,
, "X", - .
:
_;
, ; _
. ,
. ,
. , bool
. ,
. , int
char.
C# .
, , ,
,
. #.
# . ,
, ,
.
, ,
, . ,
.
(=) .
:
84
I. C#
_ = ;
, .
.
.
int count = 10; // 10 count.
char ch = ' X ' ; // ch X.
float f = 1.2F // f 1,2.
,
, , , .
int , b = 8 , = 19, d; // b
b .
, C#
,
.
.
// .
using System;
class DynInit {
static void Main() {
// ,
double s1 = 4.0;
double s2 = 5.0;
// hypot ,
double hypot = Math.Sqrt( (s1 * s1) + (s2 * s2) );
Console.Write(" " +
s1 + " " + s2 + " ");
Console.WriteLine("{0:#.###}.", hypot);
}
}
.
4 5 6.403
: s1, s2 hypot.
(s1 s2) , (hypot)
.
, Math.Sqrt().
, ,
. Math.Sqrt() (
) ,
3. ,
85
hypot.
, ,
,
, .
, C# .
, , int bool,
. C# 3.0,
, ,
. .
var
.
, .. ,
. .
var = 2.7183;
, double,
double. :
var = 2.7183F;
float.
.
, ,
.
// .
using System;
class ImplicitlyTypedVar {
static void Main() {
// .
// double,
// double.
var s1 = 4.0;
var s2 = 5.0;
// , hypot
// double, ,
// Sqrt(), double.
var hypot = Math.Sqrt( (s1 * s1) + (s2 * s2) );
Console.Write(" " +
s1 + " by " + s2 + " ");
Console.WriteLine("{0:#.###}.", hypot);
// ,
86
I. #
// s1 double
// .
// s1 = 12.2; // !
}
}
, .
, -
.
.
// s1 = 12.2; // !
, s1
double. , .
,
, . ,
. , , ,
s1 .
C# ,
. ,
,
(LINQ),
19. ,
,
.
:
.
var s1 = 4.0, s2 = 5.0; // !
.
, s1 s2, .
, ,
Main(). C#
. 2,
.
. , ,
, .
, ,
.
.
C# ,
. ( )
, .
,
.
3. ,
87
, ,
.
, , .
, ,
, . ,
,
. ,
.
. , ,
, , .
. ,
, ,
. :
, , .
,
.
// .
using System;
class ScopeDemo {
static void Main() {
int x; // Main().
= 10;
if(x == 10){
//
int = 20; // .
// , .
Console.WriteLine(" : " + + " " + );
= * 2;
}
// = 100; // ! .
// - .
Console.WriteLine(" " + );
}
}
,
Main(),
. if
.
,
. line = 100;,
, .
(//), ,
.
if, ,
88
I. C#
, ,
.
,
. ,
,
. , , ,
, .
,
, .
.
// .
using System;
class VarInitDemo {
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 for. ,
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 ,
for, , . C++
.
C# ,
, .
. ,
int float.
int i;
float f;
i = 10;
f = i; // float
,
, .
i float,
f.
# , ,
. , bool int .
, -
. , ,
. ,
.
90
I. #
,
:
;
, .
, .
, 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 ,
double long ,
. ,
.
// *** . ***
using System;
class LtoD {
static void Main() {
long L;
double D;
D = 100123285.0;
L = D; // !!!
Console.WriteLine("L D: " + L + " " + D);
}
}
,
decimal float double, char
bool. , char bool .
3. ,
91
,
,
.
.
.
. .
(_)
_ ,
. .
double , ;
/ int,
.
(int) ( / )
double,
/ int .
/ ,
int ,
. ,
double int .
,
. , long int
, long
int,
.
, . ,
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;
// 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.WriteLine("b 257: " + b +
" -- .");
Console.WriteLine();
// uint short .
u = 32000;
s = (short) u;
Console.WriteLine("s 32000: " +
s + " -- .");
// uint short ,
u = 64000;
s = (short) u;
Console.WriteLine("s 64000: " +
s + " -- .");
Console.WriteLine();
// long uint .
l = 64000;
u = (uint) l;
Console.WriteLine ("u 64000: " + u +
" -- .");
// long uint .
l = -12;
u = (uint) l;
Console.WriteLine(" -12: " + u +
" -- .");
Console.WriteLine();
// int char,
b = 88; // ASCII X
ch = (char) b;
Console.WriteLine("ch 88: " + ch);
}
}
.
/ : 3
b 255: 255 -- .
3. ,
93
b 257: 1 -- .
s 32000: 32000 -- .
s 64000: -1536 -- .
u 64000: 64000 -- .
u -12: 4294967284 -- .
ch 88: X
. /
int , , .
b 255, ,
byte.
b 257, ,
byte.
, int
byte .
s short 32 000
uint, ,
short.
64 000,
short, .
, uint short .
u 64 000 l long.
, 64 000
uint. u
-12, ,
uint.
, long uint .
, char byte,
, .
,
. ,
. ,
short long, .
,
.
C#
. ,
.
decimal,
decimal ( float double,
).
94
I. C#
double,
double.
float,
float.
ulong,
ulong ( sbyte, short, int long,
).
long,
long.
uint, sbyte, short int,
long.
uint,
uint.
int.
. -, . ,
float double decimal , , ,
ulong .
.
-, .
: ,
int. , char, sbyte, byte, ushort
short int .
. ,
int.
,
, . ,
byte int ,
- byte.
.
. ,
, byte,
. byte int.
, int. ,
, byte, int.
, .
.
// !
using System;
class PromDemo {
static void Main() {
byte b;
b = 10;
3. ,
95
b = (byte) (b * b); // !!
Console.WriteLine("b: "+ b);
}
}
, b*b
b, byte!
, b*b b int
byte .
,
, , , .
. ,
char, ch1 ch2 int.
char ch1 = 'a', ch2 = 'b';
ch1 = (char) (ch1 + ch2);
ch1 ch2
int, char.
,
. , int(byte,
sbyte, short ushort), .. ,
int. char. ,
uint,
long.
.
. ,
1 10
. ,
, Math.Sqrt(), int.
// .
using System;
class CastExpr {
static void Main() {
double n;
for(n = 1.0; n <= 10; n++) {
Console.WriteLine(" {0} {1}",
n, Math.Sqrt(n));
Console.WriteLine(" : (0)",
(int) Math.Sqrt(n));
Console.WriteLine(" :(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
, , Math.Sqrt(),
int . ,
Math.Sqrt(n) - (int) Math.Sqrt(n)
int ,
, . ,
double. int ,
Math.Sqrt().
C# ,
. #
: , ,
.
. , C#
,
,
-.
, .
,
#, .
+
*
/
%
++
98
I. C#
+, -, * / , .
.
,
. , ,
/ , ; ,
10/3 3.
(%),
. .
, 10 % 3 1. C# %
, . 10.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.WriteLine("
iresult + "
Console.WriteLine("
dresult + "
"
"
10/3: " +
+ irem);
10.0 / 3.0: " +
+ drem);
}
}
.
10 / 3: 3 1
10.0 / 3.0: 3.33333333333333 1
, , % ,
, 1.
(++) (--) 2.
, .
.
1,
1. ,
++;
4.
99
= x + 1;
--;
= - 1;
, , ,
, .
.
(
) ( ). ,
= + 1;
:
++; //
:
++; //
( )
.
, .
,
.
,
.
.
= 10;
= ++;
11,
1,
.
= 10;
= ++;
10,
, 1.
11. ,
11:
.
. ,
.
//
// (++).
100
I. #
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();
x = 1;
= 0;
Console.WriteLine(" , " +
" = + ++;");
for(i = 0; i < 10; i++) {
= + ++; // ++
Console.WriteLine( + " ");
}
Console.WriteLine();
}
}
.
, = + ++
1
3
6
10
15
14
21
28
36
45
55
, = + ++;
2
5
9
14
20
4.
101
27
35
44
54
65
,
= + ++;
,
.
1.
= + ++;
1,
,
. ,
++ ++
.
:
, :
+ ++x
, .
,
1 .
, ,
"" "".
,
.
.
.
==
!=
>
<
>=
<=
, .
102
I. #
&
|
^
&&
||
!
bool.
, ,
== !=. <, >, <= >=
, .
, .
bool ,
(true) (false) . ,
true > false C# .
bool,
bool.
&, |, ^ ! , ,
.
p
false
true
false
true
q
false
false
true
true
p & q
false
false
false
true
p | q
false
true
true
true
p ^ q
false
true
true
false
!P
true
false
true
false
,
(true),
true.
,
.
//
// .
using System;
class RelLogOps {
static void Main() {
int i, j;
bool b1, b2;
i = 10;
j = 11;
if(i < j) Console.WriteLine("i < j");
if(i <= j) Console.WriteLine("i <= j");
if(i != j) Console.WriteLine("i != j");
4.
103
q
true
false
false
true
p q
true
false
true
true
! |, .
! | 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)
<
j
p
p
q
q
2; i++) {
< 2; j++) {
= true;
= false;
= true;
= false;
C# , ,
, .
.
(false),
.
(true),
.
,
.
&&,
||.
& |.
,
.
.
: d
n . n/d , n d .
4.
105
,
.
// .
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);
}
}
- if
: d. ,
,
. ,
d 2, .
, ,
, . ,
, .
, .
,
.
? ,
- .
.
// .
using System;
class SideEffects {
static void Main() {
int i;
bool someCondition = false;
i = 0;
106
I. C#
// i ,
// , if .
if(someCondition & (++i < 100))
Console.WriteLine("He ");
Console.WriteLine(" if : " + i); // 1
// i ,
// .
if(someCondition && (++i < 100))
Console.WriteLine("He ");
Console.WriteLine(" if : " + i); // - 1 !!
}
}
, someCondition bool
false. if.
, if
i , someCondition
false. &,
if,
. if
. i
, ( someCondition) false,
, .
:
,
, #.
:
,
.
(=). #
,
. .
_ =
_ .
,
: .
, , .
int , , z;
= = z = 100; // 100 , z
100
, z .
z, , , .
" "
.
4.
107
C# ,
.
.
= + 10;
, .
+= 10;
+= ,
, 10.
.
= - 100;
x -= 100;
.
, 100.
, .. ,
, .
;
_ =
,
.
.
+=
%=
-=
&=
*=
|=
/=
^=
,
.
.
. , , "" . -,
,
.
, #.
C# , ,
#.
() .
, bool, float
double.
108
I. C#
, ,
, .
, , ,
. C# . 4.1.
4.1.
&
1 ( )
|
^
>>
<<
~
, ,
, ,
: &, |, ^ ~. , ,
. ,
.
.
0
1
0
1
q
0
0
1
1
& q
0
0
0
1
| q
0
1
1
1
^ q
0
1
1
0
~
1
0
1
0
.
, - 0,
0. :
&
1101 0011
1010 1010
__________
1000 0010
& .
. , 9
: 0000 1001. ,
8, 0000 1000.
// , .
using System;
4.
109
class MakeEven {
static void Main() {
ushort num;
ushort i;
for(i = 1; i <= 10; i++) {
num = i;
Console.WriteLine("num: " + num);
num = (ushort) (num & 0xFFFE);
Console.WriteLine("num : "
+ num + "\n");
}
}
}
.
num: 1
num : 0
num: 2
num : 2
num: 3
num : 2
num: 4
num : 4
num: 5
num : 4
num: 6
num : 6
num: 7
num : 6
num: 8
num : 8
num: 9
num : 8
num: 10
num : 10
0xFFFE,
, : 1111 1111 1111 1110. ,
num, , .
110 I. #
, 1
.
.
, .
// , ,
// .
using System;
class IsOdd {
static void Main() {
ushort num;
num = 10;
if((num & 1) == 1)
Console.WriteLine("He .");
num = 11;
if((num & 1) == 1)
Console.WriteLine(num + " .");
}
}
.
11 .
if
num 1.
num , ..
1, num & 1 1.
. if
, .
& ,
byte
. .
// , .
using System;
class ShowBits {
static void Main() {
int t;
byte val;
val = 123;
for (t=l28; t > 0; t = t/2) {
4.
111
112
I. #
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
num: 10
num : 11
num 1, 1
, .
1 ,
. ,
, .
,
, .
0111 1111
1011 1001
__________
1100 0110
,
. ,
X
Y, Y,
X. ,
R1 = X ^ Y;
R2 = R1 ^ Y;
R2 , X.
,
4.
113
, ,
.
,
.
, .
, ,
.
, .
// .
using System;
class Encode {
static void Main() {
char ch1 = 'H';
char ch2 = 'i';
char ch3 = '!';
int key = 88;
Console.WriteLine(" : " + ch1 + ch2 + ch3);
// .
ch1 = (char)(ch1 ^ key);
ch2 = (char)(ch2 ^ key);
ch3 = (char)(ch3 ^ key);
Console.WriteLine(" : " + ch1 + ch2 + ch3);
// .
ch1 = (char)(ch1 ^ key);
ch2 = (char)(ch2 ^ key);
ch3 = (char)(ch3 ^ key);
Console.WriteLine(" : " + ch1 + ch2 + ch3);
}
}
.
: Hi!
: 1y
: Hi!
,
. (
, , ,
, .)
( 1)
. ,
1001 0110,
~ 0110 1001.
114
I. C#
1 .
// .
using System;
class NotDemo {
static void Main() {
sbyte b = -34;
for(int t=128; t > 0; t = t/2)
{
if((b & t) != 0) Console.Write("1 ");
if((b & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
//
b = (sbyte) ~b;
for(int t=128; t > 0; t = t/2) {
if((b & t) != 0) Console.Write("1 ");
if((b & t) == 0) Console.Write("0 ");
}
}
}
.
1 1 0 1 1 1 1 0
0 0 1 0 0 0 0 1
C# ,
, . C#
.
<<
>>
<< _
>> _
_ ,
.
, .
.
, .
, .
,
1. , ,
4.
115
1.
,
.
.
,
.
,
. ,
1. , .
.
. ,
1 , ,
128, .
// .
using System;
class ShiftDemo {
static void Main() {
int val = 1;
for(int i = 0; i < 8; i++) {
for(int t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val << 1; //
}
Console.WriteLine();
val = 128;
for(int i = 0; i < 8; i++) {
for(int t=128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val >> 1; //
}
}
}
.
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
0
0
0
0
1
0
0
0
0
0
0
I. C#
0
0
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
2,
2. , ,
. , ,
.
.
// 2.
using System;
class MultDiv {
static void Main() {
int n;
n = 10;
Console.WriteLine(" n: " + n);
// 2.
n = n << 1;
Console.WriteLine(" n " +
" n = n * 2: " + n);
// 4.
n = n << 2;
Console.WriteLine(" n " +
" n = n * 4: " + n);
// 2.
n = n >> 1;
Console.WriteLine(" n " +
" n = n / 2: " + n);
// 4.
n = n >> 2;
Console.WriteLine(" n " +
" n = n / 4: " + n);
Console.WriteLine();
// n .
n = 10;
Console.WriteLine(" n: " + n);
4.
117
// 2 .
n = n << 30; //
Console.WriteLine(" " +
" 30 : " + n);
}
}
.
n: 10
n
n
n
n
n
n
n
n
=
=
=
=
n
n
n
n
*
*
/
/
2:
4:
2:
4:
20
80
40
10
n: 10
n 30 : -2147483648
.
10 , ,
int.
"" ,
, ,
, 1, ,
. ,
2
. ( . 3.)
. ,
127.
= ^ 127;
^= 127;
?
? #.
if-then-else. ? ,
. .
! ? 2 : 3;
1 bool, 2 3
.
?.
? .
1. , 2,
? . 1
118
I. C#
, 3,
?. , absval
val.
absval = val < 0 ? -val : val; // val
absval val,
. val ,
absval ,
.
?.
, .
// , ?.
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;
result 100
i. ,
i . , result
, .
?
. , , ?,
. ? bool,
4.
119
if.
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);
}
}
if .
i , if .
i , if ,
i , , .
.
,
.
C# ,
. ,
, , , .
=10/*(127+);
= 10 / * (127 + );
, ,
, .
. ,
,
, . ,
?
= /3-34*temp+127;
= (/3) - (34*temp) + 127;
. 4.2 #:
. ,
.
,
#.
:
, if switch,
,
for, while, do-while foreach,
: break, continue, goto, return throw.
throw,
C#
, 13,
.
if
if 2,
.
:
if() ;
else ;
, a e if else. else
. ,
if else, .
if,
.
if()
{
}
122
I. C#
else
{
}
,
if. else,
. . ,
if, bool.
, if else
, ,
.
// ,
.
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.WriteLine(" ");
}
}
}
.
-5:
-4:
-3:
-2:
-1:
0:
1:
2:
3:
4:
5:
i ,
if.
else, .
if
if,
if else. if
. #,
, else if, ..
5.
123
if, , else,
else. .
if (i ==
if(j <
if(k >
else a
}
else a =
10) {
20) a = b;
100) = d;
= ; // else if(k > 100)
d; // else if(i == 10)
,
else if(j < 20),
, ,
if else. ,
else if(i == 10). else
if(k > 100),
if .
if.
. ,
, , .
, ,
.
// ,
// , .
using System;
class PosNegZero {
static void Main() {
int i;
for(i=-5; i <= 5; i++)
{
Console.Write(" " + i + ": ");
if(i < 0) Console.WriteLine(" ");
else if(i == 0) Console.WriteLine(" ");
else Console.WriteLine (" ");
}
}
}
.
-5:
-4:
-3:
-2:
-1:
0:
1:
2:
3:
4:
5:
124
I. C#
if-else-if
if-elseif, if. .
if()
;
else if ()
;
else if ()
;
.
.
.
else
;
.
, ,
.
,
else, ,
. else ,
, .
if-else-if.
, .
//
// , .
using System;
class Ladder {
static void Main() {
int num;
for(num = 2; num < 12; num++) {
if((num % 2) == 0)
Console.WriteLine("
else if((num % 3) == 0)
Console.WriteLine("
else if((num % 5) == 0)
Console.WriteLine("
else if((num % 7) == 0)
Console.WriteLine("
else
Console.WriteLine(num + " 2, 3, 5
}
}
}
.
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 ,
.
switch
C# switch,
. ,
.
if,
switch.
.
.
, ,
. switch.
switch() {
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
}
switch (char,
byte, short int), . (
string .)
, , switch .
, switch, .
, , .
switch
.
126
I. 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:
Console.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 'A':
Console.WriteLine("ch
break;
case '':
Console.WriteLine("ch
break;
case '':
Console.WriteLine("ch
break;
case 'D':
Console.WriteLine("ch
break;
case 'E':
Console.WriteLine("ch
break;
}
A");
");
");
D");
E");
}
}
.
ch
ch
ch
ch
ch
default
switch. , default . ,
.
, case,
case , #
""
. case
switch break. ( "",
goto,
, break.)
128
I. C#
case break,
, switch,
,
switch. default
"", , , break.
"" #,
, C++ Java.
case (.. "") .
C# case . -,
case . ,
case . -,
case
, case .
""
case , case
,
.
// "" case.
using System;
class EmptyCasesCanFall {
static void Main() {
int i;
for(i=1; 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,
, WriteLine().
case "";
.
case
, .
.
5.
129
switch
switch
, switch. switch .
switch
, . ,
.
switch(ch1) {
case 'A': Console.WriteLine(" " +
" switch.");
switch(ch2){
case 'A':
Console.WriteLine(" A " +
" switch");
break;
case '': // ...
} // switch
break;
case '': // ...
for
for 2,
. .
, for.
for
.
for(; ; ) ;
:
for(; ; )
{
;
}
, , ,
,
; ,
; , ,
, , .
, for
. for
, .
, ,
, for.
for ,
, .
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; count < 5; count++)
x += 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++) {
if((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 5
12 6
14 7
15 5
16 8
18 9
for
for #,
.
for .
for
.
. .
// for.
using System;
class Comma {
static void Main() {
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--) {
if((smallest == 1) & ((num % i) == 0))
smallest = i;
if((largest == 1) & ((num % j) == 0))
largest = j;
}
Console.WriteLine(" : " + largest);
Console.WriteLine(" : " + smallest);
}
}
.
5.
133
: 50
: 2
for. ,
i .
2 ,
num. j
.
num ,
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,
i,
i,
i,
i,
i,
i,
i,
j:
j:
j:
j:
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
for ,
done (true). done
, i
j.
134
I. C#
for ,
. C#
, for.
.
// for .
using System;
class Empty {
static void Main() {
int i;
for(i = 0; i < 10; ){
Console.WriteLine(" " + i);
i++; //
}
}
}
for
, .. . i,
, . , ,
, i 10,
. i
, ,
.
0
1
2
3
4
5
6
7
8
9
for
.
// for.
using System;
class Empty2 {
static void Main() {
int i;
i = 0; //
for(; i < 10; ) {
Console.WriteLine(" " + i);
5.
135
i++; //
}
}
}
i ,
for. ,
for.
,
, for.
for,
, .. , .
, #
.
for(;;) // ,
{
//...
}
.
,
,
""
. ( "
break " .)
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++
.
, #, ,
. :
sum
sum i, i. ,
.
sum = sum + i;
i++;
for
, for,
.
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.WriteLine(" " + sum);
Console.WriteLine(" " + fact);
}
}
for, ,
for. ,
. ,
i for.
-
, for.
,
for.
.
5.
137
while
C# while.
:
while () ;
,
. , .
, ,
.
, while
.
// .
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
: 6
while .
num. , mag,
, , num
10. , num
. , ,
mag .
for, while ,
. ,
,
. while
, 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
, while ,
. ,
for, while .
do-while
C# do-while.
for while, ,
do-while .
, do-while .
do-while.
do {
;
} while ();
. ,
5.
139
do-while while.
do-while , .
do-while
.
// .
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
: 891
.
( num) 10. .
num 10. ,
. ,
num .
foreach
foreach
, . C#
, . foreach
7, .
break
break
, ,
140
I. #
. break, ,
, .
.
// 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 !
, for -10 10, ,
, break , i
.
break , #.
,
do-while.
// 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.WriteLine("!");
}
}
break.
.
// .
using System;
5.
141
class FindSmallestFactor {
static void Main() {
int factor = 1;
int num = -1000;
for (int i=2; i <= num/i;' i++) {
if((num%i) == 0) {
factor = i;
break; // ,
//
}
}
Console.WriteLine(" " + factor);
}
}
.
2
break for,
. break
, , .
break ,
.
.
// 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; // , t 10
Console.Write(t + " ");
t++;
}
Console.WriteLine();
}
Console.WriteLine(" .");
}
}
.
: 0
: 0 1 2 3 4 5 6 7 8 9
: 1
142
I. C#
: 0 1 2 3 4 5 6 1 8 9
: 2
: 0 1 2 3 4 5 6 1 8 9
, break
, .
break . , break,
, break
. -,
break, switch,
, .
continue
continue
.
continue ,
, . , continue
break.
continue
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);
}
}
}
,
WriteLine().
while do-while continue
,
. for ,
, .
continue , , ,
C# ,
. ,
, continue
.
5.
143
return
return .
. 6.
goto
C# goto
. goto,
, . "
" , "
" . goto
.
goto . ,
, , ,
.
,
. goto
. goto
,
. goto , , ,
.
goto #
. ,
goto, .
1 100
goto .
= 1;
loop1:
++;
if(x < 100) goto loop1;
, goto
case default switch. case default
switch .
goto. goto
switch. ,
switch.
goto switch.
// goto switch.
using System;
class SwitchGoto {
static void Main() {
for(int i=1; i < 5; i++) {
switch(i) {
case 1:
144
I. C#
Console.WriteLine("
goto case 3;
case 2 :
Console.WriteLine("
goto case 1;
case 3:
Console.WriteLine("
goto default;
default:
Console.WriteLine("
break;
case 1");
case 2");
case 3");
default");
}
Console.WriteLine();
}
// goto case 1; // ! 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 ,
"" ,
, break .
, goto
switch. ,
:
// goto case 1; // ! switch .
. ,
goto switch, ,
,
.
goto
.
5.
145
// 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);
}
}
.
i, j, k: 0 0
i, j, k: 0 0
i, j, k: 0 0
i, j, k: 0 0
!
0
1
2
3
i, j, k: 0, 0 3
goto,
if break,
. goto .
goto,
,
.
: ,
, .
.
#,
. ,
- ().
.
#,
.
.
. ,
,
.
,
.
.
,
. ,
. #
,
. , ,
,
.
, .
,
.
148
I. C#
, , ,
.
, .
, , ,
-. , C#
-. , ,
, ,
- , , , , ,
.
: .
.
.
class.
, .
class _ {
// .
1;
2;
//...
N;
// .
_ 1() {
//
}
_ 2() {
//
}
// ...
_ () {
//
}
}
,
. , public,
. 2,
(private) , (public), .e.
. .
, ,
.
. ,
, , Main(),
(public). ,
, .
8.
6. ,
149
,
. .
#,
. , , ... ,
, ,
, .
,
.
, .
, ,
: Main().
Main() .
, .
,
, , ,
, .. ( Building)
: ,
.
Building.
: Floors, Area Occupants. , Building
. ,
. ( .)
class Building {
public int Floors;
//
public int Area;
//
public int Occupants; //
}
, Building,
.
:
_;
; , _ , . ,
, ,
. Building
public. ,
Building.
class .
Building.
150
I. C#
Building. , , , class
, . ,
Building .
Building,
.
Building house = new Building(); // Building
house
Building, .. "" .
.
, , ,
,
. , Building
Floors, Area Occupants.
, . - .
-.
.
, . ,
2 Floors house
.
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.
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// .
areaPP = house.Area / house.Occupants;
6. ,
151
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 Building();
int areaPP; //
// house.
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office.
office.Occupants = 25;
office.Area = 4200;
office.Floors = 3;
// .
areaPP = house.Area / house.Occupants;
Console.WriteLine(" \n " +
house.Floors + " \n " +
house.Occupants + " \n " +
house.Area +
" . , \n " +
areaPP + " ");
// .
areaPP = office.Area / office.Occupants;
Console.WriteLine(" :\n " +
office.Floors + " \n " +
office.Occupants + " \n " +
office.Area +
" . , \n " +
areaPP + " ");
}
}
.
:
2
4
2500 . ,
625
6. ,
153
:
3
25
4200 . ,
168
, house ,
office. . 6.1.
house
office
Floors
Area
2500
Occupants
Floors
Area
4200
Occupants
25
. 6.1.
Building
.
Building house = new Building!);
. -,
house, Building.
, , . -,
, , .
new. , house .
, house
Building.
new (.. )
, .
, C# .
, house
, , .
Building house; //
house = new Building(); // Building
house
Building. , house ,
, .
Building, house.
house .
154
I. C#
, , ,
.
, .
, . ,
int ;
= 10;
10, int,
.
Building house = new Building();
house , .
,
, int.
, . ,
, ,
.
, ,
, ,
, , ,
. .
.
.
Building house1 = new Building();
Building house2 = house1;
, house1 house2
, . house1 house2, ,
. house1
house2, house2
, house1. ,
house1 house2. ,
house1.Area = 2600;
WriteLine()
Console.WriteLine(house1.Area);
Console.WriteLine(house2.Area);
: 2600.
, house1 house2,
, . ,
,
house2.
6. ,
Building
Building
Building
house2 =
155
house2 , house3.
house1 .
,
. Building,
, , . ,
, , .
, ,
, .
, .
.
C# .
, . ,
. , , ,
Main() ,
. , #.
,
#. , .
, GetVal,
: GetVal().
.
:
_ (_) {
//
}
, ,
. ,
. , (private)
, .
(public), .
_ , .
, .
, void.
, .
,
. , _ ,
.
, ,
. , .
156
I. C#
Building
, , ,
. ,
Main()
.
,
.
Building, ,
. Area Occupants,
Building. ,
Building. ,
Building,
, Building,
. .
, Building , ,
- ,
, , Building.
Building,
.
Building, AreaPerPerson(),
, .
// 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 Building();
Building office = new Building();
// house.
house.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 + " \n " +
house.Occupants + " \n " +
house.Area +
". , ");
house.AreaPerPerson();
Console.WriteLine();
Console.WriteLine(" :\n " +
office.Floors + " \n " +
office.Occupants + " \n " +
office.Area +
" . , ");
office.AreaPerPerson();
}
}
, .
:
2
4
2500 . ,
625
:
3
25
4200 . ,
168
,
AreaPerPerson(). .
158 I. C#
AreaPerPerson() .
, .
Main().
house.AreaPerPerson();
AreaPerPerson() house.
, AreaPerPerson() ,
house, -.
AreaPerPerson() , .
,
, .
house.AreaPerPerson()
, house. ,
office.AreaPerPerson()
, office. ,
AreaPerPerson() .
AreaPerPerson()
: Area Occupants
, .. -.
, , ,
-. ,
.
. , .
. ,
Area Occupants AreaPerPerson()
, AreaPerPerson().
Occupants
AreaPerPerson() ( ,
). Occupants ,
- . 13,
, , C# ,
.
, . -,
, ,
AreaPerPerson() . -,
return. return:
void, .. , , ,
. ,
, .
void
return.
return;
6. ,
159
,
, .
.
public void MyMeth() {
int i;
for(i=0; i<10; i++) {
if(i == 5) return; // 5
Console.WriteLine();
}
}
5 for,
5 i .
return,
. :
public void MyMeth() {
//...
if(done) return;
// ...
if(error) return;
}
:
.
. -
.
, : void
:
return.
void ,
, .
.
3 Math.Sqrt(),
.
. , Math.Sqrt(),
,
,
.
#.
return:
return ;
.
160
I. C#
,
AreaPerPerson().
, .
.
AreaPerPerson(),
, .
// AreaPerPerson().
using System;
class Building {
public int Floors;
//
public int Area;
//
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.
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office.
office.Occupants = 25;
office.Area = 4200;
office.Floors = 3;
// .
areaPP = house.AreaPerPerson();
Console.WriteLine(" :\n " +
house.Floors + " \n " +
house.Occupants + " \n " +
house.Area +
" . , \n " +
areaPP + " ");
6. ,
161
Console.WriteLine();
// .
areaPP = office.AreaPerPerson();
Console.WriteLine(" :\n " +
office.Floors + " \n " +
office.Occupants + " \n " +
office.Area +
" . , \n " +
areaPP + " ");
}
}
, .
:
AreaPerPerson() ,
. ,
, AreaPerPerson(). ,
areaPP = house.AreaPerPerson();
areaPP
( house).
, AreaPerPerson()
int. ,
. , , ,
, ,
, . , double,
double.
, , ,
. ,
areaPP, AreaPerPerson() ,
WriteLine(), .
Console.WriteLine(" :\n " +
house.Floors + " \n " +
house.Occupants + " \n " +
house.Area +
" . , \n " +
house.AreaPerPerson() +
" ");
,
WriteLine(), house.AreaPerPerson(),
WriteLine(). ,
AreaPerPerson() ,
Building. ,
.
if(b1.AreaPerPerson() > b2.AreaPerPerson())
Console.WriteLine(" b1 ");
162
I. C#
. ,
, . , ,
, .
. ,
. .
, ,
.
,
. ChkNum IsPrime(),
true, , .
false. ,
IsPrime() bool.
// .
using System;
class ChkNum {
// true,
// .
public bool IsPrime(int x) {
if (x <= 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 ChkNum();
for (int i=2; i < 10; i++)
if(ob.IsPrime(i)) Console.WriteLine(i + " .");
else Console.WriteLine(i + " .");
}
}
.
2
3
4
5
6
7
8
9
.
.
.
.
.
.
.
.
IsPrime() ,
. .
6. ,
163
, IsPrime().
. IsPrime() ,
2. , IsPrime() ,
2.
3, 4 .. , ,
IsPrime() ,
, .
, .
, .
ChkNum, LeastComFactor(),
.
, ,
.
// , .
using System;
class ChkNum {
// true,
// .
public bool IsPrime(int x) {
if(x <= 1) return false;
for(int i=2; i <= x/i; i++)
if((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 ChkNum();
int a, b;
for(int i=2; i < 10; i++)
if(ob.IsPrime(i)) Console.WriteLine(i + " .");
else Console.WriteLine(i + " .");
164
I. C#
= 7;
b = 8;
Console.WriteLine(" " +
+ " " + b + " " +
ob.LeastComFactor(, b));
= 100;
b = 8;
Console.WriteLine(" " +
+ " " + b + " " +
ob.LeastComFactor(, b));
= 100;
b = 75;
Console.WriteLine(" " +
+ " " + b + " " +
ob.LeastComFactor(, b));
}
}
: LeastComFactor(),
.
.
2 .
3 .
4 .
5 .
6 .
7 .
8 .
9 .
7 8 1
100 8 2
100 75 5
,
, . ,
.
int MyMeth(int a, double b, float ) {
// ...
Building
Building
, ,
.
MaxOccupant().
// , ,
// .
public int MaxOccupant(int minArea) {
return Area / minArea;
}
6. ,
165
MaxOccupant(), minArea
.
,
.
Building, MaxOccupant().
/*
,
,
,
.
*/
using System;
class Building {
public int Floors;
//
public int Area;
//
public int Occupants; //
// .
public int AreaPerPerson() {
return Area / Occupants;
}
// , ,
// .
public int MaxOccupant(int minArea) {
return Area / minArea;
}
}
// MaxOccupant().
class BuildingDemo {
static void Main() {
Building house = new Building();
Building office = new Building();
// house.
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
// office.
office.Occupants = 25;
office.Area = 4200;
office.Floors = 3;
Console.WriteLine(" , \n" +
" " +
300 + " . : " +
house.MaxOccupant(300));
Console.WriteLine(" " +
166
I. C#
" , \n" +
" " +
300 + " . : " +
office.MaxOccupant(300));
}
}
.
,
300 . : 8
,
300 . : 14
,
.
C# . , ,
.
.
public void MyMeth() {
char a, b;
// ...
if(a==b) {
Console.WriteLine("");
return;
} else {
Console.WriteLine(" ");
return;
}
Console.WriteLine(" ");
}
MyMeth()
, WriteLine().
, .
, ,
.
Building , , ,
.
house.Occupants = 4;
house.Area = 2500;
house.Floors = 2;
6. ,
167
#.
, (
). , :
.
.
, , .
, .
.
_(_) {
//
}
,
, ,
,
. ,
public, . _ ,
.
, ,
, C# ,
.
, bool false, .
,
.
.
// .
using System;
class MyClass {
public int x;
public MyClass() {
x = 10;
}
}
class ConsDemo {
static void Main() {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
Console.WriteLine(t1.x + " " + t2.x);
}
}
MyClass .
168
I. C#
public MyClass() {
x = 10;
}
, public.
, , .
MyClass
10. new . ,
:
MyClass t1 = new MyClass();
MyClass() t1,
t1. 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 t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
Console.WriteLine(t1.x + " " + t2.x);
}
}
.
10 88
MyClass() i,
.
:
MyClass t1 = new MyClass(10);
i , .
6. ,
169
Building
Building , ,
Floors, Area Occupants .
, 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(" , \n" +
" " +
300 ,+ " . : " +
house.MaxOccupant(300));
Console.WriteLine(" " +
" , \n" +
" " +
300 + " . : " +
office.MaxOccupant (300));
}
}
,
.
170
I. C#
new
, ,
new, .
new :
new _(_)
_ , .
_ .
, new
, C# . , new
, .
, ,
new -
.
( 13).
, , ,
, ,
, , .
new
: new
, int float?
C# .
.
, new
. ,
,
.
, int char,
, .
,
.
.
, 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 : 0
, i
. , new,
i .
, WriteLine(),
.
, new
, .
. ,
new .
, new
. , ,
.
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=1; count < 100000; count++)
ob.Generator(count);
Console.WriteLine( "!");
}
}
.
.
. ,
. Generator(),
Destruct. DestructDemo
ob Destruct,
100 . . "
". ,
,
.. - ,
. , ..
, "!",
, for.
: WriteLine()
~Destruct() .
, ,
.
,
,
174
I. #
.
" ", II
#. " "
,
. , " "
" " ,
, .
this
, this.
,
, .. , .
this. , this
, .
this,
, Rect,
Area(),
.
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 r1 =
Rect r2 =
{
Main() (
new Rect(4, 5);
new Rect(7, 9);
6. ,
175
{
Main() {
new Rect(4, 5);
new Rect(7, 9);
176
I. C#
this
#, ,
.
this . , C#
,
.
.
this. ,
C# Rect().
public Rect(int Width, int Height) {
this.Width = Width;
this.Height = Height;
}
Rect()
, , . "
" this.
#.
string,
foreach.
.
C# ,
, .
,
. ,
,
,
.
, .
, , ,
, ,
,
.
,
, .
C#
, .
:
.
,
178
I. C#
. ,
" ".
.
. ,
.
,
, C# . -,
, . -,
, new. ,
:
[] _ = new [];
.
, .
, . ,
. .
C++,
, #. ,
, .
.
int,
, sample.
int[] sample = new int[10];
sample ,
new. ,
int.
,
. :
int[] sample;
sample = new int[10];
sample -
, .
.
:
. C#
. , sample 10
0 9.
7.
179
. , sample
sample [0], sample[9].
, 10 sample.
// .
using System;
class ArrayDemo {
static void Main() {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
Console.WriteLine("sample[" + i + "]: " + sample[i]);
}
}
.
sample[0]:
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 .
,
. ,
,
nums,
for.
// .
using System;
class Average {
static void Main() {
180
I. C#
int[] nums = new int[10];
int avg = 0;
nums[0]
nums[1]
nums[2]
nums[3]
nums[4]
nums[5]
nums[6]
nums[7]
nums[8]
nums[9]
=
=
=
=
=
=
=
=
=
=
99;
10;
100;
18;
78;
23;
63;
9;
87;
49;
7.
181
C# .
, .
, ,
.
// .
using System;
class ArrayErr {
static void Main() {
int[] sample = new int[10];
int i;
// .
for(i = 0; i < 100; i = i+1)
sample[i] = i;
}
}
182
I. C#
i 10,
IndexOutOfRangeException,
, . (
13.)
,
. ,
,
.
.
.
, ,
.
integer
1020.
int[,] table = new int[10, 20];
. ,
.
[,]
, .
new,
.
int[10, 20]
1020,
.
,
. , table
(3,5) 10.
table[3, 5] = 10;
,
1 12,
.
// .
using System;
class TwoD {
static void Main() {
int t, i;
7.
183
. 7.1. table,
TwoD
, C++ Java,
, #.
, C# .
C# .
.
[,...,] _ = new [1, 2, ... N];
,
4103.
int[,,] multidim = new int[4, 10, 3];
multidim
(2,4,1) 100.
multidim[2, 4, 1] = 100;
184
I. C#
,
, 333,
.
// 333.
using System;
class ThreeDMatrix {
static void Main() {
int[,,] m = new int[3, 3, 3];
int sum = 0;
int n = 1;
for(int x=0; x < 3; x++)
for(int y=0; < 3; y++)
for(int z=0;z < 3; z++)
m[x, y, z]= n++;
sum = m[0, 0, 0]+ m[1, 1,1] + m[2, 2, 2];
Console.WriteLine(" : " + sum);
}
}
.
: 42
.
:
[,] _ = {
{val, val, val, ..., val},
{val, val, val, ..., val},
7.
185
class Squares {
static void Main() {
int[,] sqrs = {
{ 1, 1 },
{ 2, 4 },
{ 3, 9 },
{ 4, 16 },
{ 5, 25 },
{ 6, 36 },
{ 7, 49 },
{ 8, 64 },
{ 9, 81 },
{ 10, 100 }
};
int i, j;
for(i=0; i < 10; i++) {
for(j=0; j < 2; j++)
Console.Write(sqrs[i,j] + " ");
Console.WriteLine();
}
}
}
.
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
, ,
.
,
. C# ,
. ,
. ,
.
,
. ,
:
[][] _ = new [][];
186
I. C#
.
, . ,
jagged.
,
.
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
jagged ,
.
jagged [0][0]
jagged [0][1]
jagged [0][2]
jagged [1][0]
jagged [1][1]
jagged [1][2]
jagged [2][0]
jagged [2][1]
jagged [2][2]
jagged [0][3]
jagged [2][3]
jagged [2][4]
, !
,
. ,
jagged, (2,1),
10.
jagged[2][1] = 10;
.
.
// .
using System;
class Jagged {
static void Main() {
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
int i;
// .
for(i=0; i < 4; i++)
jagged[0] [i] = i;
// .
for(i=0; i < 3; i++)
jagged[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 1 2 3
0 1 2
0 1 2 3 4
,
. , ,
, .. , ,
, .
:
, .
, .
int[][,] jagged = new int[3][,];
jagged[0]
42.
jagged[0] = new int[4, 2];
jagged[0][1,0]
i.
jagged[0][1,0] = i;
, , , ,
188
I. C#
.
,
. .
// .
using System;
class AssignARef {
static void Main() {
int i;
int[] nums1 = new int[10];
int[] nums2 = new int [10];
for(i=0; i < 10; i++) nums1[i] = i;
for(i=0; i < 10; i++) nums2[i] = -i;
Console.Write(" nums1: ");
for(i=0; i < 10; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
Console.Write(" nums2: ");
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
nums2 = nums1; // nums2 nums1
Console.Write(" nums2\n" + " : ");
for(i=0; i < 10; i++)
Console.Write(nums2[i] + " ");
Console.WriteLine();
// nums1
// nums2.
nums2[3] = 99;
Console.Write(" nums1 \n" +
" nums2: ");
for(i=0; i < 10; i++)
Console.Write(numsl[i] + " ");
Console.WriteLine();
}
}
nums1: 0 1 2 3 4 5 6 7 8 9
nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9
nums2
: 0 1 2 3 4 5 6 7 8 9
nums1
nums2: 0 1 2 99 4 5 6 7 8 9
7.
189
, nums2 nums1
.
Length
C# .
, Length,
, . ,
, .
, .
// Length .
using System;
class LengthDemo {
static void Main() {
int[] nums = new int[10];
Console.WriteLine(" nums " + nums.Length);
// Length nums.
for (int i=0; i < nums.Length; i++)
nums[i] = i * i;
// Length
// nums.
Console.Write(" nums: ");
for(int i=0; i < nums.Length; i++)
Console.Write(nums[i] + " ");
Console.WriteLine();
}
}
.
nums 10
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 int[10, 5, 6];
Console.WriteLine(" nums " + nums.Length);
}
}
.
nums 300
, Length
, ( 300 (1056)
). Length
.
Length
, , .
Length
,
.
// .
using System;
class RevCopy {
static void Main() {
int i, j ;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i < nums1.Length; i++) nums1[i] = i;
Console.Write(" : ");
for(i=0; i < nums2.Length; i++)
Console.Write(nums1[i] + " ");
Console.WriteLine();
// nums1 nums2 .
7.
191
.
: 0 1 2 3 4 5 6 7 8 9
: 9 8 7 6 5 4 3 2 1 0
Length . , ,
. -,
for,
. ,
Length,
, .
Length
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 int[7];
network_nodes[2] = new int[2];
network_nodes[3] = new int[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
I. #
.
: 4
0 0: 70%
0 1: 70%
0 2: 70%
1
1
1
1
1
1
1
0:
1:
2:
3:
4:
5:
6:
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 = new[] { 1, 2, 3, 4, 5 };
int, .
vals. ,
int , .
,
[]. ,
, . .
,
double.
var vals = new[,] { {1.1, 2.2}, {3.3, 4.4},{ 5.5, 6.6} };
vals 23.
.
.
// .
using System;
class Jagged {
static void Main() {
var jagged = new[] {
new[] { 1, 2, 3, 4 },
new[] { 9, 8, 7 ),
new[] { 11, 12, 13, 14, 15 }
};
for(int j = 0; j < jagged.Length; j++) {
for(int i=0; i < jagged[j].Length; i++)
Console.Write(jagged[j][i] + " ");
Console.WriteLine();
}
}
}
.
1 2 3 4
9 8 7
11 12 13 14 15
jagged.
var jagged = new[] {
new[] { 1, 2, 3, 4 },
new[] { 9, 8, 7 },
new[] { 11, 12, 13, 14, 15 }
};
194
I. C#
, new[] .
-, . -,
, .
,
. ,
,
.
,
LINQ- .
.
foreach
5, C# foreach,
. .
foreach ,
. C#
, .
foreach.
foreach ( __ in ) ;
__
,
foreach.
, . ,
. ,
var.
, .
, .
, , .
foreach . ,
.
,
. ,
. , foreach
.
, , , foreach
. , , ,
.
foreach.
, , .
// 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++)
nums[i] = i;
// foreach
// .
foreach(int in nums) {
Console.WriteLine(" : " + );
sum += ;
}
Console.WriteLine(" : " + sum);
}
}
.
: 45
:
:
:
:
:
:
:
:
:
:
0
1
2
3
4
5
6
7
8
9
, foreach
.
foreach ,
, ,
break. ,
nums.
// break
foreach.
using System;
class ForeachDemo {
static void Main() {
int sum = 0;
int[] nums = new int[10];
// nums.
for(int i = 0; i < 10; i++)
nums[i] = i;
// foreach
// .
196
I. C#
foreach(int x in nums) {
Console.WriteLine(" : " + x);
sum += x;
if(x == 4) break; // , 4
}
Console.WriteLine(" 5 : " + sum);
}
}
.
: 0
: 1
: 2
: 3
: 4
5 : 10
, foreach
.
foreach
.
,
.
// 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++)
nums[i,j] = (i+1)*(j+1);
// foreach
// .
foreach(int in nums) {
Console.WriteLine(" : " + );
sum += ;
}
Console.WriteLine(" : " + sum);
}
}
.
:
:
:
:
1
2
3
4
7.
: 90
:
:
:
:
:
:
:
:
:
:
:
197
5
2
4
6
8
10
3
6
9
12
15
foreach
: , ,
, . .
, ,
. ,
foreach .
, .
// foreach.
using System;
class Search {
static void Main() {
int[] nums = new int[10];
int val;
bool found = false;
// nums.
for(int i = 0; i < 10; i++)
nums[i] = i;
val = 5;
// foreach
// nums.
foreach(int in nums) {
if(x == val)(
found = true;
break;
}
}
if(found)
Console.WriteLine(" !");
}
}
.
!
198
I. C#
foreach ,
.
foreach ,
,
.. , foreach
.
string
#.
.
. C# . , string
. string C# ,
,
.
string ,
2, ,
.
. , :
Console.WriteLine(" C# .");
" C# ."
#. ,
string .
, .
. ,
str .
string str = " C# .";
str
" C# .".
string char. :
char[] charray = {'t', '', 's', 't'};
string str = new string(charray);
string , ,
, .
, string
WriteLine().
// .
using System;
7.
199
class StringDemo {
static void Main() {
char[] charray = {'', 't', 'o', ' ', '', 't', 'p', 'o', '', 'a',
string strl = new string(charray);
string str2 = " .";
Console.WriteLine(strl);
Console.WriteLine(str2);
}
}
.
.
.
string .
. 7.1. ,
StringComparison.
, ,
. ( 12,
StringComparison .)
,
. , ,
. .
, ,
. .
( .)
, .
Compare(), Equals(), IndexOf()
LastIndexOf(),
,
, ,
.
.
,
(.. )
StringComparison.CurrentCulture.
,
StringComparison.Ordinal,
: StringComparison.CurrentCultureIgnoreCase
StringComparison.OrdinalIgnoreCase. ,
( 22).
, Compare() . 7.1 static.
static 8,
, : Compare()
200
I. C#
, . , Compare()
:
= string.Compare(str1, str2, );
.
,
, 22,
.
ToUpper() ToLower(),
. ,
. 7.1, CultureInf, ,
, .
, ,
(.. ).
CultureInfo.CurrentCulture. CultureInfo
System.Globalization. ,
,
,
CultureInfo.CurrentCulture .
string Length, .
7.1.
bool Equals(string
value, StringComparison
comparisonType)
true,
,
value.
comparisonType
,
value. .
-1,
int IndexOf(string
value, StringComparison
comparisonType)
,
strA strB;
, strA str; ,
.
comparisonType
,
value.
-1,
.
comparisonType
7.
201
. 7.1
,
value.
.
-1,
int LastIndexOf(string
value, StringComparison
comparisonType)
,
value.
-1,
.
comparisonType
string ToLower(CultureInfo.
CurrentCulture culture)
.
culture
string ToUpper(CultureInfo.
CurrentCulture culture)
.
culture
,
.
string str = "";
Console.WriteLine(str[0]);
"",
"". , . , ,
,
. .
==. ,
== , ,
. string.
== ,
. !=.
.
Equals(),
StringComparison.CurrentCulture. ,
Compare() ,
.
, Equals()
.
.
// .
using System;
using System.Globalization;
202
I. C#
class StrOps {
static void Main() {
string str1 = " .NET #.";
string str2 = " .NET #.";
string str3 = " C# .";
string strUp, strLow;
int result, idx;
Console.WriteLine("str1: " + str1);
Console.WriteLine(" str1: " + str1.Length);
// str1,
// .
strLow = str1.ToLower(CultureInfo.CurrentCulture);
strUp = str1.ToUpper(CultureInfo.CurrentCulture);
Console.WriteLine(" str1, " +
" :\n " + strLow);
Console.WriteLine(" str1, " +
" :\n " + strUp);
Console.WriteLine();
// str1 .
Console.WriteLine(" str1 .");
for (int i=0; i < str1.Length; i++)
Console.Write(str1[i]);
Console.WriteLine("\n");
// .
if(str1 == str2)
Console.WriteLine("str1 == str2");
else
Console.WriteLine("str1 != str2");
if(str1 == str3)
Console.WriteLine("str1 == str3");
else
Console.WriteLine("str1 != str3");
// .
result = string.Compare(str3, str1, StringComparison.CurrentCulture);
if(result == 0)
Console.WriteLine(" str1 str3 ");
else if (result < 0)
Console.WriteLine(" str1 str3");
else
Console.WriteLine(" str1 str3");
Console.WriteLine();
// str2.
str2 = " ";
// .
idx = str2.IndexOf("", StringComparison.Ordinal);
Console.WriteLine(" <>: " + idx);
7.
203
str1
str2
str3
str4
=
=
=
=
"";
"";
"";
str1 + str2 + str3;
str4 "".
: string
System.String, .NET Framework,
.. . ,
, string,
System.String, .
System.String II .
,
. .
// .
using System;
204
I. C#
class StringArrays {
static void Main() {
string[] 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 int[20];
string[] digits = { "", "", "",
"", "", "",
"", "", "",
"" };
num = 1908;
Console.WriteLine(": " + num);
Console.Write(" : ");
nextdigit = 0;
numdigits = 0;
// n.
7.
205
// .
do {
nextdigit = num % 10;
n[numdigits] = nextdigit;
numdigits++;
num = num / 10;
} while(num > 0);
numdigits--;
// .
for( ; numdigits >= 0; numdigits--)
Console.Write(digits[n[numdigits]] + " ");
Console.WriteLine();
}
}
.
: 1908
:
digits
0 9.
. ,
n int.
n .
, ,
.
, string .
, .
.
, ,
. ,
, ,
.
"", .
, , , (..
string) , , .
string .
, ,
: Substring().
, .
, ,
, , .
Substring():
string Substring(int _, int )
_ ,
.
206
I. C#
,
Substring().
// Substring().
using System;
class SubStr {
static void Main() {
string orgstr = " C# .";
//
string substr = orgstr.Substring(5, 20);
Console.WriteLine("orgstr: " + orgstr);
Console.WriteLine("substr: " + substr);
}
}
.
orgstr: C# .
substr:
, orgstr ,
substr.
: ,
, #,
. C#
StringBuilder, System.Text.
, . , ,
C# string, StringBuilder.
switch
string switch.
,
switch.
,
. ,
, "", "" "".
// switch .
using System;
class StringSwitch {
static void Main() {
string[] 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(),
static.
. -,
.
, 6. -,
. ,
.
#, ,
: ,
.
,
.
.
,
.
.
-
,
.
210
I. C#
,
, , ,
.
.
, . ,
" ", ,
.
C#
: public, private, protected 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.
211
212
I. C#
.
, ,
.
, , .
, ,
,
.
,
, ..
, , .
, , ,
.
, .
, ,
.
,
, .
, ,
,
. , ,
, .
, .
- ,
, ,
" ".
, .
.
-
,
. , ,
, ,
.
, .
:
. ,
. ,
: ,
.
8.
213
Stack,
.
.
Stack. ,
" ".
, Stack ,
.
// .
using System;
class Stack {
// .
char[] stck; // ,
int tos;
//
// Stack .
public Stack(int size) {
stck = new char[size];
//
tos = 0;
}
// .
public void Push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return;
}
stck[tos] = ch;
tos++;
}
// .
public char Pop() {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;
}
tos--;
return stck[tos];
}
// true, .
public bool IsFull() {
return tos==stck.Length;
}
// true, .
public bool IsEmpty() {
return tos==0;
}
214
I. C#
// .
public int Capacity() {
return stck.Length;
}
// , .
public int GetNum() {
return tos;
}
}
Stack .
.
// .
char[] stck; // ,
int tos;
//
stck (
). ,
. Stack. tos
.
, tos stck, ,
" ".
stck, . ,
tos ,
, tos ,
Stack, , .
stck tos Stack
, .
Stack.
// Stack .
8.
215
, , ch.
,
, : tos
stck. stck ,
, tos,
. , tos
stck.
Pop(),
.
// .
public char Pop() {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;
}
tos--;
return stck[tos];
}
tos.
, , . tos
, .
Push() Pop(),
. Stack
: IsFull(), IsEmpty(), Capacity() GetNum().
.
// true, .
public bool IsFull() {
return tos==stck.Length;
}
// true, .
public bool IsEmpty()(
return tos==0;
}
// .
public int Capacity() {
return stck.Length;
}
// , .
public int GetNum() {
return tos;
}
IsFull() true, ,
false. IsEmpty()
true, , false.
(.. , )
216
I. C#
Capacity(), ,
, GetNum(). ,
, ,
tos. ,
.
Stack
.
// Stack.
using System;
// .
class Stack {
// .
char[] stck; // ,
int tos;
//
// Stack .
public Stack (int size) {
stck = new char[size]; //
tos = 0;
}
// .
public void Push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return;
}
stck[tos] = ch;
tos++;
}
// .
public char Pop() {
if(tos==0) {
Console.WriteLine(" - .");
return (char) 0;
}
tos--;
return stck[tos];
}
// true, .
public bool IsFull() {
return tos==stck.Length;
}
// true, .
public bool IsEmpty() {
8.
217
return tos==0;
}
// .
public int Capacity() {
return stck.Length;
}
// , .
public int GetNum() {
return tos;
}
}
class StackDemo {
static void Main()
Stack stk1 = new
Stack stk2 = new
Stack stk3 = new
char ch;
int i;
{
Stack(10);
Stack(10);
Stack(10);
// stk1.
Console.WriteLine(" -J stk1.");
for(i=0; !stk1.IsFull(); i++)
stk1.Push((char) ('A' + i));
if(stk1.IsFull()) Console.WriteLine(" stk1 .");
// stk1.
Console.Write(" stk1: ");
while( !stk1.IsEmpty() ) {
ch = stk1.Pop();
Console.Write(ch);
}
Console.WriteLine();
if(stk1.IsEmpty()) Console.WriteLine(" stk1 .\n");
// stk1.
Console.WriteLine(" A-J stk1.");
for(i=0; !stk1.IsFull(); i++)
stk1.Push((char) ('A' + i));
// stk1 stk2.
// stk2 .
Console.WriteLine(" stk1\n" +
" stk2.");
while( !stk1.IsEmpty() ) {
ch = stk1.Pop();
stk2.Push(ch);
}
218
I. C#
Console.Write(" stk2: ");
while( !stk2.IsEmpty() ) {
ch = stk2.Pop();
Console.Write(ch);
}
Console.WriteLine("\n");
// 5 .
Console.WriteLine(" 5 stk3.");
for(i=0; i < 5; i++)
stk3.Push((char)('A' + i));
Console.WriteLine(" stk3: " + stk3.Capacity());
Console.WriteLine(" stk3: " +
stk3.GetNum());
}
}
.
-J stk1.
stk1 .
stk1: JIHGFEDCBA
stk1 .
-J stk1.
stk1
stk2.
stk2: ABCDEFGHIJ
5 stk3.
stk3: 10
stk3: 5
,
, , int 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: (1}",
alpha, beta);
}
}
class PassOb {
static void Main() {
MyClass ob1 = new MyClass(4, 5);
MyClass ob2 = new MyClass(6, 7);
Console.Write("ob1: ");
ob1.Show();
Console.Write("ob2: ");
ob2.Show();
if(ob1.SameAs(ob2))
Console.WriteLine("ob1 ob2 .");
else
Console.WriteLine("ob1 ob2 .");
Console.WriteLine();
// ob1 ob2.
ob1.Copy(ob2);
Console.Write(" : ");
ob1.Show();
if(ob1.SameAs(ob2))
Console.WriteLine("ob1 ob2 .");
else
Console.WriteLine("ob1 ob2 .");
}
}
.
ob1: alpha: 4, beta: 5
ob2: alpha: 6, beta: 7
219
220
I. #
ob1 ob2 .
ob1 : alpha: 6, beta: 7
ob1 b2 .
SameAs() ()
MyClass . SameAs()
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
222
I. C#
/* . ob. ob.b ,
, . */
public void Change(Test ob) {
ob.a = ob.a + ob.b;
ob.b = -ob.b;
}
}
class CallByRef {
static void Main() {
Test ob = new Test(15, 20);
Console.WriteLine("ob. ob.b : " +
ob.a + " " + ob.b);
ob.Change(ob);
Console.WriteLine("ob. ob.b : " +
ob.a + " " + ob.b);
}
}
.
ob.a ob.b : 15 20
ob.a ob.b : 35 -20
, Change()
, .
, . ,
, , .
- ,
. , .
ref out
, , int char,
. , , ,
, ,
. , ref out
.
, .
ref out,
,
. , :
.
.
, ,
. Swap(),
.
8.
223
, , C#
, ,
, int.
ref.
,
return.
. ,
, ,
? , out.
ref
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 RefTest();
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 = 10, = 20;
Console.WriteLine("x : " + + " " + );
ob.Swap(ref , ref );
Console.WriteLine(" : " + + " " + );
}
}
.
: 10 20
: 20 10
ref . ,
,
. , ,
, ,
. , ref
.
out
, . , ,
, ,
.
,
. ,
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; // frac
return whole;
//
}
}
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#
GetParts() . -,
n
return. -,
fr 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++) {
if( ((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 Num();
int lcf, gcf;
if(ob.HasComFactor(231, 105, out lcf, out gcf)) {
8.
Console.WriteLine("
" 231
Console.WriteLine("
" 231
227
" +
105 " + lcf);
" +
105 " + gcf);
}
else
Console.WriteLine(" 35 49 .");
if(ob.HasComFactor(35, 51, out lcf, out gcf)) {
Console.WriteLine(" " +
" 35 51 " + lcf);
Console.WriteLine(" " +
" 35 51 " + gcf);
}
else
Console.WriteLine(" 35 51 .");
}
}
, lcf gcf
Main() HasComFactor().
HasComFactor() ref, out, .
true false, ,
. ,
out .
.
231 105 3
231 105 21
35 51 .
ref out
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: {l}", a, b);
}
// .
public void Swap(ref RefSwap ob1, ref RefSwap ob2) {
RefSwap t;
t = ob1;
ob1 = ob2;
ob2 = t;
}
}
class RefSwapDemo {
static void Main() {
RefSwap x = new RefSwap(1, 2);
RefSwap = new RefSwap(3, 4);
Console.Write("x : ");
x.Show();
Console.Write(" : ");
.Show();
Console.WriteLine();
// , .
.Swap(ref , ref );
Console.Write(" : ");
.Show();
Console.Write(" : ");
.Show();
}
}
.
: : 1, b: 2
: : 3, b: 4
: : 3, b: 4
: : 1, b: 2
Swap() ,
. Swap() ,
1 2, ,
3 4. Swap() ,
3 4, ,
1 2. ref, Swap()
. ,
ref Swap().
8.
229
,
, . ,
. ,
, .
, , .
.
, .
, .
params.
,
, params.
, .
.
, params
MinVal(),
.
// params.
using System;
class Min {
public int MinVal(params int[] nums) {
int m;
if(nums.Length == 0) {
Console.WriteLine(": .");
return 0;
}
m = nums[0];
for(int i=1; i < nums.Length; i++)
if(nums[i] < m) m = nums[i];
return m;
}
}
class ParamsDemo {
static void Main() {
Min ob = new Min();
int min;
int a = 10, b = 20;
// .
min = ob.MinVal(a, b);
Console.WriteLine(" " + min);
// .
min = ob.MinVal(a, b, -1);
230
I. C#
Console.WriteLine(" " + min);
// .
min = ob.MinVal(18, 23, 3, 14, 25);
Console.WriteLine(" " + min);
// .
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.MinVal(args);
Console.WriteLine(" " + min);
}
}
.
10
-1
3
8
, MinVal(),
nums. .
MinVal()
.
MinVal().
, .
. params,
, .
params
, , .
, MinVal()
min = ob.MinVal(l, 2.2); // !
, double
( 2.2) int, nums MinVal().
params ,
, params
! , MinVal()
#.
min = ob.MinVal(); //
min = ob.MinVal(3); // 1
MinVal()
nums ,
. , MinVal()
. (
13.) , MinVal()
, .
.
,
. , ShowArgs()
8.
231
string,
params.
//
// params.
using System;
class MyClass {
public void ShowArgs(string msg, params int[] nums) {
Console.Write(msg + ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
}
}
class ParamsDemo2 {
static void Main() {
MyClass ob = new MyClass();
ob.ShowArgs(" ",
1, 2, 3, 4, 5);
ob.ShowArgs(" ",
17, 20);
}
}
.
: 1, 2, 3, 4, 5
: 17, 20
, ,
params,
. params .
, .
Rect, Enlarge(),
,
, .
// .
using System;
class Rect {
int width;
int height;
232
I. C#
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 = ob.Factory(i, j); //
anotherOb.Show();
}
Console.WriteLine();
}
}
.
b:
b:
b:
b:
b:
b:
b:
0
1
2
3
4
5
6
10
9
8
7
6
5
4
234
I. C#
b: 73
b: 8 2
b: 91
.
MyClass , ,
. , b
. Factory() ,
b. , b
,
Factory().
Main() MyClass,
for .
, .
MyClass anotherOb = ob.Factory(i, j); //
anotherOb, ,
. anotherOb
, , , .
C# , ,
. ( C# C++,
.) ,
FindFactors() ,
.
// .
using System;
class Factor {
/* facts, num.
numfactors out
. */
public int[] FindFactors(int num, out int numfactors) {
int[] facts = new int[80]; // 80
int i, j;
// facts.
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j;
return facts;
}
}
8.
235
class FindFactors {
static void Main() {
Factor f = new Factor();
int numfastors;
int[] factors;
factors = f.FindFactors(1000, out numfactors);
Console.WriteLine(" 1000: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
}
}
.
1000:
2 4 5 8 10 20 25 40 50 100 125 200 250 500
Factor FindFactors() .
public int[] FindFactors(int num, out int numfactors) {
, int.
. , ,
, . ,
someMeth(),
double.
public double[,] someMeth()
{ // ...
C#
, ,
-. , ,
.
#.
, ,
.
: .
,
. .
( ,
#, , .) ,
.
, ,
( ) .
236
I. C#
, .
// .
using System;
class Overload {
public void OvlDemo() {
Console.WriteLine(" ");
}
// OvlDemo .
public void OvlDemo(int a) {
Console.WriteLine(" : " + a);
}
// OvlDemo .
public int OvlDemo(int a, int b) {
Console.WriteLine(" : " + 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 resI;
double resD;
// OvlDemo().
ob.OvlDemo();
Console.WriteLine();
ob.OvlDemo(2);
Console.WriteLine();
resI = ob.OvlDemo(4, 6);
Console.WriteLine(" ob.OvlDemo(4, 6): " + resI
Console.WriteLine ();
resD = ob.OvlDemo(1.1, 2.32);
Console.WriteLine(" ob.OvlDemo(1.1, 2.32): " +
resD);
}
}
.
8.
237
: 2
: 4 6
ob.OvlDemo(4, 6): 10
double: 1.1 2.32
ob.OvlDemo(1.1, 2.32): 3.42
, OvlDemo() .
, ,
, 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(" MyMeth(int): " + x);
}
public void MyMeth(double x) {
Console.WriteLine(" MyMeth(double): " + x);
}
}
238
I. C#
class TypeConv {
static void Main() {
Overload2 ob = new Overload2();
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
MyMeth():
int double. MyMeth()
byte, short float. ,
byte short, C#
int MyMeth(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): " + x);
}
public void MyMeth(double x) {
8.
239
ob.MyMeth(int)
ob.MyMeth(double)
ob.MyMeth(b); //
ob.MyMeth(byte) -//
ob.MyMeth(s); // ob.MyMeth(int) --
ob.MyMeth(f); // ob.MyMeth(double) --
}
}
.
MyMeth(int): 10
MyMeth(double): 10.1
MyMeth(byte): 99
MyMeth(int): 10
MyMeth(double): 11.5
MyMeth(),
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)
MyMeth(int x),
ob.MyMeth(ref i)
MyMeth(ref int x).
240 I. C#
ref out ,
, .
, MyMeth()
.
// !
public void MyMeth(out int x) { // ...
public void MyMeth(ref int x) { // ...
MyMeth() ,
out, ref.
,
C# :
. , ,
. ,
, .
. , ,
. , ,
, . , abs()
, labs()
, fabs()
() .
, ,
, , , ,
.
, ,
. #
, , ,
. ,
.NET Framework Abs(), System.Math
. C# ,
Abs() , .
,
. , Abs
,
. .
,
, ,
.
,
.
- ,
. ,
,
. , Sqr ,
.
8.
241
.
.
.
C# ,
, ,
. ,
, ,
C# .
params.
, .
.
.
// .
using System;
class MyClass {
public int x;
public MyClass() {
Console.WriteLine(" MyClass().");
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, int).");
x = i * j;
}
}
class OverloadConsDemo {
static void Main() {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass(88);
MyClass t3 = new MyClass(17.23);
MyClass t4 = new MyClass(2, 4);
Console.WriteLine("t1.x: " + t1.x);
242
I. #
Console.WriteLine("t2.: " + t2.x);
Console.WriteLine("t3.x: " + t3.x);
Console.WriteLine("t4.x: " + t4.x);
}
}
.
t1.x: 0
t2.x: 88
t3.x: 17
t4.x: 8
MyClass().
MyClass(int).
MyClass(double).
MyClass(int, int).
MyClass() ,
-. ,
, new.
.
.
Stack, .
// .
using System;
class Stack {
// .
char[] stck; // ,
int tos;
//
// Stack .
public Stack(int size) {
stck = new char[size];
//
tos = 0;
}
// Stack .
public Stack(Stack ob) {
// .
stck = new char[ob.stck.Length];
// .
for(int i=0; i < ob.tos; 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] = ch;
tos++;
}
// .
public char Pop() {
if (tos==0) {
Console.WriteLine(" - .");
return (char) 0;
}
tos--;
return stck[tos];
}
// true, .
public bool IsFull() {
return tos==stck.Length;
}
// true, .
public bool IsEmpty() {
return tos==0;
}
// .
public int Capacity() {
return stck.Length;
}
// , .
244
I. #
stk1.Push((char) ('A' + i));
// stck1.
Stack stk2 = new Stack(stk1);
// stk1.
Console.Write(" stk1: ");
while( !stk1.IsEmpty() ) {
ch = stk1.Pop();
Console.Write(ch);
}
Console.WriteLine();
Console.Write(" stk2: ");
while( !stk2.IsEmpty() ) {
ch = stk2.Pop();
Console.Write(ch);
}
Console.WriteLine("\n");
}
}
.
-J stk1.
stk1: JIHGFEDCBA
stk2: JIHGFEDCBA
StackDemo (stk1),
. (stk2).
Stack.
// Stack .
public Stack(Stack ob) {
// .
stck = new char[ob.stck.Length];
// .
for(int i=0; i < ob.tos; i++)
stck[i] = ob.stck[i];
// tos .
tos = ob.tos;
}
, , ob.
, ob, ,
tos, .
, .
8.
245
this
,
. #
this. .
_(_1) : this(_2) {
// ... , .
}
,
_2,
, .
.
// this.
using System;
class XYCoord {
public int x, y;
public XYCoord():this(0, 0) {
Console.WriteLine(" XYCoord()");
}
public XYCoord(XYCoord obj) : this(obj.x, obj.y) {
Console.WriteLine(" XYCoord(obj)");
}
public XYCoord(int i, int j) {
Console.WriteLine(" XYCoord(int, int)");
x = i;
= j;
}
}
class OverloadConsDemo {
static void Main() {
XYCoord t1 = new XYCoord();
XYCoord t2 = new XYCoord(8,9);
XYCoord t3 = new XYCoord(t2);
Console.WriteLine("t1.x, t1.y: " + t1.x + ", " + t1.y);
Console.WriteLine("t2.x, t2.y: " + t2.x + ", " + t2.y);
Console.WriteLine("t3.x, t3.y: " + t3.x + ", " + t3.y);
}
}
.
XYCoord(int, int)
XYCoord()
XYCoord(int, int)
XYCoord(int, int)
246 I. C#
t1., t1.: 0,
t2., t2.: 8,
t3., t3.: 8,
XYCoord(obj)
0
9
9
.
, XYCoord,
XYCoord(int, int).
this. ,
t1, XYCoord(), this(0, 0),
XYCoord(0, 0).
t2.
this
, , , .
,
this .
" " ,
.
XYCoord.
public XYCoord(int ) : this(, ) { }
, . ,
" "
, .
. ( 10.)
,
,
. ,
.
LINQ-.
( LINQ- 19.)
, ,
.
.
// , .
using System;
class MyClass {
public int Count;
public string Str;
}
8.
247
class ObjInitDemo {
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 MyClass
.
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#
,
. ,
.
, ,
. ""
.
.
, .
.
.
static void OptArgMeth(int alpha, int beta=10, int gamma = 20) {
: beta gamma,
beta 10, gamma
20. ,
. ,
alpha . , ,
.
OptArgMeth(),
.
// .
OptArgMeth(1, 2, 3);
// gamma .
OptArgMeth(1, 2);
// beta gamma .
OptArgMeth(1);
alpha 1, beta
2, gamma 3. ,
, , , .
alpha 1, beta
2, gamma
20. , alpha
1, beta gamma
. , , , beta
,
gamma. ,
.
.
// .
using System;
class OptionArgDemo {
static void OptArgMeth(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);
// gamma .
OptArgMeth(1, 2);
// beta gamma .
OptArgMeth(1);
}
}
.
alpha, beta gamma: 1 2 3
alpha, beta gamma: 1 2 20
alpha, beta gamma: 1 10 20
, ,
, .
,
. ,
.
int Sample(string name = "", int userid) { // !
userId
name. ,
. ,
.
int Sample(int accountId, string name = "", int userId) { // !
name , userId
name ( ).
, ,
. ( .)
, , ,
. ,
.
. , ,
, ,
.
.
. , ,
250 I. C#
OptArgMeth(). C#
OptArgMeth(),
,
. .
static void OptArgMeth(int alpha)
static void OptArgMeth(int alpha, int beta)
static void OptArgMeth(int alpha, 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 = 20.0) {
Console.WriteLine(" alpha, beta gamma: " +
alpha + " " + beta + " " + gamma);
}
,
beta gamma,
. int,
double. OptArgMeth()
.
OptArgMeth(1); // - !
, ,
: , beta gamma
int, , double. ,
OptArgMeth() ,
.
,
, ,
. , ,
,
.
8.
251
,
, .
Display(),
.
// , .
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; i++)
Console.Write(str[i]);
Console.WriteLine();
}
static void Main() {
Display(" ");
Display(" ", 12);
Display(" ", 4, 14);
}
}
.
Display().
. ,
.
. stop ,
-1, ,
. start
, 0. ,
.
. ,
Display() (.. ),
. Display() ,
, ,
252
I. C#
start, . Display()
, , ,
start, , stop.
, , ,
, .
, ,
.
.
,
.
, . ,
,
.
.
,
. ,
. ,
,
. , ,
!
, ,
. C# 4.0.
, ,
, ,
. ,
.
. ,
.
. , -
,
.
.
_ :
_ ,
. , _
.
,
. IsFactor(),
true, .
// .
using System;
class NamedArgsDemo {
8.
253
// , .
static bool IsFactor(int val, int divisor) {
if((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.");
// .
if(IsFactor(divisor: 2, val: 10))
Console.WriteLine("2 - 10.");
// , .
if(IsFactor(10, divisor: 2))
Console.WriteLine("2 - 10.");
}
}
.
2
2
2
2
10.
10.
10.
10.
, IsFactor()
.
,
.
-, . ,
IsFactor() .
IsFactor(val :10, divisor: 2)
IsFactor(divisor: 2, val: 10)
. , ( )
. . -,
,
.
IsFactor(10, divisor: 2)
, , ,
.
254
I. C#
. Display(),
.
// .
Display(stop: 10, str: " ", start: 0);
// start .
Display(stop: 10, str: " ");
// , stop by name,
// start
Display(" ", stop: 10);
,
.
,
,
. , ,
.
,
, . (
.)
Main()
Main(). .
, .
.
Main()
Main() ( ).
Main().
static int Main()
, Main()
int void.
, , Main(),
-
.
,
.
8.
255
Main()
,
.. ,
. C#
Main().
Main().
static void Main(string[] args)
static int Main(string[] args)
Main() void,
, .
string,
Main(). (args)
, .
,
, .
// .
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.WriteLine(": " +
"1: <>/<> " +
"[2... N]");
return 1; //
}
// ,
// <> <>.
if(args[0]!= "" & args[0] != "") {
Console.WriteLine(" " +
"<> <>.");
return 1; //
}
// .
for(int n=1; n < args.Length; n++) {
for(int i=0; i < args[n].Length; i++) {
if(args[0] == "")
Console.Write((char) (args[n][i] + 1) );
else
Console.Write((char) (args[n][i] - 1) );
}
Console.Write(" ");
}
Console.WriteLine();
return 0;
}
}
,
, "" ""
, .
, , Cipher.
:\Cipher
:\Cipher
. -,
,
, . ,
8.
257
.
,
,
. ,
, . ,
"" ""
.
-, ,
.
, 1, .
0, .
C# , .
, , , . ,
, .
- .
, , .
.
.
N 1 N.
, 3 123, 6.
.
.
// .
using System;
class Factorial {
// .
public int FactR(int n) {
int result;
if(n==1) return 1;
result = FactR(n-1) * n;
return result;
}
// .
public int FactI(int n) {
int t, result;
result = 1;
for(t=1; t <= n; t++) result *= t;
return result;
}
}
258
I. C#
class Recursion {
static void Main() {
Factorial f = new Factorial();
Console.WriteLine(", .");
Console.WriteLine(" 3 " + f.FactR(3));
Console.WriteLine(" 4 " + f.FactR(4));
Console.WriteLine(" 5 " + f.FactR(5));
Console.WriteLine();
Console.WriteLine(", .");
Console.WriteLine(" 3 " + f.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,
, , .
FactR() .
FactR() 1, 1.
FactR(n-1)*n.
FactR() n-1.
, n 1,
. ,
2, FactR()
1. 1,
2 ( n). 2,
2(12). FactR()
, WriteLine(),
FactR(),
.
,
,
.
, .
, .
.
8.
259
.
DisplayRev().
// , .
using System;
class RevStr {
// .
public void DisplayRev(string str) {
if(str.Length > 0)
DisplayRev(str.Substring(1, str.Length-1));
else
return;
Console.Write(str[0]);
}
}
class RevStrDemo {
static void Main() {
string s = " ";
RevStr rsOb = new RevStr();
Console.WriteLine(" : " + s);
Console.Write(" : ");
rsOb.DisplayRev(s);
Console.WriteLine();
}
}
.
:
:
, DisplayRev(),
, str.
, DisplayRev() ,
. ,
.
DisplayRev().
, str,
.
,
-
. ,
.
260
I. C#
, -
. ,
(CLR) .
,
.
,
, . ,
.
, , ,
.
, if,
.
.
.
, WriteLine(),
,
.
static
,
. ,
,
. ,
static. static,
- . static
, . static
Main(), ,
.
static ,
-.
. static
, . , 10
count static, Timer,
.
Timer.count = 10;
,
, , .
static,
-.
, static, , .
, static
.
8.
261
static.
. ,
, , ,
, false,
bool. , static -
.
static ,
, .
. Sqrt() static,
System.Math #.
,
static.
// 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.Val);
StaticDemo.Val = 8;
Console.WriteLine(" " +
"StaticDemo.Val " + StaticDemo.Val);
Console.WriteLine("StaticDemo.ValDiv2(): " + StaticDemo.ValDiv2());
}
}
.
StaticDemo.Val 100
StaticDemo.Val 8
StaticDemo.ValDiv2(): 4
, static
.
static .
static this,
- .
262
I. C#
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() {
Console.WriteLine(" NonStaticMeth().");
}
/* !
. */
static void staticMeth() {
NonStaticMeth(); // !
}
}
(.. )
.
, static
,
. ,
8.
263
. ,
.
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 CountInst {
static int count = 0;
// , .
public CountInst() {
count++;
}
// , .
~Countlnst() {
count--;
}
public static int GetCount() {
return count;
}
}
class CountDemo {
static void Main() {
CountInst ob;
for(int i=0; i < 10; i++) {
264 I. C#
ob = new CountInst();
Console.WriteLine(" : " + CountInst.GetCount());
}
}
}
.
:
:
:
:
:
:
:
:
:
:
1
2
3
4
5
6
7
8
9
10
, CountInst, count
static. , , count
. , count
.
static.
, ,
.
.
, .
, ,
,
. static,
, .
,
.
// .
using System;
class MyClass {
int a, b;
// MyClass.
static public MyClass Factory(int i, int j) {
MyClass t = new MyClass();
t.a = i;
t.b = j;
return t; //
}
public void Show() {
Console.WriteLine(" b: " + a + " " + b);
8.
265
}
}
class MakeObjects {
static void Main() {
int i, j;
// , .
for(i=0, j=10; i < 10; i++, j--) {
MyClass ob = MyClass.Factory(i, j); //
ob.Show();
}
Console.WriteLine();
}
}
Factory()
.
MyClass ob = MyClass.Factory(i, j); //
MyClass,
.
static. ,
, ,
, .
-
.
.
// .
using System;
class Cons {
public static int alpha;
public int beta;
// .
static Cons() {
alpha = 99;
Console.WriteLine(" .");
}
// .
public Cons() {
beta = 100;
Console.WriteLine(" .");
}
}
266
I. C#
class ConsDemo {
static void Main() {
Cons ob = new Cons();
Console.WriteLine("Cons.alpha: " + Cons.alpha);
Console.WriteLine("ob.beta: " + ob.beta);
}
}
.
.
.
Cons.alpha: 99
ob.beta: 100
, static ,
, .
:
. ,
, ,
.
static.
. -, . -,
.
,
static.
static class _ { // ...
static.
, ,
.
. -,
.
LINQ 19.
-,
. .
NumericFn static
, .
NumericFn static,
static, .
, NumericFn ,
.
// .
using System;
8.
267
268
I. C#
,
. NumericFn ,
.
NumericFn.
: ,
, .
C#
.
.
.
. , +
,
,
.
,
.
, .
+, ,
, .. .
,
.
-
, #.
,
,
#.
#.
270
I. C#
.
operator, , ,
, .
(operator):
, .
.
// .
public static _ operator op(_ )
{
//
}
// .
public static _ operator op(_1 1,
_1 2)
{
//
}
, + /;
_ ,
. ,
, , .
.
,
1 2. ,
, public static.
, ,
.
, . , C#
, . ,
+ int string.
:
ref out.
,
, + -.
ThreeD,
. +
ThreeD .
- .
// .
using System;
9.
271
// .
class ThreeD {
int , , z;
//
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// +.
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/*
result. =
result. =
result.z =
. */
op1.x + 2.; //
op1.y + 2.; // ,
op1.z + op2.z; // .
return result;
}
// -.
public static ThreeD operator -(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/* :
op1 , 2 . */
result. = op1.x - 2.; //
result. = op1.y - 2.; //
result.z = op1.z - op2.z; //
return result;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c;
Console.Write(" a: ");
a.Show();
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
272
I. C#
= + b; // b
Console.Write(" + b: ");
.Show();
Console.WriteLine();
= + b + ; // , b
Console.Write(" + b + : ");
.Show();
Console.WriteLine();
= - ; //
Console.Write(" - : ");
.Show();
Console.WriteLine();
= - b; // b
Console.Write(" - b: ");
.Show();
Console.WriteLine();
}
}
.
: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
+ b + : 22, 24, 26
- : 21, 22, 23
- b: 11, 12, 13
,
+. + ThreeD,
,
operator+(). , , ,
,
ThreeD, .
, + ,
, :
10 + 12. 22, 10, 12.
, ,
.
, operator+() ThreeD.
C# ,
ThreeD, +
, a+b+. +b
ThreeD, .
9.
273
+b ,
a+b+ .
,
operator+(), ,
, z .
+ ThreeD
, ..
.
operator-(). -
, +, .
, (
), : - , - !
, . ,
, ,
.
, .
, , , .
,
ThreeD.
// .
public static ThreeD operator - (ThreeD op)
{
ThreeD result = new ThreeD ();
result.x = -op.x;
result. = -op.;
result.z = -op.z;
return result;
}
,
,
. ,
. ,
. ,
= -b
b, b .
C# ++ -- .
,
. #,
.
operator++() ThreeD.
274 I. #
// ++.
public static ThreeD operator ++(ThreeD op)
{
ThreeD result = new ThreeD();
// .
result.x = op.x + 1;
result. = op. + 1;
result.z = op.z + 1;
return result;
}
,
- ++.
// .
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// +.
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/* . */
result. = op1.x + 2.;
result. = op1.y + 2.;
result.z = op1.z + op2.z;
return result;
}
// -.
public static ThreeD operator -(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/* :
op1 , 2 . */
result. = op1.x - 2.;
result. = op1.y - 2.;
result.z = op1.z - op2.z;
return result;
}
// -.
public static ThreeD operator -(ThreeD op)
9.
{
ThreeD result = new ThreeD();
result.x = -op.x;
result. = -op.y;
result.z = -op.z;
return result;
}
// ++.
public static ThreeD operator ++(ThreeD op)
{
ThreeD result = new ThreeD();
// .
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 ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
Console.Write(" a: ");
a.Show();
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
= a + b; // b
Console.Write(" a + b: ");
c.Show();
Console.WriteLine();
c = a + b + c; // a, b
Console.Write(" a + b + : ");
.Show();
Console.WriteLine();
275
276
I. C#
= - ; //
Console.Write(" - : ");
.Show();
Console.WriteLine();
= - b; // b
Console.Write(" - b: ");
.Show();
Console.WriteLine();
= -a; //
Console.Write(" -: ");
.Show();
Console.WriteLine();
= ++; // ,
//
Console.WriteLine(" = ++");
Console.Write(" ");
.Show();
Console.Write(" ");
.Show();
// (1,2,3)
= new ThreeD(1, 2, 3);
Console.Write("\n : ");
.Show();
= ++; // ,
//
Console.WriteLine("\n = ++");
Console.Write(" ");
.Show();
Console.Write(" ");
.Show();
}
}
.
: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
+ b + : 22, 24, 26
- : 21, 22, 23
- b: 11, 12, 13
-: -1, -2, -3
= ++
1, 2, 3
9.
277
2, 3, 4
: 1, 2, 3
= ++
2, 3, 4
2, 3, 4
C#
. , , ,
, .
ThreeD. ,
+ ThreeD
.
ThreeD. ,
ThreeD.
. + ,
.
// +
// ThreeD int.
public static ThreeD operator +(ThreeD op1, int op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2;
result. = op1.y + op2;
result.z = op1.z + op2;
return result;
}
, int. ,
ThreeD. , , ,
,
, .
.
ThreeD
+.
// + :
// - ThreeD,
// ThreeD int.
using System;
// .
class ThreeD {
int , , z; //
278
I. #
public ThreeD() { x = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// + ThreeD.
public static ThreeD operator + (ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/*
result. =
result. =
result.z =
. */
op1.x + 2.;
op1. + 2.;
op1.z + op2.z;
return result;
}
// +
// ThreeD int.
public static ThreeD operator +(ThreeD opl, int op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2;
result. = op1. + op2;
result.z = op1.z + op2;
return result;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
Console.Write(" a; ");
a.Show();
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
= a + b; // ThreeD
Console.Write(" a + b: ");
c.Show();
Console.WriteLine();
c = b + 10; // ThreeD int
9.
279
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { x = y = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
280
I. #
// + ThreeD.
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
/*
result. =
result. =
result.z =
. */
op1.x + 2.;
op1.y + 2.;
op1.z + op2.z;
return result;
}
// +
// ThreeD int.
public static ThreeD operator +(ThreeD op1, int op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2;
result. = op1.y + op2;
result.z = op1.z + op2;
return result;
}
// +
// int ThreeD.
public static ThreeD operator +(int op1, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op2.x + op1;
result. = op2.y + op1;
result.z = op2.z + op1;
return result;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(l, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
Console.Write(" a: ");
a.Show();
9.
281
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
= a + b; // ThreeD
Console.Write(" a + b: ");
c.Show();
Console.WriteLine();
c = b + 10; // ThreeD int
Console.Write(" b + 10: ");
.Show();
Console.WriteLine();
= 15 + b; // int ThreeD
Console.Write(" 15 + b: ");
.Show();
}
}
.
: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
b + 10: 20, 20, 20
15 + b: 25, 25, 25
, == <, ,
. ,
true false.
.
,
.
ThreeD,
< >.
ThreeD, .
, . ,
, .
, , ,
.
true, . ,
.
282
I. #
// < >.
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// <.
public static bool operator <(ThreeD op1, ThreeD op2)
{
if(Math.Sqrt(op1.x * op1.x + op1.y * op1.y + op1.z * op1.z) <
Math.Sqrt(op2.x * op2.x + op2. * op2.y + op2.z * op2.z))
return true;
else
return false;
}
// >.
public static bool operator >(ThreeD op1, ThreeD op2)
{
if(Math.Sqrt(op1.x * op1.x + op1.y * op1.y + op1.z * op1.z) >
Math.Sqrt(op2.x * op2.x + op2. * op2. + op2.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(1,2,3);
ThreeD d = new ThreeD(6,7,5);
Console.Write("
a.Show();
Console.Write("
b.Show();
Console.Write("
c.Show();
Console.Write("
d.Show();
Console.WriteLine();
a: ");
b: ");
: ");
d: ");
9.
if(
if(
if(
if(
>
<
>
<
)
)
b)
b)
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
>
<
>
<
b
b
283
");
");
");
");
:
b:
:
d:
5, 6, 7
10, 10, 10
1, 2, 3
6, 7, 5
>
< b
a d
: . , <,
>, .
.
==
<
<=
!=
>
>=
: == !=,
Object.Equals() Object.
GetHashCode().
11.
true false
true false
.
true false
.
if, while, for do-while ?.
true false , .
.
public static bool operator true(_ )
{
// true false.
284
I. #
}
public static bool operator false(_ )
{
// true false.
}
,
bool.
,
true false ThreeD.
: ThreeD ,
, , .
.
// true false ThreeD.
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// true.
public static bool operator true(ThreeD op) {
if((op.x != 0) || (op. != 0) || (op.z != 0))
return true; //
else
return false;
}
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op. == 0) && (op.z == 0))
return true; //
else
return false;
}
// --.
public static ThreeD operator --(ThreeD op)
{
ThreeD result = new ThreeD();
// .
result.x = op.x - 1;
result. = op. - 1;
result.z = op.z - 1;
return result;
9.
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class TrueFalseDemo {
static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD (0, 0, 0);
Console.Write(" a: ");
a.Show();
Console.Write(" b: ");
b.Show();
Console.Write(" : ");
c.Show();
Console.WriteLine();
if(a) Console.WriteLine(" .");
else Console.WriteLine(" .");
if(b) Console.WriteLine(" b .");
else Console.WriteLine(" b .");
if() Console.WriteLine(" .");
else Console.WriteLine(" .");
Console.WriteLine();
Console.WriteLine("
ThreeD.");
do {
b.Show();
b--;
} while(b);
}
}
.
: 5, 6, 7
b: 10, 10, 10
: 0, 0, 0
b
ThreeD.
10, 10, 10
285
I. #
286
9,
8,
7,
6,
5,
4,
3,
2,
1,
9,
8,
7,
6,
5,
4,
3,
2,
1,
9
8
7
6
5
4
3
2
1
, ThreeD
if do-while. , if
ThreeD true.
, if .
do-while b . ,
, b , ..
. ,
b , true
.
, C#
: &, |, !, && ||. , ,
&, | !. , ,
&& ||.
.
.
, & |
, bool.
, , !.
,
!, & | ThreeD. ,
ThreeD ,
. , .
//
// !, | & ThreeD.
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
9.
// |.
public static bool operator |(ThreeD op1, ThreeD op2)
{
if( ((op1.x != 0) || (op1. != 0) || (op1.z != 0)) |
((op2.x != 0) || (op2. != 0) || (op2.z != 0)) )
return true;
else
return false;
}
// &.
public static bool operator &(ThreeD op1, ThreeD op2)
{
if( ((op1.x != 0) && (op1. != 0) && (op1.z != 0)) &
((op2.x != 0) && (op2.y != 0) && (op2.z != 0)) )
return true;
else
return false;
}
// !.
public static bool operator !(ThreeD op)
{
if((op.x != 0) || (op.y != 0) || (op.z != 0))
return false;
else return true;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class TrueFalseDemo {
static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(0, 0, 0);
Console.Write(" a: ");
a.Show();
Console.Write(" b: ");
b.Show();
Console.Write(" : ");
c.Show();
Console.WriteLine();
if(!a) Console.WriteLine(" .");
if(!b) Console.WriteLine(" b .");
if(!c) Console.WriteLine(" .");
Console.WriteLine();
287
288
I. C#
&
&
|
|
.
.
.
.
&, | !
bool. ,
, .. ,
bool. , C#
bool.
bool
. , ,
, .
&& ||
, . -,
& |. -,
& | ,
, . -,
,
. -, true
false. ,
.
,
& | ThreeD,
&& ||.
9.
289
/*
!, | & ThreeD.
&& ||
. */
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// | .
public static ThreeD operator |(ThreeD op1, ThreeD op2)
{
if( ((op1.x != 0) || (op1.y != 0) || (op1.z != 0)) |
((op2.x != 0) || (op2. != 0) || (op2.z != 0)) )
return new ThreeD(1, 1, 1);
else
return new ThreeD(0, 0, 0);
}
// & .
public static ThreeD operator &(ThreeD op1, ThreeD op2)
{
if( ((op1.x != 0) && (op1.y != 0) && (op1.z != 0)) &
((op2.x != 0) && (op2.y != 0) && (op2.z != 0)) )
return new ThreeD(1, 1, 1);
else
return new ThreeD(0, 0, 0);
}
// !.
public static bool operator !(ThreeD op)
{
if(op) return false;
else return true;
}
// true.
public static bool operator true(ThreeD op) {
if((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
290 I. C#
return false;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class TrueFalseDemo {
static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD(0, 0, 0);
Console.Write(" a: ");
a.Show();
Console.Write(" b: ");
b.Show();
Console.Write(" : ");
c.Show();
Console.WriteLine();
if(a) Console.WriteLine(" .");
if(b) Console.WriteLine(" b .");
if() Console.WriteLine(" .");
if(!a) Console.WriteLine(" .");
if(!b) Console.WriteLine(" b .");
if(!) Console.WriteLine(" .");
Console.WriteLine();
Console.WriteLine(" & |");
if(a & b) Console.WriteLine(" & b .");
else Console.WriteLine(" & b .");
if( & ) Console.WriteLine(" & .");
else Console.WriteLine(" & .");
if( | b) Console.WriteLine("a | b .");
else Console.WriteLine(" | b .");
if( | ) Console.WriteLine(" | .");
else Console.WriteLine(" | .");
Console.WriteLine();
// .
Console.WriteLine(" " +
" && ||");
if(a && b) Console.WriteLine("a && b .");
else Console.WriteLine(" && b .");
9.
291
292
I. C#
,
ThreeD.
, .
, ThreeD,
.
, . ,
& b :
if ( & b) Console.WriteLine(" & b .");
else Console.WriteLine(" & b .");
ThreeD, .
true false , ThreeD
true
bool. true, , if
.
,
ThreeD.
. operator true
( ||) operator false (
&&). ,
(& |) .
(& | )
. , &&
||, & | ,
.
.
if( || ) Console.WriteLine(" || .");
true .
, |
. :
if( || a) Console.WriteLine(" || .");
true ,
. ,
|.
, , , ,
.
true false
, .
. ,
& | , , ,
.
,
.
9.
293
,
. C#
,
. .
#,
, , .
: .
:
public static explicit operator _(_ v) {return ;}
public static implicit operator _(_ v) {return ;}
_ , ;
_ , ; ,
.
, _,
.
(implicit),
, , ,
.
(explicit), ,
.
.
ThreeD,
. ,
ThreeD , .
, ,
.
.
public static implicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
,
.
// .
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// +.
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
294
I. #
ThreeD result = new ThreeD);
result.x = op1.x + op2.x;
result. = op1. + op2.y;
result.z = op1.z + op2.z;
return result;
}
// ThreeD int.
public static implicit operator int(ThreeD op1)
{
return op1.x * op1. * op1.z;
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
int i;
Console.Write(" a: ");
a.Show();
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
= a + b; // b
Console.Write(" a + b: ");
c.Show();
Console.WriteLine();
i = a; // int
Console.WriteLine(" i = a: " + i);
Console.WriteLine();
i = a * 2 - b; // int
Console.WriteLine(" a * 2 - b: " + i
}
}
.
: 1, 2, 3
b: 10, 10, 10
9.
295
+ b: 11, 12, 13
i = : 6
* 2 - b: -988
, ThreeD
, i = ,
.
6, ,
. int
, .
operator int() = + b.
. ,
ThreeD double
.
.
: ; ;
.
, ,
, .
.
,
int.
// .
using System;
// .
class ThreeD {
int , , z; //
public ThreeD() { = = z = 0; }
public ThreeD(int i, int j, int k) { x = i; = j; z = k; }
// +.
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2.x;
result. = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
}
// .
public static explicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
296
I. #
}
// X, Y, Z.
public void Show()
{
Console.WriteLine(x + ", " + + ", " + z);
}
}
class ThreeDDemo {
static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD = new ThreeD();
int i;
Console.Write(" a: ");
a.Show();
Console.WriteLine();
Console.Write(" b: ");
b.Show();
Console.WriteLine();
= a + b; // b
Console.Write(" a + b: ");
c.Show();
Console.WriteLine();
i = (int) a; // int ,
//
Console.WriteLine(" i = : " + i);
Console.WriteLine();
i = (int)a * 2 - (int)b; //
Console.WriteLine(" * 2 - b: " + i);
}
}
,
int. ,
, .
i = (int) ; // int ,
//
.
,
. ,
int,
double.
object .
.
9.
297
. (
11.)
. (
12.)
, ,
. ,
, .
, . -,
, , , . , .
,
.
,
,
C# .
, ,
. , +
ThreeD
. , , +
,
/, .
: ,
,
.
. ,
,
, .
, , . ,
, ,
, , +=. ,
. ,
.
&&
??
=>
default
typeof
()
[]
->
is
unchecked
.
||
as
new
?
=
checked
sizeof
() ,
, .
298 I. C#
, , , +=,
, . ,
, .
, +=
operator+(). ,
operator+() ThreeD,
b 11, 12, 13.
ThreeD = new ThreeD(l, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
b += a; // b
: , []
,
, .
, ,
ThreeD,
. ,
.
, ,
,
.
4-
. , , ,
4- , ,
,
,
! ,
- #.
.
Nybble. int,
0 15. Nybble
.
Nybble.
int Nybble.
Nybble int.
: (>) (<).
.
int Nybble.
Nybble int.
9.
299
, ,
Nybble #.
.
.
Nybble, NybbleDemo,
.
// 4- Nybble.
using System;
// 4- .
class Nybble {
int val; //
public Nybble() { val = 0; }
public Nybble(int i) {
val = i;
val = val & 0xF; // 4
}
// + Nybble.
300
I. C#
result.val = result.val & 0xF; // 4
return result;
}
// ++.
public static Nybble operator ++(Nybble op)
{
Nybble result = new Nybble();
result.val = op.val + 1;
result.val = result.val & 0xF; // 4
return result;
}
// >.
public static bool operator >(Nybble op1, Nybble op2)
{
if(op1.val > op2.val) return true;
else return false;
}
// <.
public static bool operator <(Nybble op1, Nybble op2)
{
if(op1.val < op2.val) return true;
else return false;
}
// Nybble int.
public static implicit operator int (Nybble op)
{
return op.val;
}
// int Nybble.
public static implicit operator Nybble (int op)
{
return new Nybble(op);
}
}
class NybbleDemo {
static void Main() {
Nybble a = new Nybble(1);
Nybble b = new Nybble(10);
Nybble = new Nybble();
int t;
Console.WriteLine("a: " + (int) a);
Console.WriteLine("b: " + (int) b);
// Nybble if.
9.
301
Console.WriteLine();
// int .
= 19;
Console.WriteLine(" = 19: " + (int) );
Console.WriteLine();
// Nybble .
Console.WriteLine(" for " +
" Nybble.");
for( = 0; < 10; ++)
Console.Write((int) + " ");
Console.WriteLine();
}
}
.
: 1
b: 10
b
= + b: 11
+= 5: 6
* 2 + 3: 15
= 19: 3
for Nybble.
0 1 2 3 4 5 6 7 8 9
Nybble .
,
Nybble #. ,
Nybble
, int
. .
t = * 2 + 3;
302 I. C#
t 2 3 int,
Nybble.
Nybble int.
int, int
.
int Nybble int
Nybble. ,
:
= 19;
int Nybble.
Nybble, 4
19, , 3, 19
Nybble.
.
.
, Nybble Nybble for.
for
.
Nybble,
,
. .
( 13.)
10
:
. -
,
# .
,
,
.
, C#
: .
,
[].
[],
, ,
. ,
, ,
,
.
,
,
. - .
.
304
I. C#
:
_ this[int ] {
// .
get {
// , .
}
// .
set {
// , .
}
}
_ . ,
, ,
_. .
, .
int,
, , ,
.
(.. ): get
set. , ,
.
, . ,
,
set , .
get ,
. , set value,
, .
, , ,
, .
, FailSoftArray,
, ,
,
.
,
.
,
. FailSoftArray
, .
// .
using System;
class FailSoftArray {
int[] a; //
public int Length; //
10.
public bool ErrFlag; //
// .
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}
// FailSoftArray.
public int this[int index] {
// get.
get {
if(ok(index)) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;
}
}
// set.
set {
if(ok(index)) {
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
// 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("\n .");
for (int i=0; i < (fs.Length * 2); i++) {
fs[i] = i * 10;
if(fs.ErrFlag)
Console.WriteLine("fs[" + i + "] ");
}
for(int i=0; i < (fs.Length * 2); i++) {
x = fs[i];
if(!fs.ErrFlag) Console.Write(x + " ");
else
Console.WriteLine("fs[" + i + "] ");
}
}
}
.
.
0 10 20 30 40 0 0 0 0 0
.
fs[5]
fs[6]
fs[7]
fs[8]
fs[9]
0 10 20 30 40 fs[5]
fs[6]
fs[7]
fs[8]
fs[9]
.
. .
public int this[int index] {
, int.
index. ,
(public),
.
get.
get {
if(ok(index)) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;
}
}
10.
307
get ,
, .
ok(), true,
, false. ,
,
. ,
, .
FailSoftArray ErrFlag
.
. ( 13
C#
,
.)
set,
.
set {
if(ok(index)) {
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
index ok() ,
,
value. true
ErrFlag. , value
, . ( )
.
, get set, .
, ,
get, set.
.
,
, . ,
FailSoftArray
double. double
.
// FailSoftArray.
using System;
class FailSoftArray {
int[] a; //
public int Length; //
308
I. C#
10.
309
// .
if( (idx - (int) idx) < 0.5) index = (int) idx;
else index = (int) idx + 1;
if(ok(index)) {
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
// 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("fs[1] : " + fs[1]);
Console.WriteLine("fs[2] : " + fs[2]);
Console.WriteLine("fs[1.1]: " + fs[l.l]);
Console.WriteLine("fs[1.6]: " + fs[1.6]);
}
}
.
fs[1]: 1
fs[2]: 2
fs[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.Write(" 8 2: ");
for(int i=0; i < 8; i++)
Console.Write(pwr[i] + " ");
Console.WriteLine();
Console.Write(" : ");
Console.Write(pwr[-1] + " " + pwr[17]);
Console.WriteLine();
}
}
10.
311
.
8 2: 1 2 4 8 16 32 64 128
: -1 -1
, PwrOfTwo
get, set. ,
. , PwrOfTwo
, . ,
.
pwr[0] = 11; //
, set.
.
-, , ,
ref out,
. -,
static.
.
.
.
// .
using System;
class FailSoftArray2D {
int[,] a; //
int rows, cols; //
public int Length; //
public bool ErrFlag; //
// .
public FailSoftArray2D(int r, int ) {
rows = r;
cols = ;
= new int[rows, cols];
Length = rows * cols;
}
// FailSoftArray2D.
public int this[int index1, int index2] {
// get.
get {
if(ok(index1, index2)) {
ErrFlag = false;
return a[index1, index2];
} else {
312
I. C#
ErrFlag = true;
return 0;
}
}
// set.
set {
if(ok(index1, index2)) {
a[index1, index2] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
// true,
// .
private bool ok(int index1, int index2) {
if (index1 >= 0 & index1 < rows &
index2 >= 0 & index2 < cols)
return true;
return false;
}
}
// .
class TwoDIndexerDemo {
static void Main() {
FailSoftArray2D fs = new FailSoftArray2D(3, 5);
int x;
// .
Console.WriteLine(" .");
for (int i=0; i < 6; i++)
fs[i, i] = i*10;
for(int i=0; i < 6; i++) {
x = fs[i,i];
if(x != -1) Console.Write(x + " ");
}
Console.WriteLine();
// .
Console.WriteLine("\n .");
for(int i=0; i < 6; i++) {
fs[i,i] = i*10;
if(fs.ErrFlag)
Console.WriteLine("fs[" + i + ", " + i + "] ");
}
for(int i=0; i < 6; i++) {
x = fs[i,i];
if(!fs.ErrFlag) Console.Write(x + " ");
10.
313
else
Console.WriteLine("fs[" + i + ", " + i + "] ");
}
}
}
:
.
0 10 20 0 0 0
.
fs[3, 3]
fs[4, 4]
fs[5, 5]
0 10 20 fs[3, 3]
fs[4, 4]
fs[5, 5]
. ,
.
, ,
, ,
, , ,
. , ,
, ,
.
. ,
get set.
. ,
,
get set.
get set .
:
{
get {
//
}
set {
//
}
, int,
. ,
. ,
set value, ,
.
314
I. C#
, , ,
, . ,
, .
( ,
.)
,
MyProp, prop.
.
// .
using System;
class SimpProp {
int prop; // , r
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.r: " + ob.r);
ob.r = 100; //
Console.WriteLine(" ob.r: " + ob.r);
// prop .
Console.WriteLine(" " +
"-10 ob.r");
ob.r = -10;
Console.WriteLine(" ob.r: " + ob.r);
}
}
.
ob.r: 0
ob.r: 100
-10 ob.r
ob.r: 100
10.
315
.
prop MyProp, prop.
, ,
. , prop ,
, MyProp.
MyProp public, ,
. ,
prop, . get
prop, set
prop ,
. , MyProp ,
prop. , , .
MyProp , ,
.
. ,
, ,
get. , ,
set.
. ,
(Length). FailSoftArray
Length.
, ,
. (, , ,
.)
, Length " ",
, FailSoftArray.
// Length FailSoftArray.
using System;
class FailSoftArray {
int[] 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 = fs[i];
if(x != -1) Console.Write(x + " ");
}
Console.WriteLine();
// fs.Length = 10; // , !
}
}
Length ,
len. -
10.
317
ceccop get, . ,
Length , . ,
.
// fs.Length = 10; // , !
,
, Length , .
Length FailSoftArray
.
, ,
ErrFlag, .
FailSoftArray,
Error,
ErrFlag, .
// ErrFlag .
using System;
class FailSoftArray {
int[] 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. #
} 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;
if(fs.Error)
tonsole.WriteLine(" " + i);
}
}
}
Error
FailSoftArray. -, ErrFlag ,
Error,
, . -,
Error " ". Error
, .
Main(),
, Error.
C# 3.0,
, , .
.
:
10.
319
{ get; set; }
, .
, get set
, .
,
, .
. .
,
UserCount.
public int UserCount { get; set; }
, .
, ,
. UserCount
.
.
get set.
(..
) , private
( " ").
,
,
. ,
. , ,
,
. ,
, .
,
,
.
8,
.
,
.
, .
8,
. , 8
, , Count
Str .
.
// .
using System;
320
I. C#
class MyClass {
// .
public int Count { get; set; }
public string Str { get; set; }
}
class ObjInitDemo {
static void Main() {
// MyClass
.
MyClass obj =
new MyClass { Count = 100, Str = "" };
Console.WriteLine(obj.Count + " " + obj.Str);
}
}
, Count Str
. ,
8, :
100
8,
, LINQ-.
.
,
. -,
,
ref out. -, .
, , ,
, . ,
get.
, .
get
.
set get ,
, . ,
public, set get
(public). set get
, private. ,
, ,
, .
,
. , ,
10.
321
.
private.
MyProp, set
private.
// .
using System;
class PropAccess {
int prop; // , r
public PropAccess() { prop = 0; }
/* prop.
prop ,
. */
public int r {
get {
return prop;
}
private set { //
prop = value;
}
}
// r.
public void IncrProp() {
MyProp++; // . .
}
}
// .
class PropAccessDemo {
static void Main() {
PropAccess ob = new PropAccess();
Console.WriteLine(" ob.r: " + ob.r);
// ob.r = 100; //
ob.IncrProp();
Console.WriteLine(" ob.r : " +
ob.r);
}
}
PropAccess set private. ,
, IncrProp(),
PropAccess.
ob.r PropAccessDemo .
,
. ,
322
I. C#
, , get set,
. ,
private.
Length
FailSoftArray,
.
public int Length { get; private set; }
Length ,
set private. Length
. , ,
, .
Error, .
public bool Error { get; private set; }
Error ,
FailSoftArray.
Length Error
FailSoftArray len ErrFlag,
, len ErrFlag
Length Error FailSoftArray.
FailSoftArray Main(),
.
//
// Length Error.
using System;
class FailSoftArray {
int[] a; //
// .
public FailSoftArray(int size) {
a = new int [size];
Length = size;
}
// Length.
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);
}
}
}
FailSoftArray ,
, , .
. -,
: set get, . -,
,
. ,
, . (
12.)
324
I. C#
,
. RangeArray,
, .
, C#
.
: 1 ,
-5 5. RangeArray ,
.
RangeArray, .
RangeArray r = new RangeArray(-5, 10); // -5 10
for(int i=-5; i <= 10; i++) ra[i] = i; // -5 10
,
RangeArray -5 10 .
, .
r ,
-5 10.
RangeArray RangeArrayDemo,
.
RangeArray , 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.
325
// 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] = value;
Error = false;
}
else Error = true;
}
}
// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound) return true;
return false;
}
}
//
// .
class RangeArrayDemo {
static void Main() {
RangeArray ra = new RangeArray(-5, 5);
RangeArray ra2 = new RangeArray(1, 10);
RangeArray ra3 = new RangeArray(-20, -12);
// ra .
Console.WriteLine(" ra: " + r.Length);
for(int i = -5; i <= 5; i++)
326 I. C#
ra[i] = i;
Console.Write(" ra: ");
for(int i = -5; i <= 5; i++)
Console.Write(ra[i] + " ");
Console.WriteLine("\n");
// ra2 .
Console.WriteLine(" ra2: " + ra2.Length);
for(int i = 1; i <= 10; i++)
ra2[i] = i;
Console.Write(" ra2: ");
for(int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " ");
Console.WriteLine("\n");
// ra .
Console.WriteLine(" ra3: " + ra3.Length);
for(int i = -20; i <= -12; i++)
ra3[i] = i;
Console.Write(" ra3: ");
for(int i = -20; i <= -12; i++)
Console.Write(ra3[i] + " ");
Console.WriteLine("\n");
}
}
.
ra: 11
ra: -5 -4 -3 -2 -1 0 1 2 3 4 5
ra2: 10
ra2: 1 2 3 4 5 6 7 8 9 10
ra3: 9
ra2: -20 -19 -18 -17 -16 -15 -14 -13 -12
,
RangeArray ,
, .
RangeArray.
RangeArray
.
// .
int[] ; //
int lowerBound; //
int upperBound; //
10.
327
.
RangeArray.
lowerBound,
upperBound.
Length Error.
// Length.
328
I. C#
}
// set.
set {
if(ok(index)) {
a[index - lowerBound] = value;
Error = false;
}
else Error = true;
}
}
, FailSoftArray,
. ,
.
index - lowerBound
, index,
, .
lowerBound: ,
.
ok().
// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound) return true;
return false;
}
FailSoftArray,
,
lowerBound upperBound.
RangeArray
, .
, , . , ,
, ,
.
.
11
-
,
.
,
,
. ,
,
.
C# , ,
, , , .
,
.
, , ,
,
.
C# ,
.
. .
TwoDShape,
, ,
, ..
// .
class TwoDShape {
public double Width;
330
I. #
11.
331
t1.ShowStyle();
t1.ShowDim();
Console.WriteLine(" " + t1.Area());
Console.WriteLine();
Console.WriteLine(" t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine(" " + t2.Area());
}
}
.
t1:
4 4
8
t2:
8 12
48
Triangle TwoDShape (
). , Triangle TwoDShape,
, , Area() ShowStyle(). ,
Style, Area()
, ShowStyle() .
, Triangle
TwoDShape.
class Triangle : TwoDShape {
. ,
, ,
. C#
.
Triangle TwoDShape,
Width Height Area(). ,
t1 t2 Main() Width
Height, Triangle. . 11.1
, TwoDShape Triangle.
Width
TwoDShape
Height
ShowDim()
Triangle
Style
Area()
ShowStyle()
. 11.1. Triangle
332
I. #
TwoDShape Triangle,
.
, ,
. ,
.
TwoDShape shape = new TwoDShape();
shape.Width = 10;
shape.Height = 20;
shape.ShowDim();
, 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,
IsSquare(), , ,
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);
}
}
Triangle ,
Width Height Area() . Width
Height ,
, .
.
, .
334
I. #
,
,
.
. C# .
(protected) ,
,
.
,
. ,
. ,
, ,
,
.
TwoDShape, Width Height
. :
Width Height. , ,
Width 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 ShowStyle() {
Console.WriteLine(" " + Style);
}
}
class Shapes2 {
static void Main() {
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.Width = 4.0;
t1.Height = 4.0;
t1.Style = "";
t2.Width = 8.0;
t2.Height = 12.0;
t2.Style = "";
Console.WriteLine(" t1: ");
t1.ShowStyle();
t1.ShowDim();
Console.WriteLine(" " + t1.Area());
Console.WriteLine();
Console.WriteLine(" t2: ");
t2.ShowStyle ();
t2.ShowDim();
Console.WriteLine(" " + t2.Area());
}
}
Width Height
pri_width pri_height TwoDShape,
. ,
pri_width pri_height TwoDShape
, , .
. Java.
, Java , C# . ,
Java , C# .
,
- C#
, C++.
336 I. C#
,
. ,
.
, ,
. , ,
C# .
, .
protected.
protected, ,
, .
, ,
. ,
protected, , ,
.
protected.
// 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); // , D
11.
337
ob.Show(); // , D
ob.Setk(); // , D
ob.Showk(); // , D
}
}
D, i j
protected, Setk(). i j
private, D,
.
public private, protected
.
,
,
, .
,
. , TwoDShape ,
Width Height ,
, ,
, protected.
, ,
. , protected
, ,
, .
.
,
. :
:
, ?
: ,
.
,
, , .
,
, C# .
. ,
.
,
: ,
, .
Triangle,
, Style ,
.
// Triangle.
using System;
338
I. C#
// .
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() {
Console.WriteLine(" " +
Width + " " + Height);
}
}
// , TwoDShape.
11.
339
Console.WriteLine();
Console.WriteLine(" t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine(" " + t2.Area());
}
}
Triangle
TwoDShape Style.
, ,
,
.
#: base, : -,
; -, ,
.
base.
base ,
.
:
__(_) : base(_) {
//
}
_ ,
. .
base
, TwoDShape
. ,
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#
11.
341
Triangle .
public Triangle(
string s, double w, double h) : base(w, h) {
Triangle() base
w h. , , TwoDShape(),
Width Height w h.
Triangle,
Style, .
TwoDShape
. , TwoDShape
, ,
.
base ,
, ,
.
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 : value; }
}
public double Height {
get { return pri_height; }
342 I. #
set { pri_height = value < 0 ? -value : value; }
}
public void ShowDim() {
Console.WriteLine(" " +
Width + " " + Height);
}
}
// , TwoDShape.
class Triangle : TwoDShape {
string Style;
/* , .
,
TwoDShape. */
public Triangle() {
Style = "null";
}
// , .
public Triangle(
string s, double w, double h) : base (w, h) {
Style = s;
}
// .
public Triangle(double x) : base(x) {
Style = "";
}
// .
public double Area() {
return Width * Height / 2;
}
// .
public void ShowStyle() {
Console.WriteLine(" " + Style);
}
}
class Shapes5 {
static void Main() {
Triangle t1 = new Triangle();
Triangle t2 = new Triangle("",8.0, 12.0);
Triangle t3 = new Triangle(4.0);
t1 = t2;
Console.WriteLine(" t1: ");
t1.ShowStyle();
t1.ShowDim();
Console.WriteLine(" " + t1.Area());
11.
343
Console.WriteLine();
Console.WriteLine(" t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine(" " + t2.Area());
Console.WriteLine();
Console.WriteLine(" t3: ");
t3.ShowStyle();
t3.ShowDim();
Console.WriteLine(" " + t3.Area());
Console.WriteLine();
}
}
.
t1:
8 12
48
t2:
8 12
48
t3:
4 4
8
base.
base,
. , base
,
. .
base().
, ,
.
,
.
. C# ,
, , .
,
new, . ,
344
I. C#
, , new,
.
.
// .
using System;
class {
public int i = 0;
}
// .
class : {
new int i; // i
public (int b) {
i = b; // i
}
public void Show() {
Console.WriteLine(" i : " + i);
}
}
class NameHiding {
static void Main() {
ob = new (2);
ob.Show();
}
}
new
.
new int i; // i
, , ,
i i
. new
, .
.
i : 2
i,
i . Show()
i, , ,
.
base
base,
this, ,
11.
345
, .
:
base.
.
base ,
.
.
// base
// , .
using System;
class {
public int i = 0;
}
// .
class : {
new int i; // i
public (int a, int b) {
base.i = ; //
i = b; // i
}
public void Show() {
// i .
Console.WriteLine(" i : " + base.i);
// i .
Console.WriteLine(" i : " + i);
}
}
class UncoverName {
static void Main() {
ob = new (1, 2);
ob.Show();
}
}
.
i : 1
i : 2
i
i , base
i, .
base .
,
Show(). Show()
base Show(), .
346
I. C#
// .
using System;
class {
public int i = 0;
// Show() A
public void Show() {
Console.WriteLine(" i : " + i);
}
}
// .
class : {
new int i; // i
public (int a, int b) {
base.i = ; //
i = b; // i
}
// Show() .
// new.
new public void Show() {
base.Show(); // Show()
// i
Console.WriteLine(" i : " + i);
}
}
class UncoverName {
static void Main() {
ob = new (1, 2);
ob.Show();
}
}
.
i : 1
i : 2
, base.Show() Show()
.
: new
, Show(),
, Show(),
.
, . 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) : base(w, h) {
Style = s;
}
// .
public Triangle(double x) : base(x) {
Style = "";
}
// .
public double Area() {
return Width * Height / 2;
}
// .
public void ShowStyle() {
Console.WriteLine(" " + Style);
}
}
// Triangle.
class ColorTriangle : Triangle {
string color;
public ColorTriangle(string c, string s,
double w, double h) : base(s, w, h) {
color = c;
}
// .
public void ShowColor() {
Console.WriteLine(" " + color);
}
}
class Shapes6 {
static void Main() {
ColorTriangle t1 =
new ColorTriangle("", "", 8.0, 12.0);
ColorTriangle t2 =
11.
349
:
,
, , ? ,
350
I. C#
,
? ,
: . ,
base.
, base ,
, .. .
.
// .
using System;
// .
class {
public () {
Console.WriteLine(" .");
}
}
// , .
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) : base(j) {
b = i;
}
}
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.b = 27; // , b X
}
}
Y X.
:
2 = ; // , Y X
. (
2 X)
, .. , .
,
, , .
,
,
, . 2
b Y, .
, ,
11.
353
.
.
, .
, ,
.
,
. ,
, .
.
, .
TwoDShape 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 : value; }
}
public double Height {
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 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;
}
// .
public double Area() {
return Width * Height / 2;
}
// .
public void ShowStyle() {
Console.WriteLine(" " + Style);
}
}
class Shapes7 {
static void Main() {
Triangle t1 = new Triangle("", 8.0, 12.0);
// t1.
Triangle t2 = new Triangle(t1);
Console.WriteLine(" t1: ");
t1.ShowStyle();
11.
355
t1.ShowDim();
Console.WriteLine(" " + t1.Area());
Console.WriteLine();
Console.WriteLine(" t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine(" " + t2.Area());
}
}
t2 t1
. .
t1:
8 12
48
t2:
8 12
48
Triangle:
public Triangle(Triangle ob) : base(ob) {
Style = ob.Style;
}
Triangle
( base) TwoDShape.
public TwoDShape(TwoDShape ob) {
Width = ob.Width;
Height = ob.Height;
}
, TwoDShape()
TwoDShape, Triangle()
Triangle. , ,
.
, TwoDShape()
, TwoDShape.
TwoDShape() ,
TwoDShape, ,
, .
, virtual
. ,
. ,
356
I. C#
. ,
, .
C# ,
, ,
, .
. ,
,
. ,
,
.
virtual, .
, override.
. ,
,
, . ,
static abstract (
).
C# : ,
, .
,
C# .
,
.
// .
using System;
class Base {
// .
public virtual void Who() {
Console.WriteLine(" Who() Base");
}
}
class Derivedl : Base {
// Who() .
public override void Who() {
Console.WriteLine(" Who() Derivedl");
}
}
class Derived2 : Base {
// Who() .
public override void Who() {
Console.WriteLine(" Who() Derived2");
}
}
11.
357
class OverrideDemo {
static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
Base baseRef; //
baseRef = baseOb;
baseRef.Who();
baseRef = dOb1;
baseRef.Who();
baseRef = dOb2;
baseRef.Who();
}
}
.
Who() Base.
Who() Derived1
Who() Derived2
Base
Derived1 Derived2. Base
Who(), .
Main() Base, Derived1 Derived2. ,
baseRef Base.
baseRef
Who(). ,
Who() ,
,
baseRef.
.
,
, .
/* ,
. */
using System;
class Base {
// .
public virtual void Who() {
Console.WriteLine(" Who() Base");
}
}
class Derivedl : Base {
// Who() .
358
I. C#
11.
359
// Who() .
public override void Who() {
Console.WriteLine(" Who() Derived1");
}
}
class Derived2 : Derived1 {
// Who() .
}
class Derived3 : Derived2 {
// Who() .
}
class NoOverrideDemo2 {
static void Main() {
Derived3 dOb = new Derived3();
Base baseRef; //
baseRef = dOb;
baseRef.Who(); // Who() Derived1
}
}
.
Who() Derivedl
Derived3 Derived2,
Derived1, , , Base.
, Who(), Derived1,
,
Derived3 Derived2, Who()
, Derived1.
:
virtual override.
.
C#
. -
, ,
,
.
C#
: .
, ,
.
,
.
360
I. #
,
. , ,
,
.
,
TwoDShape. ,
TwoDShape, Area(). , -, Area()
TwoDShape
, .
.
name TwoDShape.
// .
using System;
class TwoDShape {
double pri_width;
double pri_height;
// .
public TwoDShape() {
Width = Height = 0.0;
name = "null";
}
// .
public TwoDShape(double w, double h, string n) {
Width = w;
Height = h;
name = n;
}
// .
public TwoDShape(double , 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;
}
// Area() Triangle.
pulplic override double Area() {
return Width * Height / 2;
}
// .
public void ShowStyle() {
Console.WriteLine(" " + Style);
}
361
362
I. C#
}
// , 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;
}
// Area() Rectangle.
public override double Area() {
return Width * Height;
}
}
class DynShapes {
static void Main() {
TwoDShape[] shapes = new TwoDShape[5];
shapes[0]
shapes[1]
shapes[2]
shapes[3]
shapes[4]
=
=
=
=
=
new
new
new
new
new
11.
363
40
24.5
Area()
0
. ,
Area() virtual TwoDShape
Triangle Rectangle . TwoDShape
Area() , ,
.
Area() ,
, . ,
, Area() .
. , Main()
TwoDShape,
Triangle, Rectangle TwoDShape.
,
.
.
,
. ,
,
. , TwoDShape,
Area().
.
,
,
. ,
,
. , ,
.
TwoDShape ,
Area() .
.
, ,
. . ,
, ,
. ,
, .
364
I. C#
,
, .
Triangle. , Area().
- , ,
.
# . .
abstract. ,
. , ,
.
,
virtual.
virtual abstract .
.
abstract (_);
, . abstract
, (static).
.
, ,
, class
abstract.
, . ,
new .
,
.
abstract. , abstract
, .
,
TwoDShape.
, TwoDShape
Area() TwoDShape abstract. , ,
, , TwoDShape,
Area().
// .
using System;
abstract class TwoDShape {
double pri_width;
double pri_height;
// , .
public TwoDShape() {
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);
}
// Area() .
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#
// ,
public Triangle(double ) : base(x, "") {
Style = "";
}
// Triangle.
public Triangle(Triangle ob) : base(ob) {
Style = ob.Style;
}
// Area() Triangle.
public override double Area() {
return Width * Height / 2;
}
// .
public void ShowStyle() {
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;
}
// Area() Rectangle.
public override double Area() {
return Width * Height;
}
}
class AbsShape {
static void Main() {
TwoDShape[] shapes = new TwoDShape[4];
shapes[0] = new Triangle("", 8.0, 12.0);
shapes[1] = new Rectangle(10);
11.
367
sealed
,
. , ,
,
. ,
,
. C#
sealed.
,
sealed . ,
abstract sealed,
, .
sealed.
sealed class {
// ...
}
// .
368 I. C#
class : A ( // !
// ...
}
,
, sealed.
: sealed
.
, D. ,
virtual, D sealed.
,
. .
class {
public virtual void MyMethod() { /* ... */ }
}
class D : {
// MyMethod()
// .
sealed public override void MyMethod() { /* ... */ }
}
class X : D {
// ! MyMethodO !
public override void MyMethod() { /* ... */ }
}
MyMethod() D,
X.
object
C# object,
, .
, object. , , ,
object
. , object ,
C# . object
C# System.Object,
.NET Framework.
object , . 11.1. ,
.
.
Equals(object) ,
, , , ..
, . Equals(object)
true, ,
false.
. ,
. , Equals(object) ,
.
11.
369
11.1. object
, ,
, ob
, ,
objA, , ,
objB
"
. C# Finalize()
-,
, ..
, ,
, objA objB
,
GetHashCode() -, .
- ,
. , ,
, GetHashCode()
.
9, ==,
Equals(object) GetHashCode(),
, Equals(object) == .
Equals(object),
GetHashCode(), .
ToString() ,
, . , ToString()
WriteLine().
,
, .
.
// ToString()
using System;
class MyClass {
static int count = 0;
int id;
public MyClass() {
370 I. C#
id = count;
count++;
}
public override string ToString() {
return " #" + id + " MyClass";
}
}
class Test {
static void Main() {
MyClass ob1 = new MyClass();
MyClass ob2 = new MyClass();
MyClass ob3 = new MyClass();
Console.WriteLine(obi);
Console.WriteLine(ob2);
Console.WriteLine(ob3);
}
}
.
#0 MyClass
#1 MyClass
#2 MyClass
, #, ,
object. , object
, .
object ,
. ,
, .. "" ,
.
.
object, #.
.
object .
.
, .
// .
using System;
class BoxingDemo {
static void Main() {
int x;
object obj;
11.
371
= 10;
obj = x; //
int = (int)obj; // ,
// obj, int
Console.WriteLine();
}
}
10. ,
obj, . ,
obj, int.
, .
int Sqr(), ,
, object.
// .
using System;
class BoxingDemo {
static void Main() {
int x;
x = 10;
Console.WriteLine(" x : " + x);
// x
// Sqr().
= BoxingDemo.Sqr();
Console.WriteLine(" x : " + );
}
static int Sqr(object ) {
return (int) * (int);
}
}
.
: 10
: 100
Sqr().
#.
object,
object, . ,
object ,
.
.
372
I. C#
// !
using System;
class MethOnValue {
static void Main() {
Console.WriteLine(10.ToString());
}
}
10. ,
ToString() ,
. 10
10!
object
object
, object
"" .
, object,
.
// object "" .
using System;
class GenericDemo {
static void Main() {
object[] ga = new object[10];
// .
for(int i=0; i < 3; i++)
ga[i] = i;
// double.
for(int i=3; i < 6; i++)
ga[i] = (double) i / 2;
// , bool char.
ga[6] = "";
ga[7] = true;
ga[8] = 'X';
ga[9] = "";
for (int i = 0; i < ga.Length; i++)
Console.WriteLine("ga[" + 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
, object
, object
. ,
object
. , ,
object.
.
object
, ,
C# .
, int,
string ..
, 2.0 C#
(
18).
, ,
.
object .
.
12
C# : ,
.
,
,
.
,
#: .
, ,
, .
.
#.
-
,
, .
.
, .
,
. ,
, .
,
,
376
I. C#
. C#
interface.
.
. ,
. ,
, . ,
. ,
.
(..
) , .
. ,
-.
. , ,
,
. C#
:
.
interface.
.
interface {
_ _1(_);
_ _2(_);
// ...
_ _N{_);
}
.
_ . , ,
. ,
.
, .
, .
,
.
public interface ISeries {
int GetNext(); //
void Reset(); //
void SetStart(int ); //
}
ISeries. I
, ,
- . ISeries public
.
, ,
. 15,
, .
. ,
. ,
static.
12. ,
377
,
.
, .
.
class _ : _ {
//
}
_ .
, . ,
.
.
.
.
,
.
, , public.
, ,
. ,
, .
,
ISeries. ByTwos,
,
.
// ISeries.
class ByTwos : ISeries {
int start;
int val;
public ByTwos() {
start = 0;
val = 0;
}
public int GetNext() {
val += 2;
return val;
}
public void Reset() {
val = start;
}
public void SetStart(int x) {
start = x;
val = start;
}
}
378
I. #
, ByTwos ,
ISeries. , ,
.
, ByTwos,
ISeries.
// ByTwos, .
using System;
class SeriesDemo {
static void Main() {
ByTwos ob = new ByTwos();
for(int i=0; i < 5; i++)
Console.WriteLine(" " + ob.GetNext());
Console.WriteLine("\n");
ob.Reset();
for(int i=0; i < 5; i++)
Console.WriteLine(" " + ob.GetNext());
Console.WriteLine("\n 100");
ob.SetStart(100);
for(int i=0; i < 5; i++)
Console.WriteLine(" " + ob.GetNext());
}
}
SeriesDemo,
, ISeries, ByTwos
SeriesDemo.
. , ISeries.
cs, ByTwos.cs SeriesDemo.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, GetPrevious(),
.
// ISeries
// ByTwos GetPrevious().
class
int
int
int
ByTwos : ISeries {
start;
val;
prev;
public ByTwos() {
start = 0;
val = 0;
prev = -2;
}
public int GetNext() {
prev = val;
val += 2;
return val;
}
public void Reset() {
val = start;
prev = start -2;
}
public void SetStart(int x) {
start = x;
val = start;
prev = val - 2;
}
// , ISeries.
public int GetPrevious() {
return prev;
}
}
, GetPrevious(),
, ISeries.
,
.
.
380
I. #
,
. Primes,
. , ISeries
, ByTwos.
// ISeries
// .
class Primes : ISeries {
int start;
int val;
public Primes() {
start = 2;
val = 2;
}
public int GetNext() {
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 Reset() {
val = start;
}
public void SetStart(int x) {
start = x;
val = start;
}
}
, , ByTwos Primes,
, ,
. , - ,
,
.
12. ,
381
, C#
, .. .
, .
,
.
, 11.
.
ByTwos Primes.
, .
// .
using System;
// .
public interface ISeries {
int GetNext(); //
void Reset(); //
void SetStart(int ); //
}
// ISeries
// ,
// .
class ByTwos : ISeries {
int start;
int val;
public ByTwos() {
start = 0;
val = 0;
}
public int GetNext() {
val += 2;
return val;
}
public void Reset() {
val = start;
}
public void SetStart(int x) {
start = x;
val = start;
}
}
// ISeries
// .
382 I. C#
class Primes : ISeries {
int start;
int val;
public Primes() {
start = 2;
val = 2;
}
public int GetNext() {
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 Reset() {
val = start;
}
public void SetStart(int x) {
start = x;
val = start;
}
}
class SeriesDemo2 {
static void Main() {
ByTwos twoOb = new ByTwos();
Primes primeOb = new Primes();
ISeries ob;
for(int i=0; i < 5; i++) {
ob = twoOb;
Console.WriteLine(" " + ob.GetNext());
ob = primeOb;
Console.WriteLine(" " + " " + ob.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, Next
, .
// .
using System;
384 I. C#
public interface ISeries {
// .
int Next {
get; //
set; //
}
}
// ISeries.
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
}
// .
public int Next {
get {
val += 2;
return val;
}
set {
val = value;
}
}
}
// .
class SeriesDemo3 {
static void Main() {
ByTwos ob = new ByTwos();
// .
2
4
6
8
10
21
23
25
12. ,
385
27
29
31
.
.
//
_ this[int ]{
get;
set;
}
, ,
, : get
set .
ISeries, , i-
.
// .
using System;
public interface ISeries {
// .
int Next {
get; //
set; //
}
// .
int this[int index] {
get; //
}
}
// ISeries.
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
}
// .
public int Next {
get {
val += 2;
return val;
}
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 ByTwos();
// .
for(int i=0; i < 5; i++)
Console.WriteLine(" " + ob.Next);
Console.WriteLine("\n 21");
ob.Next = 21;
for (int i=0; i < 5; i++)
Console.WriteLine(" " + ob.Next);
Console.WriteLine("\n 0");
ob.Next = 0;
//
for(int i=0; i < 5; i++)
Console.WriteLine(" " + ob[i]);
}
}
.
2
4
6
8
10
21
23
25
27
29
31
12. ,
0
387
0
2
4
6
8
.
, . ,
, ,
, .
// .
using System;
public interface IA {
void Meth1();
void Meth2();
}
// Meth1() Meth2().
// Meth3().
public interface IB : IA {
void Meth3();
}
// IA IB.
class MyClass : IB {
public void Methl() {
Console.WriteLine(" Meth1().");
}
public void Meth2() {
Console.WriteLine(" Meth2().");
}
public void Meth3() {
Console.WriteLine(" Meth3().");
}
}
class IFExtend {
static void Main() {
MyClass ob = new MyClass();
ob.Meth1();
ob.Meth2();
ob.Meth3();
}
}
388 I. #
Meth1() MyClass.
. , ,
, ,
, , .
,
, .
,
, .
new,
.
.
, . , IMyIF
interface IMyIF {
int MyMeth(int x);
}
:
class MyClass : IMyIF {
int IMyIF.MyMeth(int x) {
return x / 3;
}
}
, MyMeth() IMyIF
, .
. -,
,
,
, . ,
,
, . -,
,
.
.
.
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 !.IsOdd();
}
}
class Demo {
static void Main() {
MyClass ob = new MyClass();
bool result;
result = ob.IsEven(4);
if(result) Console.WriteLine("4 - .");
// result = ob.IsOdd(4); // , IsOdd IEven
// ,
// IEven MyClass,
// IsOdd().
IEven iRef = (IEven) ob;
result = iRef.IsOdd(3);
if(result) Console.WriteLine("3 .");
}
}
IsOdd() , ,
MyClass. ,
.
IEven IsEven().
, ,
Meth().
, .
// .
using System;
390
I. #
interface IMyIF_A {
int Meth(int x);
}
interface IMyIF_B {
int Meth(int x);
}
// MyClass.
class MyClass : IMyIF_A, IMyIF_B {
// Meth() .
int IMyIF_A.Meth(int x) {
return x + x;
}
int IMyIF_B.Meth(int x) {
return x * x;
}
// Meth() .
public int MethA(int x) {
IMyIF_A a_ob;
a_ob = this;
return a_ob.Meth(x); // IMyIF_A
}
public int MethB(int x){
IMyIF_B b_ob;
b_ob = this;
return b_ob.Meth(x); // IMyIF_B
}
}
class FQIFNames {
static void Main() {
MyClass ob = new MyClass();
Console.Write(" IMyIF_A.Meth(): ");
Console.WriteLine(ob.MethA(3));
Console.Write(" IMyIF_B.Meth(): ");
Console.WriteLine(ob.MethB(3));
}
}
.
IMyIF_A.Meth(): 6
IMyIF_B.Meth(): 9
,
Meth() , IMyIF_A
IMyIF_B. MyClass,
, .. Meth().
12. ,
391
, MyClass :
IMyIF_A, IMyIF_B.
, .
C#
,
, .
: -
,
, .
, .
.NET Framework
.NET Framework ,
#. , System.IComparable
CompareTo(), ,
.
, ,
, . , System.
Collections.ICollection ,
System.Collections.IEnumerator
.
II .
, .
, ,
, .
, ,
. ( )
. C#
, , ,
.
struct
. :
struct : {
//
}
.
392
I. #
. (, ,
#, object.)
,
. ,
: , , , , .
, .
, (..
). , , ,
.
, .
,
abstract, virtual protected.
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 book1 = new Book(" ",
" o C# 4.0",
2010) ; //
Book book2 = new Book(); //
Book b3; //
Console.WriteLine(book1.Author + ", " +
book1.Title + ", (c) " + book1.Copyright);
Console.WriteLine();
if(book2.Title == null)
12. , 393
Console.WriteLine(" book2.Title .");
// book2.
book2.Title = " ";
book2.Author = " ";
book2.Copyright = 1932;
Console.Write(" book2 :\n");
Console.WriteLine(book2.Author + ", " +
book2.Title + ",(c) " + book2.Copyright);
Console.WriteLine();
// Console.WriteLine(.Title); // ,
//
.Title = " ";
Console.WriteLine(.Title); //
}
}
.
, C# 4.0, () 2010
book2.Title .
b2 :
, , () 1932
,
new
. , new,
, (
), ,
. new ,
b3, ,
, .
, .
.
, ,
,
.
,
. .
// .
using System;
// .
struct MyStruct {
public int x;
}
394 I. C#
// .
class StructAssignment {
static void Main() {
MyStruct a;
MyStruct b;
a.x = 10;
b.x = 20;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
}
}
.
. 10, b.x 20
a.x 20, b.x 30
,
= b;
b - ,
.. b , ,
b. ,
b ,
. ,
.
// .
using System;
// .
class MyClass {
public int x;
}
// .
class ClassAssignment {
static void Main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
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
: C#
, , ?
. ,
, . ,
,
. ,
, .
, ,
.
,
. , ,
,
.
,
.
. ,
. .
,
,
.
// .
using System;
// .
struct PacketHeader {
public uint PackNum; //
public ushort PackLen; //
}
// PacketHeader
// .
class Transaction {
static uint transacNum = 0;
396 I. #
12. ,
397
, ++
struct. , #. , C++
, ,
,
. #
, .
.
enum.
:
enum {_};
, _
, .
Apple
.
enum Apple { Jonathan, GoldenDel, RedDel, Winesap,
Cortland, McIntosh };
,
.
C# ,
, . ,
.
, , ,
switch for.
, , .
. , Apple
Jonathan , GoldenDel 1, RedDel 2
..
,
-. ,
Console.WriteLine(Apple.RedDel + " " +
(int)Apple.RedDel);
.
RedDel 2
,
.
int.
,
Apple.
398
I. C#
// .
using System;
class EnumDemo {
enum Apple { Jonathan, GoldenDel, RedDel, Winesap,
Cortland, McIntosh };
static void Main() {
string[] color = {
"",
"",
"",
"",
"",
"-"
};
Apple i; //
// i
// .
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " " + (int)i);
Console.WriteLine();
// .
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(" " + i + " " +
color[(int)i]);
}
}
.
Jonathan 0
GoldenDel 1
RedDel 2
Winsap 3
Cortland 4
McIntosh 5
Jonathan -
GoldenDel -
RedDel -
Winsap -
Cortland -
McIntosh - -
, Apple for.
Apple
, ,
.
,
12. ,
399
. , C#
,
.
: System.Enum,
System.ValueType, , ,
object.
.
.
,
. ,
RedDel 10.
enum Apple { Jonathan, GoldenDel, RedDel = 10, Winesap,
Cortland, McIntosh };
.
Jonathan
GoldenDel
RedDel
Winesap
Cortland
McIntosh
0
1
10
11
12
13
int,
,
char. , int,
, .
byte Apple.
enum Apple : byte { Jonathan, GoldenDel, RedDel,
Winesap, Cortland, McIntosh };
Apple.Winesap, ,
byte.
,
#, . ,
. ,
. Conveyor(),
: "", "", "" "".
Conveyor() , , 1
400
I. C#
"", 2 "" , ,
,
. .
// .
using System;
class ConveyorControl {
// .
public enum Action { Start, Stop, Forward, Reverse };
public void Conveyor(Action com) {
switch(com) {
case Action.Start:
Console.WriteLine(" .");
break;
case Action.Stop:
Console.WriteLine(" .");
break;
case Action.Forward:
Console.WriteLine(" .");
break;
case Action.Reverse:
Console.WriteLine(" .");
break;
}
}
}
class ConveyorDemo {
static void Main() {
ConveyorControl = new ConveyorControl();
.Conveyor(ConveyorControl.Action.Start);
.Conveyor(ConveyorControl.Action.Forward);
.Conveyor(ConveyorControl.Action.Reverse);
.Conveyor(ConveyorControl.Action.Stop);
}
}
.
.
.
.
.
Conveyor() Action,
, Action. ,
Conveyor() 22.
.Conveyor(22); // !
,
int Action.
Conveyor(). ,
12. ,
401
,
, .
,
Conveyor() ,
.
: switch.
, ,
switch.
13
, ,
.
#,
,
.
,
,
. ,
,
,
.
,
.
,
,
,
.
,
. ,
.
, #
,
.
404
I. C#
.
C#
.
System.Exception
C# .
C# Exception,
System. ,
Exception.
Exception SystemException.
,
C# (.. CLR). SystemException
Exception, .
.NET Framework ,
SystemException. ,
DivideByZeroException.
, C# ,
Exception.
C#
: try, catch, throw finally. ,
.
.
. .
,
, try. try
, .
- ,
catch. , ,
.
throw. ,
try, finally.
try catch
C#
try catch.
. try/catch
:
try {
// , .
}
13.
405
,
. ,
. , CLR
IndexOutOfRangeException,
.NET Framework.
.
// .
using System;
class ExcDemol {
static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine(" .");
// .
406 I. C#
Console.WriteLine("nums[{0)]: {1}",i,nums[i]);
}
Console.WriteLine("He ");
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" !");
}
Console.WriteLine(" .");
}
}
.
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
!
.
nums int .
for 0 9,
IndexOutOfRangeException,
4.
,
.
-, , ,
try. -, (
nums for),
try , catch.
try
catch. , catch ,
. , ,
WriteLine() for,
, .
, ,
.
, catch
( IndexOutOfRangeException),
. ,
, .
,
, .
,
.
, try, catch
, ,
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() {
int[] nums = new int[4];
Console.WriteLine(" .");
//
.
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums [{0}] : {1}", i, nums[i]);
}
Console.WriteLine("He ");
}
}
class ExcDemo2 {
static void Main() {
try {
ExcTest.GenException();
408
I. C#
}
catch (IndexOutOfRangeException) {
// .
Console.WriteLine(" !");
}
Console.WriteLine(" .");
}
}
,
.
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
!
.
, GenException() try,
, catch
Main(). GenException(),
Main().
, ,
: .
, -
. ,
, .
,
. ,
.
// C# .
using System;
class NotHandled {
static void Main() {
int[] nums = new int[4];
Console.WriteLine(" .");
// .
13.
409
,
.
: System.IndexOutOfRangeException:
.
NotHandled.Main() <_>: 16
NotHandled.Main()
System.IndexOutOfRangeException,
.
, ,
, !
.
,
, catch.
. ,
catch,
DivideByZeroException,
. ,
IndexOutOfRangeException,
catch, .
// !
using System;
class ExcTypeMismatch {
static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine(" .");
// .
410 I. C#
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
: System.IndexOutOfRangeException:
ExcTypeMismatch.Main() <_>: 18
, catch,
DivideByZeroException,
IndexOutOfRangeException.
-
,
. ,
.
, DivideByZeroException.
,
. ,
-
. "",
.
// .
using System;
class ExcDemo3 {
static void Main() {
int[] numer = { 4, 8, 16, 32, 64, 128 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// .
Console.WriteLine(" !");
}
}
}
}
.
13.
411
4/2 2
!
16/4 4
32/4 8
!
128 / 8 16
:
, .
try for, ,
.
.
catch
try catch.
. catch
. ,
.
// catch.
using System;
class ExcDemo4 {
static void Main() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine(" !");
}
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");
}
}
}
}
.
4/2 2
!
16/4 4
32/4 8
!
412
I. C#
128 / 8 16
.
.
, catch
.
, catch
. catch,
. catch
.
. catch,
. .
catch {
//
}
""
, .
"" .
, ,
IndexOutOfRangeException DivideByZeroException, .
// "" .
using System;
class ExcDemo5 {
static void Main() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 );
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch { // "" .
Console.WriteLine(" .");
}
}
}
}
.
4/2 2
.
13.
413
16/4 4
32/4 8
.
128 / 8 16
.
.
"" , ,
catch.
"" (
. , , ,
.
, , ,
. ,
- . , "
,
.
try
try . ,
try catch,
try. ,
IndexOutOfRangeException ,
try.
// try.
using System;
class NestTrys {
static void Main() {
// numer denom.
int[] numer = {4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = (2, 0, 4, 4, 0, 8);
try { // try
for(int i=0; i < numer.Length; i++) {
try { // try
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine(" !");
}
}
}
414 I. C#
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");
Console.WriteLine(" - .");
}
}
}
.
4/2 2
!
16/4 4
32/4 8
!
128 / 8 16
.
- .
, try
- ,
. , try,
.
,
try,
. try
. ,
,
. , try
, try
. , try ""
, .
,
.
throw.
:
throw exceptOb;
exceptOb ,
Exception.
,
throw DivideByZeroException.
// .
using System;
class ThrowDemo {
static void Main() {
try {
13.
415
Console.WriteLine(" .");
throw new DivideByZeroException();
}
catch (DivideByZeroException) {
Console.WriteLine(" .");
}
Console.WriteLine(" try/catch.");
}
}
.
.
.
try/catch.
, DivideByZeroException
new throw.
, , ,
. ,
.
DivideByZeroException ,
, .
, catch,
, catch.
. ,
- ,
.
throw , .
throw ;
, , , ,
catch,
catch.
.
IndexOutOfRangeException.
// .
using System;
class Rethrow {
public static void GenException() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.Length; i++) {
416
I. C#
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine(" !");
}
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");
throw; //
}
}
}
}
class RethrowDemo {
static void Main() {
try {
Rethrow.GenException();
}
catch(IndexOutOfRangeException) {
//
Console.WriteLine(" - .");
}
}
}
-
GenException(),
. IndexOutOfRangeException
Main().
finally
,
try/catch. ,
, .
, ,
, .
, C# :
finally.
,
try/catch, finally
try/catch. try/
catch finally.
try {
// , .
}
catch (ExcepType1 exOb) {
// ExcepType1.
13.
417
}
catch (ExcepType2 b) {
// 2.
}
.
.
.
finally {
// .
}
finally , try/
catch, , . ,
try ,
, finally. finally ,
try catch
.
finally.
// finally.
using System;
class UseFinally {
public static void GenException(int what) {
int t;
int[] nums = new int[2];
Console.WriteLine(" " + what);
try {
switch(what) {
case 0:
t = 10 / what; // -
break;
case 1:
nums[4] = 4; //
break;
case 2:
return; // try
}
}
catch (DivideByZeroException) {
Console.WriteLine(" !");
return; // catch
}
catch (IndexOutOfRangeException) {
Console.WriteLine(" .");
}
finally {
Console.WriteLine(" try.");
}
}
}
418
I. C#
class FinallyDemo {
static void Main() {
for(int i=0; i < 3; i++) {
UseFinally.GenException(i);
Console.WriteLine();
}
}
}
.
0
try.
1
.
try.
2
try.
, finally
try.
: finally
try, catch . , finally
try, catch.
finally try,
.
Exception
,
. ,
catch .
. ,
Exception,
.
Exception
.
Exception .
: Message, StackTrace TargetSite.
. Message ,
; StackTrace ,
, TargetSite ,
, .
, Exception .
ToString(),
. , ,
WriteLine().
13.
419
Exception
.
// Exception.
using System;
class ExcTest {
public static void GenException() {
int[] nums = new int[4];
Console.WriteLine(" .");
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: (1)", i, nums[i]);
}
Console.WriteLine("He ");
}
}
class UseExcept {
static void Main() {
try {
ExcTest.GenException();
}
catch (IndexOutOfRangeException exc) {
Console.WriteLine(" : ");
Console.WriteLine(exc); // ToString()
Console.WriteLine(" StackTrace: " + exc.StackTrace);
Console.WriteLine(" Message: " + exc.Message);
Console.WriteLine(" TargetSite: " + exc.TargetSite);
}
Console.WriteLine(" .");
}
}
.
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
: System.IndexOutOfRangeException:
.
ExcTest.genException() <_>: 15
UseExcept.Main() <_>: 29
StackTrace: ExcTest.genException() <_>: 15
UseExcept.Main() <_>: 29
Message: .
TargetSite: Void genException()
.
420
I. C#
Exception .
public Exception()
public Exception(string )
public Exception(string , Exception _)
protected Exception(System.Runtime.Serialization.SerializationInfo ,
System.Runtime.Serialization.StreamingContext )
.
, Message,
.
. ,
, _
, , .
( ,
InnerException, Exception.)
, ,
.
, Exception
SerializationInfo StreamingContext System.
Runtime.Serialization.
System ,
. SystemException,
CLR
. . 13.1
.
13.1. ,
System
ArrayTypeMismatchException
DivideByZeroException
IndexOutOfRangeException
InvalidCastException
OutOfMemoryException
OverflowException
NullReferenceException
. ,
, ,
new
, .. ,
, . 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.WriteLine(" ...\n");
// .
q = new X(9);
val = p.Add(q);
}
Console.WriteLine(" val {0}", val);
}
}
.
NullReferenceException!
...
val 19
X,
Add(),
422
I. C#
, .
X Main(). ( )
, ( q) . q
. .Add() q
. q ,
q. NullReferenceException.
, C#
.
C# ,
, , .. ,
#. ,
, .
, Exception.
-
, .
Application.Exception,
. Microsoft
, , Exception.
.
, Exception . ,
Exception .
, , , ,
, Exception.
,
Exception, base.
, .
,
. , 10 RangeArray,
,
. , , ,
-5 27. ,
RangeArray .
, RangeArray. ,
"" .
RangeArray
13.
423
.
//
// RangeArray.
using System;
// RangeArray.
class RangeArrayException : Exception {
/* Exception.
.
RangeArrayException Exception,
. */
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 S index <= upperBound) return true;
return false;
}
}
//
// .
class RangeArrayDemo {
static void Main() {
try {
RangeArray ra = new RangeArray(-5, 5);
RangeArray ra2 = new RangeArray(1, 10);
// ra .
Console.WriteLine(" ra: " + ra.Length);
for(int i = -5; i <= 5; i++)
ra[i] = i;
Console.Write(" ra: ");
for(int i = -5; i <= 5; i++)
Console.Write(ra[i] + " ");
Console.WriteLine("\n");
// ra2 .
Console.WriteLine(" ra2: " + ra2.Length);
for(int i = 1; i <= 10; i++)
ra2[i] = i;
Console.Write(" ra2: ");
for(int i = 1; i <= 10; i++)
Console.Write(ra2[i] + " ");
13.
425
Console.WriteLine("\n");
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// .
Console.WriteLine(" .");
// .
try {
RangeArray ra3 = new RangeArray(100, -10); // !
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
// .
try {
RangeArray ra3 = new RangeArray(-2, 2);
for(int i = -2; i <= 2; i++)
ra3[i] = i;
Console.Write(" ra3: ");
for(int i = -2; i <= 10; i++) //
Console.Write(ra3[i] + " ");
} catch (RangeArrayException exc) {
Console.WriteLine(exc);
}
}
}
.
ra: 11
ra: -5 -4 -3 -2 -1 0 1 2 3 4 5
ra2: 10
ra2: 1 2 3 4 5 6 7 8 9 10
.
.
ra3: -2 -1 0 1 2 .
RangeArray,
RangeArrayException. RangeArray
: get , set
RangeArray.
, RangeArray
try, .
, RangeArray
C# ,
, .
426
I. C#
,
RangeArrayException - ,
Exception, base.
, ,
,
Exception.
- , Exception.
,
. ,
ToString() . ,
, , ,
, #.
, ,
,
catch,
. ,
Exception ,
Exception
. ,
catch
.
, .
,
catch,
. ,
. , :
catch, ,
.
:
ExceptA ExceptB. ExceptA Exception,
ExceptB ExceptA.
.
, ,
.
,
Exception.
//
// .
using System;
// .
class ExceptA : Exception {
public ExceptA(string str) : base(str) { }
13.
427
ExceptA.
ExceptB.
"System.Exception".
<_>: 36
catch.
. ExceptB
ExceptA, ExceptB
ExceptA. , Exception (..
) . ,
catch.
.
catch,
, . ,
.
, ,
,
.
428
I. C#
checked unchecked
C# , ,
.
,
, .
.
.
byte a, b, result;
= 127;
b = 127;
result = (byte)( * b);
b
byte. ,
,
result.
C# ,
, checked unchecked. ,
, ,
checked,
unchecked. ,
.
checked .
, .
, .
:
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() <_>: 20
, .
.
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 = unchecked((byte)(a * b));
Console.WriteLine(" : " +
result);
}
checked {
a = 2;
b = 7;
result = checked((byte)(a * b)); //
Console.WriteLine(" : " +
result);
= 127;
b = 127;
result = checked((byte)(a * b)); //
//
Console.WriteLine(" : " +
result); //
}
}
catch (OverflowException exc) {
Console.WriteLine(exc);
}
}
}
.
: 1
: 113
: 14
System.OverflowException:
.
CheckedDemo.Main() <_>: 41
,
.
, .
checked unchecked
, , ,
.
.
14
,
,
- #, Console.
WriteLine(), -
. - C#
,
,
, .
-. C# -
, .NET Framework,
-
- .NET .
-. , ,
, - C# .
.
C#
- C#
.
.
-.
.
-
. ,
.
432
I. C#
- # .
, -
. . , C#
char 16-, byte 8-. , ASCII, char
byte char.
(Unicode), ,
. ,
- .
.NET Framework ,
byte
char .
, System,
, Console.In, Console.Out
Console.Error. , Console.Out
. . ,
Console.WriteLine(), Console.
Out. Console.In ,
. Console.Error
,
.
-. .
.
.NET Framework ,
.
,
. ,
, .
System.IO.
, ,
.
using System.IO;
System.IO -
, Console System.
Stream
System.IO.Stream.
. ,
14. -
433
, ,
Stream . Stream
, . . 14.1
, Stream.
14.1. , Stream
void Close()
void Flush()
int ReadByte()
, .
-1
count
buffer, buffer[offset].
offset
origin.
count
buffer, buffer[offset].
, . 14.1,
IOException -.
, ,
, NotSupportedException.
,
.
, Stream ( )
( ) . ,
.
,
Seek(). ,
, Stream.
. 14.2 Length Position,
.
14.2. , Stream
bool CanRead
bool CanSeek
true, .
true,
.
434 I. C#
. 14.2
bool CanWrite
long Length
long Position
int ReadTimeout
int WriteTimeout
true, .
.
. ,
. ,
. ,
Stream
. System.IO .
BufferedStream
. , ,
FileStream
,
MemoryStream
,
UnmanagedMemoryStream ,
NET Framework
, - , . ,
,
.
-
- .
TextReader TextWriter. ,
TextReader , TextWriter . ,
, .
-, .
. 14.3 , TextReader.
, IOException
, .
ReadLine(), ,
string. ,
. TextReader Close(),
.
void Close()
14. -
435
.
14.3. , TextReader
int e()
int Read()
int Read(char[]buffer,
int index, int count)
int ReadBlock(char[]buffer,
int index,
int count)
string ReadLine()
string ReadToEnd()
,
. -1,
.
-1
count
buffer,
buffer[index],
count
buffer,
buffer[index],
string.
, ,
string
int
double
bool
string
uint
IOException
.
, TextWriter Close() Flush(),
.
436
I. C#
.
.
,
,
BinaryReader BinaryWriter.
, -.
, - #,
, -.
-
- ,
Console.In, Console.Out Console.Error.
- 2, .
, .
,
C# - ,
,
, .
-, , .
, -,
,
, .
Console.In TextReader,
,
14. -
437
TextReader. ,
Console,
Console.In. Console . ,
Read() ReadLine(), .NET Framework 1.0.
, ReadKey(), 2.0 .
Read().
static int Read()
Read() , .
, , .
int
char. , Read() -1.
IOException
. Read() ,
<Enter>,
, .
, Read()
, .
// , .
using System;
class KbIn {
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()
ReadLine() ,
<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, Console.In,
, .
ReadKey()
.NET Framework , Console
. ReadKey().
14. -
439
ReadKey()
.
<Enter>. , ReadKey()
.
ReadKey().
static ConsoleKeyInfo ReadKey()
static ConsoleKeyInfo ReadKey(bool intercept)
.
, .
,
. intercept true,
. intercept false,
.
ReadKey()
ConsoleKeyInfo, ,
, .
char KeyChar
ConsoleKey Key
ConsoleModifiers Modifiers
KeyChar char ,
Key ConsoleKey ,
Modifiers (<Alt>, <Ctrl>
<Shift>), , ,
.
ConsoleModifiers : Control, Shift Alt.
Modifiers
.
ReadKey() ,
,
.
, .
// , , ReadKey().
using System;
class ReadKeys {
static void Main() {
ConsoleKeyInfo keypress;
Console.WriteLine(" , " +
" - <Q>.");
do {
keypress = Console.ReadKey(); //
Console.WriteLine(" : " + keypress.KeyChar);
// .
if((ConsoleModifiers.Alt & keypress.Modifiers) != 0)
Console.WriteLine(" <Alt>.");
if((ConsoleModifiers.Control & keypress.Modifiers) != 0)
440 I. C#
Console.WriteLine(" <Control>.");
if((ConsoleModifiers.Shift & keypress.Modifiers) != 0)
Console.WriteLine(" <Shift>.");
} while(keypress.KeyChar != 'Q');
}
}
, , .
, - <Q>.
:
b : b
d : d
:
<Shift>.
:
<Shift>.
:
<Shift>.
:
<Control>.
Q : Q
<Shift>.
, ,
, ReadKey() .
Read(),
.
, ReadKey().
Console.Out Console.Error TextWriter.
Write()
WriteLine(), .
. Console
Write() WriteLine(),
Console,
.
TextWriter, Console.Out Console.Error.
,
Console.Out Console.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 = a / b; //
} catch(DivideByZeroException exc) {
Console.Error.WriteLine(exc.Message);
}
}
}
.
.
.
Console.Error. : ,
Console.Out Console.Error, ,
? ,
. ,
Console.Error , . ,
, ,
, . ,
, ,
, .
-.
FileStream -
.NET Framework -
. , .
. , ,
.
. ,
. -
. ,
-.
, , FileStream.
Stream .
, , FileStream,
System.IO.
.
using System.IO;
, ,
FileStream. .
:
FileStream(string , FileMode )
442
I. C#
, ;
. ,
FileMode . 14.4. ,
.
FileMode.Append,
.
14.4. FileMode
FileMode.Append
FileMode.Create
FileMode.CreateNew
FileMode.Open
FileMode.OpenOrCreate
FileMode.Truncate
.
.
, .
,
,
. - ,
FileNotFoundException. - -, IOException.
,
, : ArgumentNullException ( ),
ArgumentException ( ), ArgumentOutOfRangeException
( ), SeaurityException (
), PathTooLongException ( ),
NotSupportedException ( ,
), DirectoryNotFoundException ( ).
DirectoryNotFoundException
PathTooLongException,
FileNotFoundException IOException.
,
IOException.
test.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
// .
}
catch ,
, , ,
, -. catch,
"" ,
(, ).
, ,
.
, ,
IOException, , ,
, -,
. , ,
, ,
, .
, ,
. , .
, FileStream ,
.
, .
FileStream(string , FileMode , FileAccess )
, ,
, .
. ,
FileAccess .
FileAccess.Read
FileAccess.Write
FileAccess.ReadWrite
, test.dat
.
FileStream fin = new FileStream("test.dat", FileMode.Open, FileAccess.Read);
, Close().
.
void Close()
,
, . ,
Close() , , Dispose(), , ,
.
using, 20,
, .
,
. ,
, , ,
, Close().
444
I. C#
-
FileStream :
ReadByte() Read(). ,
ReadByte(), .
int ReadByte()
, , ,
. ,
, NotSupportedException (
) ObjectDisposedException ( ).
Read(),
.
int Read(byte[ ] array, int offset, int count)
Read() count
array, array[offset].
, . -,
IOException. ,
, NotSupportedException.
, .
ReadByte()
,
. ,
, , .
/* .
, ,
. ,
TEST.CS :
ShowFile TEST.CS
*/
using System;
using System.IO;
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();
}
}
}
,
try. , .
-, .
try , . , try ,
fin . ,
finally, try.
, , do-while (
- ), .
, ,
, , ,
finally
- - .
,
, try,
. ,
ShowFile.
// .
using System;
using System.IO;
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();
}
}
}
, fin
FileStream .
FileStream,
fin , . ,
Close() finally ,
fin .
Close() fin,
.
-, .
, , , , ,
, . ,
, , ,
, try,
.
, ,
. , ,
.
.
WriteByte().
.
void WriteByte(byte value)
, value.
,
NotSupportedException. ,
ObjectDisposedException.
Write().
.
void Write(byte[] array, int offset, int count)
Write() count
array, array[offset].
14. -
447
, . ,
IOException.
, NotSupportedException. ,
.
, , ,
.
,
, .
. ,
128 . ,
.
, Flush.
void Flush()
IOException.
, ObjectDisposedException.
Close().
, ,
, .
Flush() .
,
.
// .
using System;
using System.IO;
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();
}
}
}
test.txt
FileMode.CreateNew. ,
. (
IOException.)
448
I. C#
.
test.txt .
ABCDEFGHIJKLMNOPQRSTUVWXYZ
FileStream
- FileStream
, , , ,
. ,
, .
.
/* .
,
. , FIRST.DAT SECOND.DAT
:
14. -
449
-
,
.
, . ,
,
. , -
FileStream StreamReader
StreamWriter.
.
, , ,
. StreamReader StreamWriter
.
StreamWriter TextWriter,
StreamReader TextReader. ,
StreamReader StreamWriter ,
.
StreamWriter
Stream, FileStream, StreamWriter.
StreamWriter .
:
StreamWriter(Stream )
.
ArgumentException, ,
ArgumentNullException, .
StreamWriter .
, test.txt.
, "".
FileStream,
StreamWriter.
// ,
// StreamWriter.
using System;
using System.IO;
class KtoD {
static void Main() {
string str;
FileStream fout;
// -.
try {
fout = new FileStream("test.txt", FileMode.Create);
}
450
I. C#
catch(IOException exc) {
Console.WriteLine(" :\n" + exc.Message);
return;
}
// - StreamWriter.
StreamWriter(string )
StreamWriter(string , bool append)
, .
append true,
.
.
, . IOException. ,
.
, ,
StreamWriter.
// StreamWriter.
using System;
using System.IO;
class KtoD {
static void Main() {
string str;
StreamWriter fstr_out = null;
try {
// , StreamWriter.
14. -
451
StreamReader
StreamReader. StreamReader
. :
StreamReader(Stream )
.
ArgumentNullException, ,
ArgumentException, .
StreamReader .
StreamReader .
.
test.txt.
.
// ,
// StreamReader.
using System;
using System.IO;
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(" :\n" + exc.Message);
return;
}
StreamReader fstr_in = new StreamReader(fin);
try {
while((s = fstr_in.ReadLine()) != null) {
Console.WriteLine(s);
}
} catch(IOException exc) {
Console.WriteLine(" -:\n" + exc.Message);
} finally {
fstr_in.Close();
}
}
}
, .
ReadLine() , ,
. , StreamReader
EndOfStream.
true,
, false. ,
EndOfStream .
while .
while(!fstr_in.EndOfStream) {
s = fstr_in.ReadLine();
Console.WriteLine(s);
}
EndOfStream,
.
EndOfStream ,
.
, 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,
,
. ,
.
SetIn(), SetOut() SetError(),
Console.
static void SetIn(TextReader __)
static void SetOut(TextWriter __)
static void SetError(TextWriter ____)
, SetIn()
. ,
, TextReader.
SetOut() ,
TextReader. ,
FileStream,
StreamWriter. .
// Console.Out.
using System;
using System.IO;
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(" -\n" + exc.Message);
} finally {
if(log_out != null) log_out.Close();
}
}
}
,
logfile.txt .
.
0
1
2
3
4
5
6
7
8
9
.
.
. ( )
. , ,
int, double short.
C# BinaryReader BinaryWriter.
, ,
, .
BinaryWriter
BinaryWriter , ,
.
:
14. - 455
BinaryWriter(Stream output)
output , .
output ,
FileStream. output ,
ArgumentNullException. ,
output, ,
ArgumentException. BinaryWriter
. .
BinaryWriter ,
C# . . 14.5.
, string
. , BinaryWriter
Close() Flush(), .
14.5. , BinaryWriter
sbyte
byte
byte
short
( )
ushort
( )
int
uint
( )
long
( )
ulong
( )
float (
)
double (
)
decimal (
)
string,
BinaryReader
BinaryReader , ,
.
:
456
I. C#
BinaryReader(Stream input)
input , .
input ,
FileStream. ,
input,
, ArgumentException.
BinaryReader .
.
BinaryReader ,
C# . . 14.6.
, , , Readstring()
, .
IOException, .
, .
14.6. , BinaryReader
bool ReadBoolean()
byte ReadByte()
sbyte ReadSByte()
byte[] ReadBytes(int count)
char ReadChar()
char[] ReadChars(int count)
decimal ReadDecimal()
double ReadDouble()
float ReadSingle()
short ReadInt16()
int ReadInt32()
long ReadInt64()
ushort ReadUIntl6()
uint ReadUInt32()
ulong ReadUInt64()
string ReadString()
bool
byte
sbyte
count
char
count
decimal
double
float
short
int
long
ushort
uint
ulong
string,
.
,
BinaryWriter
BinaryWriter
Read().
IOException. , BinaryReader
Close().
14. -
int Read()
int
int
int
int
457
.
-1
Read(byte[] buffer, count
offset, int count)
buffer, buffer[offset],
Read(char[]buffer,
count
offset, int count)
buffer, buffer[offset],
-
,
BinaryReader BinaryWriter -.
.
// , .
using System;
using System.IO;
class RWData {
static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
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(" :\n" + 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#
10
1023.56
True
90.28
14. -
459
10
1023.56
True
90.28
testdata,
, , ,
.
, ,
-.
, , ,
, . ,
.
/* BinaryReader BinaryWriter
. */
using System;
using System.IO;
class Inventory {
static void Main() {
BinaryWriter dataOut;
BinaryReader detaIn;
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
I. C#
dataOut.Write(4.95);
dataOut.Write("");
dataOut.Write(8);
dataOut.Write(8.95);
}
catch(IOException exc) {
Console.WriteLine(" ");
Console.WriteLine(": " + exc.Message);
} finally {
dataOut.Close();
}
Console.WriteLine();
// .
try {
dataIn = 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 = dataIn.ReadString();
onhand = dataIn.ReadInt32();
cost = dataIn.ReadDouble();
// , .
// , .
if(item.Equals(what, StringComparison.OrdinalIgnoreCase)) {
Console.WriteLine(item + ": " + onhand + " . " +
": {0:} ", cost);
Console.WriteLine(" <{0}>: {1:}.",
14. -
461
catch(IOException exc) {
Console.WriteLine(" ");
Console.WriteLine(": " + exc.Message);
} finally {
dataIn.Glose();
}
}
}
, , .
:
: 18 . : $1.50 .
<>: $27.00.
,
, .
.
,
. EndOfStreamException
, ,
. ,
.
, ..
, .
. , , Seek(),
FileStream. ,
, .
Seek():
long Seek(long offset, SeekOrigin origin)
offset
(origin). origin
, SeekOrigin.
SeekOrigin.Begin
SeekOrigin.Current
SeekOrigin.End
Seek()
, , .
, IOException.
,
NotSupportedException. ,
.
462
I. #
-
.
, .
// .
using System;
using System.IO;
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(1, 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(" -\n" + exc.Message);
} finally {
if(f != null) f.Close();
}
Console.WriteLine();
}
}
.
14. -
463
:
:
:
:
C E G I K M O Q S U W Y
Seek()
,
Position. . 14.2, Position
, .
.
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 + " ");
}
MemoryStream
,
. MemoryStream.
Stream,
. MemoryStream .
:
MemoryStream(byte[] buffer)
buffer ,
-. , ,
buffer
.
,
MemoryStream -.
// MemoryStream.
using System;
using System.IO;
class MemStrDemo {
static void Main() {
byte[] storage = new byte[255];
// .
MemoryStream memstrm = 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("\n 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(" -\n" + 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. -
byte [1]:
byte [2]:
byte [3]:
byte [4]:
byte [5]:
byte [6]:
byte [7]:
byte [8]:
byte [9]:
465
memrdr:
1
2
3
4
5
6
7
8
9
, storage.
memstrm
MemoryStream. memstrm, , memrdr
StreamReader memwtr StreamWriter. memwtr
. ,
memwtr Flush().
,
.
foreach.
Seek() ,
memrdr.
.
, ,
, .
, Windows. ,
. , ,
.
StringReader StringWriter
-
string,
byte. StringReader
StringWriter. , StringReader TextReader,
StringWriter TextWriter. ,
, ,
, , , ReadLine()
StringReader, WriteLine() StringWriter.
StringReader:
StringReader(string s)
s , .
StringWriter .
.
StringWriter()
466
I. C#
,
.
ToString().
, StringReader
StringWriter.
// // StringReader StringWriter.
using System;
using System.IO;
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(" -\n" + 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,
WriteLine().
StringReader , strwtr.
ToString() strwtr.
, ReadLine().
File
.NET Framework File,
, ,
. , File
, ,
, ,
, ,
( , .). , File
,
FileStream . File
, .
(), Exists() GetLastAccessTime().
,
, File. , File
.
FileInfo.
File , :
, .
FileInfo.
()
,
.
,
(), File.
.
static void Copy (string __, string __)
static void Copy (string __, string __,
boolean overwrite)
Copy() , __,
, __.
, , __, .
, overwrite
true.
, IOException FileNotFoundException.
468
I. #
()
. .
, .
, .
/* , File.Copy().
,
. , FIRST.DAT SECOND.DAT,
:
Exists() GetLastAccessTime()
File .
: Exists() GetLastAccessTime(). Exists()
, , GetLastAccessTime()
. .
static bool Exists(string )
static DateTime GetLastAccessTime(string )
, .
Exists() true,
. GetLastAccessTime()
DateTime, . (
14. -
469
DateTime , ToString()
.)
,
IOException.
Exists() GetLastAccessTime()
. ,
test.txt. ,
.
// Exists() GetLastAccessTime().
using System;
using System.IO;
class ExistsDemo {
static void Main() {
if(File.Exists("test.txt"))
Console.WriteLine(" . " +
File.GetLastAccessTime("test.txt"));
else
Console.WriteLine(" ");
}
}
, , GetCreationTime(),
, GetLastWriteTime().
(UTC). .
-,
, .
, WriteLine()
, ,
int double.
WriteLine() .
. ,
Read() "100",
,
, int.
.
Parse(), .
: C#
, int double,
(.. ) , .NET Framework.
C# .NET
Framework, . C#
470
I. C#
,
.
.NET C#
.
.NET
Decimal
Double
Single
Int16
Int32
Int64
UInt16
UInt32
Uint64
Byte
Sbyte
C#
decimal
double
float
short
int
long
ushort
uint
ulong
byte
sbyte
System. ,
Int32 System.Int32.
,
#. ,
Parse(),
.
Parse().
.
. ,
, .
Decimal
Double
Single
Int64
Int32
Intl6
UInt64
UInt32
Ulnt16
Byte
Sbyte
static decimal Parse(string s)
static double Parse(string s)
static float Parse(string s)
static long Parse(string s)
static int Parse(string s)
static short Parse(string s)
static ulong Parse(string s)
static uint Parse(string s)
static ushort Parse(string s)
static byte Parse(string s)
static sbyte Parse(string s)
Parse()
FormatException, s ,
. ,
ArgumentNullException. s
,
OverflowException.
14. -
471
,
, .
, , .
,
ReadLine()
Int32.Parse(). ,
Double.Parse() double.
// , .
using System;
using System.IO;
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(),
.
TryParse(), Int32:
static bool TryParse(string s, out int )
s , ,
. (
.) , ,
s , TryParse()
false.
true. , , ,
, ( )
.
15
,
-
#:
, -.
,
,
. ,
.
,
#. -
,
,
,
. -
,
-. ( , -
LINQ, 19.)
,
,
.
.
, ,
. , ,
, .
, .
, ,
. ,
.
474
I. C#
,
,
, . , ,
, , . ,
, .
C/C++, ,
C# C/C++.
delegate.
:
delegate _ (_);
_ , ,
; ; _
, , .
, ,
.
,
. ,
, , ,
. :
,
.
,
.
// .
using System;
// .
delegate string StrMod(string str);
class DelegateTest {
// .
static string ReplaceSpaces(string s) {
Console.WriteLine(" .");
return s.Replace(' ', '-');
}
// .
static string RemoveSpaces(string s) {
string temp = "";
int i;
Console.WriteLine(" .");
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.WriteLine(" .");
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 = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new StrMod(RemoveSpaces);
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new StrMod(Reverse);
str = strOp(" .");
Console.WriteLine(" : " + str);
}
}
.
.
: --.
.
: .
.
: .
.
StrMod string, .
delegate string StrMod(string str);
, StrMod string
.
476
I. C#
DelegateTest
string . ,
StrMod.
. , ReplaceSpaces()
string Replace().
Main() strOp StrMod
ReplaceSpaces().
.
StrMod strOp = new StrMod(ReplaceSpaces);
ReplaceSpaces() .
, . :
,
. , ,
.
.
ReplaceSpaces() strOp,
.
str = strOp(" .");
strOp ReplaceSpaces(),
.
strOp RemoveSpaces(),
RemoveSpaces().
, strOp Reverse().
.
: ,
strOp, ,
. , ,
.
C# 2.0 ,
.
, ,
new .
Main() ,
.
static void Main() {
// , .
15. , -
477
strOp = RemoveSpaces; //
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = Reverse; //
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
}
, strOp
ReplaceSpaces .
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.WriteLine(" .");
for(j=0, i=s.Length-1; i >= 0; i--, j++)
temp += s[i];
return temp;
}
}
class DelegateTest {
static void Main() {
StringOps so = new StringOps(); //
// StringOps
// .
StrMod strOp = so.ReplaceSpaces;
string str;
// .
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = so.RemoveSpaces;
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = so.Reverse;
str = strOp(" .");
Console.WriteLine(" : " + str);
}
}
,
,
StringOps.
. , ,
, ,
. .
, + +=.
- -=.
, ,
. , ,
void.
15. , -
479
.
, ,
, void,
ref.
.
// .
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
I. C#
strOp += reverseStr;
// .
strOp(ref str);
Console.WriteLine(" : " + str);
Console.WriteLine();
// .
strOp -= replaceSp;
strOp += removeSp;
str = " ."; //
// .
strOp (ref str);
Console.WriteLine(" : " + str);
Console.WriteLine();
}
}
.
.
.
: .--
.
.
: .
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,
// ChangeIt Y.
// .
482
I. C#
X Xob = change(Yob);
Console.WriteLine("Xob: " + Xob.Val);
// IncrB Y,
// ChangeIt X.
// .
change = IncrB;
Yob = (Y) change (Yob);
Console.WriteLine("Yob: " + Yob.Val);
}
}
.
Xob: 1
Yob: 1
Y X. ChangeIt
.
delegate X ChangeIt(Y obj);
X
Y. IncrA() IncrB() .
static X IncrA(X obj)
static Y IncrB(Y obj)
IncrA() X
. IncrB()
Y .
ChangeIt,
.
,
ChangeIt change = IncrA;
IncrA() ,
X IncrA(), Y
ChangeIt.
, ,
, , ,
.
,
.
change = IncrB;
IncrB() Y,
X.
,
.
15. , -
483
System.Delegate
System.Delegate. ,
, . System.
Delegate .
, .
, . -,
, . -,
,
. ,
.
,
Windows Paint.
.
,
. ,
.
, , .
,
, ,
. ,
. , ,
, .
, , .
, ,
.
3.0, C#
: -. C#
2.0, - 3.0. -
.
# -
#.
-,
-.
, -
. , .
484 I. C#
,
.
delegate. , ,
.
0 5.
// .
using System;
// .
delegate void CountIt();
class AnonMethDemo {
static void Main() {
// ,
// .
CountIt count = delegate {
// .
for(int i=0; i <= 5; i++)
Console.WriteLine(i);
}; //
count();
}
}
CountIt
void. Main() count
CountIt, ,
delegate. ,
count. ,
,
. .
0
1
2
3
4
5
.
delegate,
. ,
.
15. , -
485
// , .
using System;
// , CountIt .
.
return, ,
. ,
, .
,
.
// , .
using System;
486
I. C#
// .
delegate int CountIt(int end);
class AnonMethDemo3 {
static void Main() {
int result;
// .
// .
CountIt 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);
}
}
,
count. , return
, .
.
0
1
2
3
3 6
0
1
2
3
4
5
5 15
, ,
.
. .
,
15. , -
487
"". ,
, ,
, ,
.
.
. CountIt
Counter(). sum,
Counter(), .
sum . Counter()
Main() CountIt, , sum
.
// .
using System;
// int int.
488
I. #
0
1
2
3
3 6
0
1
2
3
4
5
5 21
, - .
, 5 21, 15! , sum
ctObj Counter(). ,
count "
" . ,
Counter() ,
count Main().
, ,
. ,
, .
,
.
-
,
: -. , #,
1.0 . -
. -
LINQ ( 19),
. -
.
- . (
, , .) ,
- . -
,
.
-
- - =>,
- .
( ), -.
=> , "" "".
15. , -
489
C# -
-. , -
, -.
. -
, , -.
- ,
, if. .
-
- , =>,
( ), .
.
-,
.
=>
, .
(_) =>
, ,
. ,
.
-.
count- => count + 2
count ,
count + 2. count 2.
-.
n => n % 2 == 0
true,
n , false.
- . ,
-, ,
-. -
. .
-.
. , Incr, int
. , IsEven, int,
bool.
-. , -
.
// -.
using System;
490
I. C#
// , 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.WriteLine(" - 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.WriteLine(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
incr
-, 2
count. Incr,
. ,
incr, count,
-. isEven
, true,
, false.
, - IsEven.
:
, , , int count -,
incr? :
. ,
.
,
-.
.
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. #
-
, -.
, -, .
- .
-. -
,
. , -
if, ..
- .
.
, -,
-.
-
.
// -.
using System;
// IntOp int
// int.
delegate int IntOp(int end);
class StatementLambdaDemo {
static void Main() {
// -
// .
IntOp fact = n => {
int r = 1;
for(int i=1; i <= n; i++)
r = i * r;
return r;
};
Console.WriteLine(" 3 " + fact(3));
Console.WriteLine(" 5 " + fact(5));
}
}
.
3 6
5 120
,
- r, for
return. -.
. ,
-
. : return, , .
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.WriteLine(" .");
for(i=0; i < s.Length; i++)
if (s[i] != ' ') 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];
return temp;
};
string str;
// - .
StrMod strOp = ReplaceSpaces;
494
I. #
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = RemoveSpaces;
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = Reverse;
str = strOp(" .");
Console.WriteLine(" : " + str);
}
}
,
.
.
: --.
.
: .
.
: .
#, ,
. , , ,
. :
, , .
,
. .
event. :
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();
// Handler() .
evt.SomeEvent += Handler;
// .
evt.OnSomeEvent();
}
}
.
,
, .
, .
delegate void MyEventHandler();
.
.
, .
MyEvent.
SomeEvent .
public event MyEventHandler SomeEvent;
. event
, .
, MyEvent OnSomeEvent(),
. , ,
. OnSomeEvent()
SomeEvent.
if(SomeEvent != null)
SomeEvent();
, , SomeEvent
.
, , OnSomeEvent()
.
496
I. C#
,
, .
EventDemo Handler().
,
. Main()
MyEvent, a Handler()
, .
MyEvent evt = new MyEvent();
// Handler() .
evt.SomeEvent += Handler;
,
+=. += -=.
Handler() ,
.
, , .
// .
evt.OnSomeEvent();
OnSomeEvent() ,
. ,
, .
, .
.
.
// .
using System;
// .
delegate void MyEventHandler();
// , .
class MyEvent {
public event MyEventHandler SomeEvent;
// .
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent();
}
}
class X {
public void Xhandler() {
Console.WriteLine(" X");
}
15. , -
497
}
class Y {
public void Yhandler() {
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();
// .
evt.SomeEvent += Handler;
evt.SomeEvent += xOb.Xhandler;
evt.SomeEvent += yOb.Yhandler;
// .
evt.OnSomeEvent();
Console.WriteLine();
// .
evt.SomeEvent -= xOb.Xhandler;
evt.OnSomeEvent();
}
}
.
EventDemo
X
Y
EventDemo
Y
, X Y,
, MyEventHandler.
.
, X Y .
, ,
, .
.
, .
498
I. C#
,
.
, . ,
,
, .
, , ,
.
.
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.WriteLine(" " + id);
}
}
class EventDemo3 {
static void Main() {
MyEvent evt = new MyEvent();
X o1 = new X(1);
X o2 = new X(2);
X o3 = new X(3);
evt.SomeEvent += o1.Xhandler;
evt.SomeEvent += o2.Xhandler;
evt.SomeEvent += o3.Xhandler;
15. , -
499
// .
evt.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 MyEvent();
evt.SomeEvent += X.Xhandler;
// .
evt.OnSomeEvent();
}
}
500
I. #
.
.
, X
. Xhandler() X,
SomeEvent
OnSomeEvent().
,
,
.
.
.
, , ,
.
event, .
.
event _ _ {
add {
// .
}
rernove {
// .
}
}
: add remove. add ,
+=.
remove ,
-=.
add remove,
. ,
value. add remove,
. ,
, .
,
. .
,
.
//
// .
using System;
// .
delegate void MyEventHandler();
15. , -
501
// .
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.WriteLine(" .");
}
// .
remove {
int i;
for(i=0; i < 3; i++)
if(evnt[i] == value) {
evnt[i] = null;
break;
}
if (i == 3) Console.WriteLine(" .");
}
}
// .
public void OnSomeEvent() {
for(int i=0; i < 3; i++)
if(evnt[i] != null) evnt[i]();
}
}
// , MyEventHandler.
class W {
public void Whandler() {
Console.WriteLine(" W");
}
}
class X {
public void Xhandler() {
Console.WriteLine(" X");
}
}
class Y {
public void Yhandler() {
Console.WriteLine(" Y");
}
}
502
I. #
class Z {
public void Zhandler() {
Console.WriteLine(" Z");
}
}
class EventDemo5 {
static void Main() {
MyEvent evt = new MyEvent();
W wOb = new W();
X xOb = new X();
Y yOb = new Y();
Z zOb = new Z();
// .
Console.WriteLine(" . ");
evt.SomeEvent += wOb.Whandler;
evt.SomeEvent += xOb.Xhandler;
evt.SomeEvent += yOb.Yhandler;
// - .
evt.SomeEvent += zOb.Zhandler;
Console.WriteLine();
// .
evt.OnSomeEvent();
Console.WriteLine();
// .
Console.WriteLine(" xOb.Xhandler.");
evt.SomeEvent -= xOb.Xhandler;
evt.OnSomeEvent();
Console.WriteLine();
// .
Console.WriteLine(" " +
"xOb.Xhandler .");
evt.SomeEvent -= xOb.Xhandler;
evt.OnSomeEvent();
Console.WriteLine();
// Zhandler.
Console.WriteLine(" zOb.Zhandler.");
evt.SomeEvent += zOb.Zhandler;
evt.OnSomeEvent();
}
}
:
.
.
15. , -
503
W
X
Y
xOb.Xhandler.
W
Y
xOb.Xhandler .
.
W
Y
zOb.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.WriteLine(" .");
}
// .
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 MyEvent();
// - .
evt.SomeEvent += (n) =>
Console.WriteLine(" . " + n);
// .
evt.OnSomeEvent(1);
evt.OnSomeEvent(2);
}
}
.
. 1
. 2
, -
.
evt.SomeEvent += (n) =>
Console.WriteLine(" . " + n);
-
, .
-, .
,
.
506
I. C#
// .
evt.SomeEvent += delegate(int n) {
Console.WriteLine(" . " + n);
};
,
,
.
.NET Framework
C# .
.NET Framework
, Microsoft.
, , :
. ,
, EventArgs,
, . , .NET .
void (object , EventArgs ) {
// ...
}
, ,
this. EventArgs
, .
EventArgs ,
. , EventArgs
, ,
. EventArgs Empty
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 ob1 = new X();
Y ob2 = new Y();
MyEvent evt = new MyEvent();
// Handler() .
evt.SomeEvent += ob1.Handler;
evt.SomeEvent += ob2.Handler;
// .
evt.OnSomeEvent();
evt.OnSomeEvent();
}
}
.
0 X
: MyEvent
0 Y
: MyEvent
1 X
: MyEvent
507
508
I. C#
1 Y
: MyEvent
MyEventArgs, EventArgs.
MyEventArgs : EventNum.
MyEventHandler, ,
.NET Framework. ,
, ,
EventArgs . Handler(),
X Y, .
MyEvent SomeEvent MyEventHandler.
OnSomeEvent() SomeEvent,
this,
MyEventArgs. ,
MyEventHandler
.NET.
EventHandler<TEventArgs>
EventHandler
. , , .NET
Framework
EventHandler<TEventArgs>. (
18.) TEventArgs ,
EventArgs . ,
SomeEvent MyEvent .
public event EventHandler<MyEventArgs> SomeEvent;
, ,
.
EventArgs
. .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.WriteLine(" ");
Console.WriteLine(": " + source);
}
static void Main() {
MyEvent evt = new MyEvent();
// Handler() .
evt.SomeEvent += Handler;
// .
evt.OnSomeEvent();
}
}
EventArgs ,
- EventArgs.Empty.
.
: MyEvent
, Windows. ,
,
.
#,
. ,
LButtonClick.
OnLButtonClick(),
.
Windows, ,
, , ,
, .
, . ,
, KeyPress
OnKeyPress(). , .NET -.
// , .
using System;
// , EventArgs
// .
510
I. C#
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 KeyEvent();
ConsoleKeyInfo key;
int count = 0;
// - .
.
: t
:
: s
: t
: .
15. , -
511
KeyEventArgs,
EventArgs
. EventHandler,
, .
KeyEvent, KeyPress.
Main() kevt KeyEvent.
kevt.KeyPress , . ,
.
kevt.KeyPress += (sender, ) =>
Console.WriteLine(" : " + e.ch);
kevt.KeyPress ,
-.
, .
kevt.KeyPress += (sender, ) =>
count++; // count
, count ,
Main() .
, kevt.OnKeyPress()
.
.
. ,
#.
. ,
,
.
16
#,
.
, .
2
, #.
#.
, C#
. ,
, ,
.
.
.
,
. , ,
,
,
. , .NET Framework,
#,
System.
514
I. C#
using System;
#. 14,
- System.IO,
System. ,
#.
,
"" , ,
, , .
, . ,
Finder, Finder,
, . ,
, ,
.
namespace.
:
namespace {
//
}
.
. ,
, .
, , , ,
.
namespace
Counter. ,
CountDown.
// .
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;
}
16. ,
515
}
} // Counter.
, CountDown
Counter.
, Counter.cs.
,
Counter.
// Counter.
using System;
class NSDemo {
static void Main() {
// , CountDown
// Counter.
Counter.CountDown cd1 = new Counter.CountDown(10);
int i;
do {
i = cd1.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
// , CountDown
// Counter.
Counter.CountDown cd2 = new Counter.CountDown(20);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
cd2.Reset(4);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
}
}
.
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#
NSDemo.cs, Counter
Counter.cs,
.
csc NSDemo.cs counter.cs
. -, CountDown
Counter,
. CountDown Counter.
Counter.CountDown cd1 = new Counter.CountDown(10);
: ,
,
. .
-, Counter ,
. ,
cd1.Count()
, .
i = cd1.Count();
-,
.
Counter, NSDemo.
. ,
.
, Counter
.
, ,
. , , ,
, .
,
, . ,
.
Counter, Counter2.
CountDown,
, CountDown
. ,
. , . ,
,
.
// .
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 Count() {
Console.WriteLine(" Count() " +
" Counter2.");
}
}
}
class NSDemo2 {
static void Main() {
// CountDown Counter.
Counter.CountDown cd1 = new Counter.CountDown(10);
// CountDown Counter2.
Counter2.CountDown cd2 = new Counter2.CountDown();
int i;
do {
i = cd1.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
cd2.Count();
}
}
517
518
I. C#
.
10 9 8 7 6 5 4 3 2 1 0
Count() Counter2.
, CountDown
Counter
Counter2, .
, ,
, ,
.
using
, , ,
. 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 cd1 = new CountDown(10);
int i;
do {
i = cd1.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
CountDown cd2 = new CountDown(20);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
cd2.Reset(4);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
}
}
.
using ,
.
using Counter;
Counter.
, CountDown
Counter,
Main().
CountDown cd1 = new CountDown(10);
Counter ,
CountDown .
520
I. C#
:
.
,
. ,
, System Counter, .
using
using (
) . :
using = ;
(, )
, . ,
.
,
MyCounter
Counter.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 Count() {
if(val > 0) return val--;
else return 0;
}
}
}
class NSDemo4 {
static void Main() {
// MyCounter
// Counter.CountDown.
16. ,
521
.
. ,
Counter. CountDown, CountUp.
Counter .
// .
using System;
// Counter.
using Counter;
// Counter.
522
I. #
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;
}
}
}
// Counter.
namespace Counter {
// .
class CountUp {
int val;
int target;
public int Target {
get{
return target;
}
}
public CountUp(int n) {
target = n;
va1 = 0;
}
public void Reset(int n) {
target = n;
val = 0;
}
public int Count() {
if(val < target) return val++;
else return target;
}
}
}
class NSDemo5 {
static void Main() {
CountDown cd = new CountDown(10);
CountUp cu = new CountUp(8);
16. ,
523
int i;
do {
i = cd.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
do {
i = cu.Count();
Console.Write(i + " ");
} whiled < 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 ClassA() {
Console.WriteLine(" ClassA");
}
}
namespace NS2 { //
class ClassB {
public ClassB() {
Console.WriteLine(" ClassB");
}
}
}
}
class NestedNSDemo {
static void Main() {
524
I. #
NS1.ClassA a = new NS1.ClassA();
,
. ,
,
namespace. ,
,
.
.
,
.
::
,
. , , ,
16. ,
525
. ,
MyClass.
using, MyClass
MyClass ,
.
::.
::.
__::
__
, .
, ,
, Counter AnotherCounter,
CountDown.
using. , Main()
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
I. C#
}
}
class WhyAliasQualifier {
static void Main() {
int i;
// , , !
// , CountDown
// Counter AnotherCounter?
CountDown cd1 = new CountDown(10); // ! !!
// ...
}
}
,
,
Main().
CountDown cd1 = new CountDown(10); // !!!
,
, Counter AnotherCounter, CountDown
. , CountDown
.
::.
::,
, ,
.
,
.
// ::.
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.
Ctr::CountDown cd1 = new Ctr::CountDown(10);
// ...
}
}
Counter
Ctr .
using Ctr = Counter;
Main()
CountDown, .
Ctr::CountDown cd1 = new Ctr::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.
Ctr::CountDown cd1 = new Ctr::CountDown(10);
// CountDown
// .
global::CountDown cd2 = new global::CountDown(10);
// ...
}
}
, global
CountDown .
global::CountDown cd2 = new global::CountDown(10);
,
.
:
extern, 20.
# ,
.
16. ,
529
, .
,
, .
,
.
, #.
#define
#endregion
#pragma
#elif
#error
#region
#else
#if
#undef
#endif
#line
#warning
#. ,
.
-
#, ,
.
, .
.
#define
#define ,
.
#if #elif
. #define.
#define
.
#define ,
. ,
EXPERIMENTAL .
#define EXPERIMENTAL
C/C++ #define ,
, ,
. C# #define .
#define .
#if #endif
, #if #endif,
,
. ,
, . ,
#define, . #if.
530
I. 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.
#if,
,
WriteLine(). EXPERIMENTAL
, ,
WriteLine(), ,
#if . ,
WriteLine(), ,
#if.
, #if
. .
// .
#define EXPERIMENTAL
#define TRIAL
using System;
16. ,
531
class Test {
static void Main() {
#if EXPERIMENTAL
Console.WriteLine(" .");
#endif
#if EXPERIMENTAL && TRIAL
Console.Error.WriteLine ("
.");
#endif
Console.WriteLine(" .");
}
}
.
.
.
.
: EXPERIMENTAL TRIAL.
, WriteLine(),
, .
, ,
!, .
#if !EXPERIMENTAL
Console.WriteLine(" !");
#endif
,
EXPERIMENTAL .
#else #elif
#else else #,
,
#if. #else
.
// #else.
#define EXPERIMENTAL
using System;
class Test {
static void Main() {
#if EXPERIMENTAL
Console.WriteLine(" .");
#else
Console.WriteLine(" .");
#endif
532
I. C#
16. ,
533
#if EXPERIMENTAL
Console.WriteLine(" .");
#elif RELEASE
Console.WriteLine(" .");
#else
Console.WriteLine(" .");
#endif
#if TRIAL && !RELEASE
Console.WriteLine(" .");
#endif
Console.WriteLine(" .");
}
}
.
.
.
#undef
#undef .
, , , "".
#undef.
#undef
.
#define SMALL
#if SMALL
// ...
#undef SMALL
// SMALL .
#undef SMALL
.
#undef
, .
#error
#error .
. #error.
#error __
#error, .
,
#error !
" !".
534
I. C#
#warning
#warning #error,
, , . ,
. #warning.
#warning _
#line
#line , .
. #line.
#line "_"
#line.
default,
, .
#line default
#line hidden.
,
#line hidden
#line hidden, .
#region #endregion
#region #endregion ,
Visual Studio. :
#region
//
#endregion
.
#pragma
#pragma .
:
#pragma
, .
C# #pragma.
, warning,
. :
#pragma warning disable
#pragma warning restore
16. ,
535
. disable,
restore.
, #pragma
168, , , .
#pragma warning disable 168
#pragma checksum.
ASP.NET. :
#pragma checksum "_" "{GUID}" "_"
_ ; GUID
, _; _
, .
.
internal
#.
,
. .NET.
,
. ,
.
.
. .
, , , ,
( ).
, .. ,
.
.
MSIL (Microsoft Intermediate Language
Microsoft). ,
.
, C# ,
. ,
, #,
, ,
. , #,
.
,
, , ,
.
.NET, #.
C# , .
internal, .
536
I. #
internal
public, private protected,
, C#
internal.
. , ,
internal, , .
internal
.
internal ,
. , internal
.
protected internal
protected internal. protected internal
. , protected 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,
.
17
: ,
.
,
.
.
,
. ,
, .. .
#. , ,
, .
.
.
(RTTI)
.
.
,
, .
,
,
. ,
.
538
I. C#
#
: is, as typeof.
.
is
is.
:
is
, ,
. ,
, ,
. , ,
. is ,
,
.
is.
// is.
using System;
class A {}
class : A {}
class UseIs {
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.WriteLine(" , ");
if(b is )
Console.WriteLine(" ");
if(a is object)
Console.WriteLine(" object");
}
}
.
b
b
object
is ,
. ,
.
17. ,
539
if(b is A)
Console.WriteLine("b , ");
if , b ,
. . ,
if(a is )
Console.WriteLine(" , ");
if , ,
. .
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 = () HE .");
else
Console.WriteLine(" b = () .");
}
}
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
,
, .
typeof
, as is
. .
# typeof. System.
.
. typeof:
typeof()
. , ,
.
,
, , , .
,
, .
,
17. ,
541
, .
, , :
, .
, (
) , .
,
, .
, ,
.NET Reflection API, System.Reflection.
.
using System.Reflection;
System.Type -
System. ,
. ,
542
I. C#
.
System.Reflection.
MemberInfo.
MemberInfo ,
.
Type DeclaringType
MemberTypes MemberType
int MetadataToken
Module Module
string Name
Type ReflectedType
,
. ,
, , ,
,
Module, (
),
, MemberType MemberTypes
, ,
. .
MemberTypes.Constructor
MemberTypes.Method
MemberTypes.Field
MemberTypes.Event
MemberTypes.Property
, , MemberType. ,
MemberType MemberTypes.Method,
.
MemberInfo : GetCustomAttributes()
IsDefined(). .
, ,
, . .NET Framework
Version 4.0 GetCustomAttributesData(),
. ( .)
,
MemberInfo.
.
ConstructorInfo[]
GetConstructors()
EventInfo[] GetEvents()
FieldInfo[] GetFields()
Type[]
GetGenericArguments()
,
,
,
.
17. ,
543
, .
( 18.)
MemberInf[]
GetMembers()
MethodInfo[]
GetMethods()
PropertyInfo[]
GetProperties()
,
.
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. C#
, ,
, GetMethods().
, .
MethodInfo[] GetMethods()
MethodInfo,
, . MethodInfo
System.Reflection.
MethodInfo MethodBase,
MemberInf.
, . ,
Name.
MethodInfo:ReturnType GetParameters().
ReturnType, .
GetParameters() ,
. .
ParameterInf[] GetParameters();
ParameterInf.
ParameterInf , .
: 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. ,
545
}
public void Set(int a, int b) {
x = a;
= b;
}
public void Set(double a, double b) {
x = (int) a;
y = (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(MethodInfo m in mi) {
// .
Console.Write(" " + m.ReturnType.Name + " " + m.Name + "(");
// .
ParameterInfo[] 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.Write(", ");
}
Console.WriteLine(")");
Console.WriteLine();
}
}
}
.
, MyClass
:
Int32 Sum()
546
I. #
Boolean IsBetween(Int32 i)
17. ,
547
, ,
GetParameters() pi.
for pi
. ,
,
MyClass.
GetMethods()
GetMethods(),
.
GetMethods().
MethodInfo[] GetMethods(BindingFlags )
,
. BindingFlags .
.
DeclaredOnly
Instance
NonPublic
Public
Static
, .
,
. Instance Static
Public NonPublic.
.
BindingFlags GetMethods()
, ,
. ,
, .
GetMethods()
.
// ,
// MyClass.
MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
.
, MyClass
:
Int32 Sum()
Boolean IsBetween(Int32 i)
548
I. C#
, ,
, . Invoke(),
MethodInfo. :
object Invoke(object obj, object[] parameters)
obj , .
(static) obj (null).
, ,
parameters. , parameters
(null). , parameters
. ,
, parameters ,
. , ,
Invoke(), .
Invoke()
MethodInfo, GetMethods().
.
// .
using System;
using System.Reflection;
class MyClass {
int x;
int y;
public MyClass(int i, int j) {
x = i;
= j;
}
public int Sum() {
return x+y;
}
public bool IsBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
}
17. ,
549
550
I. C#
object[] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine(" 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
. .
foreach .
if/else.
Set() .
if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(int)) {
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(double)) {
object[] args = new object[2];
args[0] = 1.12;
args[1] = 23.4;
m.Invoke(reflectOb, args);
}
Set, ,
. , Set(int, int),
args.
double.
, MyClass,
, MyClass
.
.
, .
17. ,
551
,
, .
,
.
GetConstructors() .
.
ConstructorInf[] GetConstructors()
GetConstructors() ConstructorInf,
.
ConstructorInfo
MethodBase, MemberInf.
.
GetConstructors(), ,
. ,
GetParameters(), MethodInfo.
,
Invoke(), ConstructorInfo.
.
object Invoke(object[] parameters)
, ,
parameters. , parameters
(null).
parameters ,
. Invoke()
.
MyClass.
// .
using System;
using System.Reflection;
class MyClass {
int x;
int y;
public MyClass(int i) {
Console.WriteLine(" MyClass(int, int). ");
x = = i;
}
public MyClass(int i, int j) {
Console.WriteLine(" MyClass(int, int). ");
x = i;
= j;
Show();
}
552
I. #
17. ,
553
// .
int ;
for(x=0; < ci.Length; ++) {
ParameterInf[] pi = ci[].GetParameters();
if(pi.Length == 2) break;
}
if(x == ci.Length) {
Console.WriteLine(" .");
return;
}
else
Console.WriteLine(" .\n");
// .
object[] consargs = new object[2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Console.WriteLine("\n reflectOb.");
Console.WriteLine();
MethodInfo[] mi = t.GetMethods();
// .
foreach(MethodInfo m in mi) {
// .
ParameterInf[] pi = m.GetParameters();
if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(int)) {
// Set(int, int).
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(double)) {
// Set(double, double).
object[] args = new object[2];
args[0] = 1.12;
args[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) {
object[] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine(" 14 x ");
}
554
I. C#
else if(m.Name.CompareTo("Show")==0) {
m.Invoke(reflectOb, null);
}
}
}
}
.
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)
.
MyClass(int, int)
: 10, : 20
reflectOb
30
14
Set(int, int). : 9, : 18
Set(double, double). : 1, : 23
: 1, : 23
MyClass.
.
ConstructorInf[] ci = t.GetConstructors();
.
, ,
.
for(x=0; < ci.Length; ++) {
ParameterInfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;
}
, ,
.
// .
object[] consargs = new object[2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Invoke() reflectOb
MyClass.
.
, , ,
int. ,
.
17. ,
555
MyClass
, : MyClass.
,
, MyClass
typeof ,
. ,
,
.
16, ,
, .
Reflection API ,
. ,
,
. . ,
, , " ",
, , ,
,
. ,
.
Assembly. Assembly .
Assembly . ,
LoadFrom().
:
static Assembly LoadFrom(string _)
_ .
Assembly,
, GetTypes()
.
[] GetTypes()
, .
,
. ,
. MyClasses.cs,
.
// , 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, int). ");
x = i;
= j;
Show();
}
public int Sum() {
return x+y;
}
public bool IsBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
}
public void Set(int a, int b) {
Console.Write(" Set(int, int). ");
x = a;
= b;
Show();
}
// Set.
public void Set(double a, double b) {
Console.Write(" Set(double, double). ");
x = (int) a;
y = (int) b;
Show();
}
public void Show() {
Console.WriteLine(" x: {0}, : {1}", x, );
}
}
class AnotherClass {
string msg;
public AnotherClass(string str) {
msg = str;
}
public void Show() {
Console.WriteLine(msg);
}
}
17. ,
557
class Demo {
static void Main() {
Console.WriteLine(" .");
}
}
MyClass,
. , AnotherClass
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);
// .
ConstructorInfo[] ci = t.GetConstructors();
Console.WriteLine(" : ");
foreach(ConstructorInfo in ci) {
// .
Console.Write(" " + t.Name + "(");
// .
ParameterInf[] 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.Write(", ");
}
558
I. C#
Console.WriteLine(")");
}
Console.WriteLine();
// .
int x;
for(x=0; x < ci.Length; x++) {
ParameterInfo[] pi = ci[x].GetParameters();
if(pi.Length == 2) break;
}
if(x == ci.Length) {
Console.WriteLine(" .");
return;
}
else
Console.WriteLine(" .\n");
// .
object[] consargs = new object[2];
consargs[0] = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Console.Write.Line("/n reflectOb.");
Console.WriteLine();
MethodInfo[] mi = t.GetMethods();
// .
foreach(MethodInfo m in mi) {
// .
ParameterInfo[] pi = m.GetParameters();
if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(int)) {
// Set(int, int).
object[] args = new object[2];
args[0] = 9;
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if(m.Name.CompareTo("Set")==0 &&
pi[0].ParameterType == typeof(double))
// Set(double, double).
object[] args = new object[2];
args[0] = 1.12;
args[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) {
object[] args = new object[1];
17. ,
559
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine(" 14 x ");
}
else if(m.Name.CompareTo("Show")==0) {
m.Invoke(reflectOb, null);
}
}
}
}
.
: MyClass
: AnotherClass
: Demo
: MyClass
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)
.
MyClass(int, int)
: 10, : 20
reflectOb
30
14
Set(int, int). : 9, : 18
Set(double, double). : 1, : 23
: 1, : 23
,
, MyClasses..
MyClass,
.
MyClasses.
, in().
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.");
// , MyClasses.exe.
[] alltypes = asm.GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(": " + temp.Name);
,
.
..
560
I. #
,
.
MyClass ,
MyClass. , Set 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 = alltypes[0]; //
Console.WriteLine(": " + t.Name);
ConstructorInfo[] ci = t.GetConstructors();
// .
ParameterInf[] cpi = ci[0].GetParameters();
object reflectOb;
17. ,
561
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("\n reflectOb.");
Console.WriteLine();
// .
MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
// .
foreach(Methodlnfo m in mi) {
Console.WriteLine(" {0} ", m.Name);
// .
ParameterInfo[] 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: //
if((pi[0].ParameterType == typeof(int)) &&
(pi[1].ParameterType == typeof (int))) {
object[] args = new object[2];
args[0] = 9;
562
I. C#
args[1] = 18;
m.Invoke(reflectOb, args);
}
else if((pi[0].ParameterType == typeof(double)) &&
(pi[1].ParameterType == typeof(double))) {
object[] args = new object[2];
args[0] = 1.12;
args[1] = 23.4;
m.Invoke(reflectOb, args);
}
break;
}
Console.WriteLine();
}
}
}
.
: 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. ,
563
, ,
. ,
. , ,
, .
, System.Attribute.
Attribute.
Attribute ,
.
Attribute. , ErrorAttribute ,
.
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;
}
}
}
.
RemarkAttribute.
AttributeUsage, ,
RemarkAttribute .
AttributeUsage ,
.
.
RemarkAttribute, Attribute.
RemarkAttribute pri_remark,
Remark.
, . (, Remark
564
I. C#
set,
, .)
,
Remark.
RemarkAttribute, .
,
. , ,
.
, RemarkAttribute .
[RemarkAttribute(" .")]
class UseAttrib {
// ...
}
RemarkAttribute,
" ."
UseAttrib.
, Attribute.
, .
[Remark(" .")]
class UseAttrib {
// ...
}
Remark.
,
, .
,
.
. , GetCustomAttributes(), MemberInf
. ,
. .
object[] GetCustomAttributes(bool )
true,
, .
,
.
, GetCustomAttribute(), Attribute.
:
static Attribute GetCustomAttribute(MemberInfo , Type _)
MemberInfo, ,
, _ .
, ,
17. ,
565
. , UseAttrib RemarkAttribute,
.
// MemberInf,
// , RemarkAttribute.
Type t = typeof(UseAttrib);
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
,
MemberInfo . , t
MemberInfo.
, .
, ,
. ,
Remark.
Console.WriteLine(r.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. #
object[] attribs = t.GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine(o);
}
Console.Write(": ");
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.Remark);
}
}
.
UseAttrib: RemarkAttribute
: .
RemarkAttribute
. comment RemarkAttribute()
. ,
. ,
, ..
,
. ,
.
, ,
, .
,
.
.
,
. ,
.
[attrib(__,
__1 = ,
__2 = , ...)]
, .
.
17. ,
567
.
, ,
.
. RemarkAttribute,
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
I. 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.Write(" " + t.Name +");
object[] attribs = t.GetCustomAttributes(false);
foreach(object in attribs) {
Console.WriteLine(o);
}
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttrib.ute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write(": ");
Console.WriteLine(ra.Remark);
Console.Write(": ") ;
Console.WriteLine(ra.Supplement);
}
}
.
UseAttrib: RemarkAttribute
: .
: .
, ,
pri_remark ,
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
I. C#
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write(": ");
Console.WriteLine(ra.Remark);
Console.Write(": ");
Console.WriteLine(ra.Supplement);
Console.WriteLine(": " + ra.Priority);
}
}
.
UseAttrib: RemarkAttribute
: .
: .
: 10
UseAttrib, .
[RemarkAttribute(" .",
Supplement = " .",
Priority = 10)]
class UseAttrib {
// ...
}
Supplement Priority
- .
, .
: ( ,
) , object, ,
.
C# ,
, .
AttributeUsage, Conditional Obsolete, .
AttributeUsage
, AttributeUsage ,
. AttributeUsage ,
, System.AttributeUsageAttribute.
:
AttributeUsage(AttributeTargets validOn)
17. ,
571
validOn ,
, AttributeTargets ,
.
ll
Delegate
GenericParameter
Parameter
Assembly
Enum
Interface
Property
Class
Event
Method
ReturnValue
Constructor
Field
Module
Struct
. , , ,
.
AttributeTargets.Field | AttributeTargets.Property
AttributeUsage .
AllowMultiple,
. ,
. , Inherited,
. ,
, . AllowMultiple
(false), Inherited (true).
AttributeUsage
ValidOn. AttributeTargets,
, .
AttributeTargets.All.
Conditional
Conditional , ,
. ,
, #define
, . ,
#if.
Conditional , , System.
Diagnostics.ConditionalAttribute. Conditional
System.Diagnostics.
.
// Conditional.
#define TRIAL
using System;
using System.Diagnostics;
class Test {
[Conditional("TRIAL")]
void Trial() {
Console.WriteLine(" , " +
" .");
}
572
I. C#
[Conditional("RELEASE")]
void Release() {
Console.WriteLine(" .");
}
static void Main() {
Test t = new Test();
t.Trial(); // ,
// TRIAL
t.Release(); // ,
// RELEASE
}
}
.
, .
,
. ,
TRIAL. Trial()
Release(). Conditional,
:
[Conditional ]
,
. .
, , .
, .
, Trial() Release(), Main().
TRIAL, Trial(),
Release() .
RELEASE, Release() .
TRIAL, Trial() .
Conditional , .. ,
Attribute. , ,
, .
.
. -,
void, , . -,
, . -,
override.
Obsolete
Obsolete ( System.ObsoleteAttribute)
.
:
[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.WriteLine("4 / 3 " + Test.MyMeth(4, 3));
// .
Console.WriteLine("4 / 3 " + Test.MyMeth2(4, 3));
}
}
Main()
MyMeth(), , ,
MyMeth2().
Obsolete:
[Obsolete("", )]
. (true),
. , ,
, .
18
#. ,
1.0 2.0,
#.
,
#.
,
.
,
# .
,
, ,
,
.
,
,
. , , ,
,
int, string, object
, .
.
,
- .
576
I. C#
, ,
,
, .
25,
,
.
, , .
, ,
, , ,
. , ,
,
. , , , ,
, , , ,
.
, C#
, object. object
, object
. ,
,
object.
, ,
object
. - ,
.
, ,
. , ,
. ,
.
C++ Java , C#
C++ Java, ,
.
. C++
Java,
, #.
.
.
Gen, GenericsDemo, Gen.
18.
577
// .
using System;
// Gen
// Gen.
class Gen<T> {
ob; //
// , .
public Gen(T ) {
ob = ;
}
// ob, .
public GetOb() {
return ob;
}
// .
public void ShowType() {
Console.WriteLine(" T " + typeof());
}
}
// .
class GenericsDemo {
static void Main() {
// Gen int.
Gen<int> iOb;
// Gen<int> iOb.
// , strOb.
strOb.ShowType();
// strOb.
string str = strOb.GetOb();
Console.WriteLine(": " + str);
}
}
578
I. C#
.
System.Int32
: 102
System.String
: .
.
Gen :
class Gen<T> {
. -
, Gen. ,
Gen , .
, (< >).
: , ,
. Gen,
.
Gen ,
.
V . , , ,
TValue .
.
ob,
.
ob; //
, -
, Gen.
ob , Gen.
, string,
b string.
Gen.
public Gen( ) {
ob = ;
}
, . ,
,
Gen. ob
, Gen
.
,
, GetOb().
public GetOb() {
return ob;
}
ob , ,
GetOb().
18.
579
ShowType() , typeof.
Gen,
typeof .
GenericsDemo 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.
Int32. .NET, int. ob
.
int v = iOb.GetOb();
GetOb() ,
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.
# , .
,
. ,
, .
, .
,
. ,
.
, ,
. ,
, .
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 GetOb() {
return ob;
18.
}
// ob.
public void ShowType() {
Console.WriteLine(" ob: " + ob.GetType());
}
}
// .
class NonGenDemo {
static void Main() {
NonGen iOb;
// NonGen.
iOb = new NonGen(102);
// , iOb.
iOb.ShowType();
// iOb.
// .
int v = (int) iOb.GetOb();
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.GetOb(); // !
}
}
.
ob: System.Int32
: 102
ob: System.String
:
581
582
I. C#
, ,
.
.
, , NonGen.
NonGen ,
. . -,
. -,
. .
.
int v = (int) iOb.GetOb();
GetOb() object, ,
, GetOb(),
v int.
, .
, int
iOb.
. ,
.
.
// , !
iOb = strOb;
//
// .
// v = (int) iOb.GetOb(); // !
strOb iOb.
strOb , ,
. ,
NonGen , ,
NonGen NonGen.
,
. ,
GetOb(), int,
int. ,
.
,
int. ,
, , .
.
,
.
, ,
, ,
.
,
18.
583
, . C#
"" ,
, , .. ,
. . ,
.
.
. , ob
NonGen ShowType() .
Console.WriteLine(" ob: " + ob.GetType());
11, object ,
. GetType(),
, .
, , ob,
, , ob
object. CLR
.
.
.
TwoGen, Gen
.
// V.
using System;
class TwoGen<T, V> {
T ob1;
V ob2;
// ,
// V.
public TwoGen( o1, V 2) {
ob1 = o1;
b2 = 2;
}
// V.
public void showTypes() {
Console.WriteLine(" T " + typeof());
Console.WriteLine(" V " + typeof(V));
}
public getob1() {
584
I. C#
return b1;
}
public V GetObj2() {
return ob2;
}
}
// .
class SimpGen {
static void Main() {
TwoGen<int, string> tgObj =
new TwoGen<int, string>(119, " ");
// .
tgObj.ShowTypes();
// .
int v = tgObj.getob1();
Console.WriteLine(": " + v);
string str = tgObj.GetObj2();
Console.WriteLine(": " + str);
}
}
.
System.Int32
V System.String
: 119
:
, TwoGen.
class TwoGen<T, V> {
V, .
TwoGen ,
, .
TwoGen<int, string> tgObj =
new TwoGen<int, string>(119, " ");
int, V string.
,
. ,
.
TwoGen<string, string> =
new TwoGen<string, 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().
,
class.
,
struct.
, .
.
,
.
. -,
, . , ,
.
,
. ,
, ,
.
-,
, .
, , ,
.
,
,
.
,
where:
where : __
T , __
.
.
.
// ,
// .
using System;
class {
public void Hello() {
Console.WriteLine("Hello");
}
}
18.
587
// .
class : { }
// .
class { }
// ,
// Test, .
class Test<T> where : {
obj;
public Test( ) {
obj = ;
}
public void SayHello() {
// Hello() , .
obj.Hello();
}
}
class BaseClassConstraintDemo {
static void Main() {
A a = new A();
b = new ();
= new ();
// , .
588
I. C#
obj.Hello();
}
Hello() obj .
, Hello()
: ,
, ,
Hello(). ,
Hello(). ,
, Hello()
. , where
Test. ,
Hello() .
,
,
, .
.
// Test<C> t3 = new Test<C>(c); // !
// t3.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
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
, ,
NotFoundException
, Exception.
, ,
Exception. NotFoundException
Exception,
.
, PhoneList.
, EmailFriend.
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.SerializationInfo 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.
593
// .
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);
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 IPhoneNumber,
Friend Supplier.
// .
using System;
// , ,
// .
class NotFoundException : Exception {
18.
/* Exception.
.
NotFoundException Exception
. */
595
596
I. #
}
// IPhoneNumber.
public string Number { get; set; }
public string Name { get; set; }
// ...
}
// IPhoneNumber .
class EmailFriend {
// ...
}
// PhoneList
// , , PhoneNumber.
if(phList[i].Name == name)
return phList[i];
}
// .
throw new NotFoundException();
}
// .
18.
597
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 ");
}
// ,
598 I. C#
// EmailFriend IPhoneNumber.
// PhoneList<EmailFriend> plist3 =
// new PhoneList<EmailFriend>(); // !
}
}
,
PhoneList, , IPhoneList.
, Friend Supplier,
, .
EmailFriend,
. ,
Main(). ,
.
new()
new()
. ,
. new(), ,
. ,
,
. new(),
.
,
new().
// new() .
using System;
class MyClass {
public MyClass() {
// ...
}
// ...
}
class Test<T> where T : new() {
T obj;
public Test() {
// new().
obj = new (); //
}
// ...
}
class ConsConstraintDemo {
18.
599
, , ,
, .
,
.
.
where : class
600
I. #
where class ,
. ,
, int bool,
.
.
where : struct
struct ,
. (, .)
, , string, T
. ,
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
class , .
Test.
public Test() {
// ,
//
// , .
obj = null;
}
obj T .
. ,
. (
, ,
(null).
20.) ,
, . ,
.
.
, , ,
, struct enum. (
.) .
// .
using System;
struct MyStruct {
// ...
}
class MyClass {
// ...
}
class Test<T> where T : struct {
T obj;
public Test(T x) {
obj = x;
}
// ...
}
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> Test<int> ,
Test<MyClass> . ,
. .
,
.
.
class Gen<T; V> where V : T {
where ,
, V, , ,
, .
Gen,
.
. .
// .
using System;
class {
// ...
}
class : {
// ...
}
// V .
class Gen<T, V> where V : T {
// ...
}
class NakedConstraintDemo {
static void Main() {
// ,
18.
603
// .
GerKA, > = new Gen<A, >();
// ,
// .
// Gen<B, > = new Gen<B, >();
}
}
, .
Gen Main().
Gen<A, > = new Gen<A, >();
, .
// Gen<B, > = new Gen<B, >();
, .
.
.
class struct, ,
, . class struct
.
,
new(). , .
class Gen<T> where : MyClass, IMyInterface, new() {
// ...
,
MyClass, IMyInterface
.
,
where,
.
// where.
using System;
// Gen ,
// where.
class Gen<T, V> where T : class
where V : struct {
T ob1;
V ob2;
public Gen(T t, V v) {
ob1 = t;
604
I. #
ob2 = v;
}
}
class MultipleConstraintDemo {
static void Main() {
// ,
// string , a int .
Gen<string, int> obj = new Gen<string, int>("", 11);
// ,
// bool .
// Gen<bool, int> obj = new Gencbool, int>(true, 11);
}
}
Gen ,
where.
.
class Gen<T, V> where T : class
where V : struct {
, where .
.
,
,
.
, , ,
.
null, 0 false,
bool, struct ,
. :
: null, 0 ?
, Test:
class Test<T> {
obj;
// ...
obj ,
obj = null; //
obj = 0; //
// ,
?
default, .
18.
605
default()
default ,
.
,
default.
// default.
using System;
class MyClass {
// ...
}
// , .
class Test<T> {
public obj;
public Test() {
// .
// obj = null; //
// .
// obj = 0; //
// ,
// .
obj = default(T); // !
}
// ...
}
class DefaultDemo {
static void Main() {
// Test, .
Test<MyClass> = new Test<MyClass>();
if(x.obj == null)
Console.WriteLine(" x.obj <null>.");
// Test, .
Test<int> = new Test<int>();
if(.obj == 0)
Console.WriteLine(" .obj 0.");
}
}
.
x.obj <null>.
.obj 0.
606
I. C#
C# . ,
. ,
XY X, Y.
// .
using System;
// .
struct XY<T> {
;
;
public XY( , b) {
= ;
= b;
}
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);
}
}
.
10, 20
88, 99
,
. , XY
.
struct XY<T> where : struct {
// ...
18.
607
, ,
, , ,
.
,
.
.
ArrayUtils,
CopyInsert(). ,
. CopyInsert()
.
// .
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. #
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();
// , copyInsert.
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# .
CopyInsert().
.
public static bool CopyInsert<T>( e, uint idx,
T[] src, T[] target) {
18.
609
, .
, CopyInsert() ,
. , , ,
, .
.
, CopyInsert()
Main() . ,
,
. . ,
ArrayUtils.CopyInsert(99, 2, nums, nums2);
T int, 99
nums nums2 int.
, string.
.
// ArrayUtils.CopyInsert(0.01, 2, nums, nums2);
, . ,
CopyInsert() double,
nums nums2
int. ,
, ,
.
.
CopyInsert() .
.
_ _<__>(_) { // ...
__
. ,
.
,
.
. , CopyInsert()
string.
ArrayUtils.CopyInsert<string>(" #", 1, strs, strs2);
,
.
610
I. #
,
. CopyInsert()
.
public static bool CopyInsert<T>( e, uint idx,
T[] src, T[] target) where T : class {
, CopyInsert()
, int , .
// , !
, .
.
delegate _ _<__>(_);
.
.
, ,
.
SomeOp .
.
// .
using System;
// .
delegate SomeOp<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>( 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; // !
612
I. C#
Reflect() string
string, ,
SomeOp.
, C#
. .
12, ISeries.
(, ISeries ,
.) , ,
.
// .
using System;
public interface ISeries<T> {
T GetNext();//
void Reset(); //
void SetStart( v); //
}
// ISeries.
class ByTwos<T> : ISeries<T> {
T start;
T val;
// ,
// .
public delegate IncByTwo(T v);
// ,
// ByTwos.
IncByTwo incr;
public ByTwos(IncByTwo incrMeth) {
start = default(T);
val = default(T);
incr = incrMeth;
}
public T GetNext() {
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, y, 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
614
I. 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,
Iseries.
class ByTwos<T> : ISeries<T> {
ByTwos,
ISeries. . ,
, . ,
, .
class ByTwos : ISeries<T> { // !
, ISeries,
ByTwos. .
, (val)
(start), .
IncByTwo. ,
, .
ByTwos , .
ByTwos ,
. incr.
,
incr.
18.
615
ThreeD.
(X,Z,Y).
ByTwos.
GenIntfDemo
int, double 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(), v
. ,
.
, .
ISeries
.
public interface ISeries<T> where T : class {
ISeries,
,
.
class ByTwos<T> : ISeries<T> where T : class {
ISeries
.
, ByTwos<ThreeD>,
ByTwos<int> ByTwos<double>.
.
, IsIn(),
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>.
IComparable
CompareTo(), IEquatable<T> Equals().
IComparable ,
.
IEquatable .
System C#
, int, string double.
. , IEquatable<T>.
IEquatable<T> .
public interface IEquatable<T>
.
Equals(), .
bool Equals( other)
,
other. true,
, false.
IEquatable<T>
GetHashCode() Equals(Object), Object,
Equals().
,
IsIn().
// 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, IsIn().
18.
617
Equals(),
.
IComparable. :
.
, .
IComparable<T> .
public interface IComparable<T>
.
CompareTo(), .
int CompareTo( other)
,
other. ,
, other; ,
, other.
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;
}
IsIn() 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 Val.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.
if(what.CompareTo(obs[0]) < 0 ||
what.CompareTo(ob?[obs.Length-1]) > 0) return false;
return true;
}
// .
static void Main() {
// IsIn() int.
int[] nums = { 1, 2, 3, 4, 5 };
if(IsIn(2, nums))
Console.WriteLine(" 2.");
if(IsIn(99, nums))
Console.WriteLine("He .");
18.
619
// IsIn() MyClass.
MyClass[] mcs = { new MyClass(1), new MyClass(2),
new MyClass(3), new MyClass(4));
if(IsIn(new MyClass()), mcs))
Console.WriteLine(" MyClass()).");
if(IsIn(new MyClass(99), mcs))
Console.WriteLine("He .");
// InRange() 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.");
if(!InRange(0, nums))
Console.WriteLine(" 0 HE nums.");
if(!InRange(6, nums))
Console.WriteLine(" 6 HE nums.");
// InRange() MyClass.
if(InRange(new MyClass(2), mcs))
Console.WriteLine(" MyClass(2) nums.");
620
I. C#
,
, , == !=,
.
IComparable IComparable<T> lEquatable<T>.
. ,
.
, ,
,
.
,
.
// .
using System;
// .
class Gen<T> {
ob;
public Gen(T ) {
ob = ;
}
// ob.
public GetOb() {
return ob;
}
}
// , Gen.
class Gen2<T> : Gen<T> {
public Gen2(T o) : base(o) {
// ...
}
}
class GenHierDemo {
static void Main() {
Gen2<string> g2 = new Gen2<string>("");
Console.WriteLine(g2.GetOb());
}
}
18.
621
Gen2 Gen.
Gen2 .
class Gen2<T> : Gen<T> {
Gen2
Gen. , , Gen2,
Gen. , :
Gen2<string> g2 = new Gen2<string>("");
string Gen. ob
Gen2, Gen, string.
, Gen2
, Gen. ,
,
,
.
,
, .
, Gen2
.
// .
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) : base() {
ob2 = o2;
}
public V GetObj2() {
return ob2;
}
622 I. #
}
// Gen2.
class GenHierDemo2 {
static void Main() {
// Gen2
// string int.
Gen2<string, int> x =
new Gen2<string, int>(" : ", 99);
Console.Write(x.GetOb());
Console.WriteLine(x.GetObj2());
}
}
Gen2
.
class Gen2<T, V> : Gen<T> {
, Gen; V ,
Gen2.
b2 , GetObj2(). Main()
Gen2 string 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.
623
, .
, GetOb().
// .
using System;
// .
class Gen<T> {
protected ob;
public Gen(T ) {
ob = ;
}
// ob. .
624
I. C#
return ob;
}
}
// , Gen.
// GetOb().
class Gen2<T> : Gen<T> {
public Gen2 (T o) : base(o) { }
// GetOb().
public override T GetOb() {
Console.Write(" GetOb() Gen2" + " : ");
return ob;
}
}
// .
class OverrideDemo {
static void Main() {
// Gen int.
Gen<int> iOb = new Gen<int>(88);
// GetOb() Gen.
Console.WriteLine(iOb.GetOb());
// Gen2
// iOb Gen<int>.
iOb = new Gen2<int>(99);
// GetOb() Gen2.
Console.WriteLine(iOb.GetOb());
}
}
.
GetOb() Gen : 88
GetOb() Gen2 : 99
,
GetOb() Gen2,
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> {
b1;
V ob2;
// ...
//
// .
public void Set(T ) {
ob1 = ;
}
public void Set(V ) {
ob2 = ;
}
}
class AmbiguityDemo {
static void Main() {
Gen<int, double> ok = new Gen<int, double>();
Gen<int, int> notOK = new Gen<int, int>();
ok.Set(10); // ,
notOK.Set(10); // , !
}
}
.
, Gen : V. Gen
Set() V, .
626
I. #
15
. #, . C# 4.0
, .
, ,
,
, .NET Framework.
, , ,
. ,
, .
.
,
, ,
.
18.
627
.
,
.
out, .
,
. IMyCoVarGenIF,
.
// .
public interface IMyCoVarGenIF<out > {
GetObject();
}
, .
out. out
, . ,
GetObject()
, .
,
IMyCoVarGenIF
. MyClass.
// IMyCoVarGenIF.
class MyClass<T> : IMyCoVarGenIF<T> {
T obj;
public MyClass(T v) { obj = v; }
public T GetObject() { return obj; }
}
, out
, MyClass.
, , out
.
.
// .
class Alpha {
string name;
public Alpha(string n) { name = n; }
public string GetName() { return name; }
// ...
}
class Beta : Alpha {
public Beta(string n) : base(n) { }
// ...
}
, Beta Alpha.
628
I. #
,
.
// IMyCoVarGenIF MyClass<Alpha>.
// , .
IMyCoVarGenIF<Alpha> AlphaRef =
new MyClass<Alpha>(new Alpha("Alpha #1"));
Console.WriteLine(" , AlphaRef: " +
AlphaRef.GetObject().GetName());
// MyClass<Beta> AlphaRef.
// *** . ***
AlphaRef = new MyClass<Beta>(new Beta("Beta #1"));
Console.WriteLine(" , " +
" AlphaRef: " + AlphaRef.GetObject().GetName());
, AlphaRef IMyCoVarGenIF<Alpha>
MyClass<Alpha>.
, MyClass IMyCoVarGenIF,
, Alpha.
GetName() ,
GetObject(). , Alpha
, GetName(), .
AlphaRef MyClass<Beta>,
, Beta Alpha,
IMyCoVarGenIF.
, .
.
// .
using System;
// .
public interface IMyCoVarGenIF<out > {
GetObject();
}
// IMyCoVarGenIF.
class MyClass<T> : IMyCoVarGenIF<T> {
T obj;
public MyClass(T v) { obj = v; }
public T GetObject() { return obj; }
}
// .
class Alpha {
string name;
public Alpha(string n) { name = n; }
18.
629
Console.WriteLine(" , " +
"AlphaRef: " + AlphaRef.GetObject().GetName());
// MyClass<Beta>
// AlphaRef.
// *** . ***
AlphaRef = new MyClass<Beta>(new Beta("Beta #1"));
Console.WriteLine(" , " +
630
I. C#
IMyCoVarGetIF. , IMyCoVarGenIF2
.
.
,
. , out ,
.
.
. , .
public interface IMyCoVarGenIF2<out > {
void M<V>() where V:T; // , T
//
}
, ,
, .
.
, .
in,
.
,
.
IMyContraVarGenIF .
, Show().
// , .
public interface IMyContraVarGenIF<in > {
void Show(T obj);
}
,
in, .
, obj
Show().
IMyContraVarGenIF MyClass,
.
// IMyContraVarGenIF.
class MyClass<T> : IMyContraVarGenIF<T> {
public void Show(T x) { Console.WriteLine(x); }
}
Show()
, ToString()
WriteLine().
, .
// .
class Alpha {
18.
631
BetaRef.Show(new Beta());
// AlphaRef BetaRef.
// *** . ***
BetaRef = AlphaRef;
BetaRef.Show(new Beta());
,
IMyContraVarGenIF, MyClass,
.
Alpha,
Beta. .
IMyContraVarGenIF<Beta>,
MyClass<Alpha>.
, .
632
I. C#
, , BetaRef.
Show() Beta, . Beta
MyClass<Beta> Show().
AlphaRef BetaRef.
.
MyClass<Beta>, AlphaRef
MyClass<Alpha>. Alpha Beta,
.
, in
IMyContraVarGenIF,
. .
.
// .
using System;
// , .
public interface IMyContraVarGenIF<in > {
void Show(T obj);
}
// IMyContraVarGenIF.
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>.
// , .
18.
633
// .
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
, . ,
IMyContraVarGenIF2 .
, IMyContraVarGenIF2
in. , ,
IMyContraVarGen,
IMyContraVarGenIF2.
,
.
, in ,
.
15,
, , ,
. C# 4.0,
.
,
.
634
I. C#
.
// , .
delegate bool SomeOp<in >( obj);
, .
.
// , .
delegate AnotherOp<out , V>(V obj);
, ,
, . V
.
.
//
// .
using System;
// , .
delegate bool SomeOp<in >( obj);
// , .
delegate AnotherOp<out , 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 ChangeIt(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> checkIt = IsEven;
18.
635
// SomeOp<Beta>.
SomeOp<Beta> checkIt2;
// - SomeOp<Alpha> SomeOp<Beta>.
// *** . ***
checklt2 = checkIt;
// .
Console.WriteLine(checkIt2(obj));
// , .
// AnotherOp.
// Beta,
// - Alpha.
// , modifyIt
// ChangeIt.
AnotherOp<Beta, Alpha> modifyIt = ChangeIt;
// Alpha,
// Alpha.
AnotherOp<Alpha, Alpha> modifyIt2;
// modifyIt modifyIt2.
// *** . ***
modifyIt2 = modifyIt;
// .
objA = modifyIt2(obj);
Console.WriteLine(objA.Val);
}
}
.
False
6
. ,
SomeOp and AnotherOp
in out .
-
.
, :
?
: . , C#
:
. .
636
I. C#
MSIL,
.
, JIT-
,
.
.
, Gen<T>,
Gen<T> .
, ,
, .
,
.
,
, ,
int double. , Gen<int>
Gen, Gen<double>
Gen,
. , ,
,
( ). .
,
,
.
, , .
,
.
extern.
.
static,
. ,
static.
. ,
static .
#,
, .
, , ,
. ,
.
#.
.
19
LINQ
, LINQ
#.
C# 3.0
,
#,
,
,
. , LINQ
#.
LINQ Language-Integrated Query,
.. .
,
. ,
.
,
,
,
. ,
, . ,
.
(SQL).
, XML,
. , 3.0
C# .
LINQ.
LINQ C# ,
LINQ-
638
I. C#
. , ,
, . , , ,
, ,
, .
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.
, . ,
, foreach. .
.
, . ,
, .
.
LINQ.
, .
// LINQ.
using System;
using System.Linq;
class SimpQuery {
static void Main() {
int[] nums = { 1, -2, 3, 0, -4, 5 };
// .
640
I. C#
LINQ
System.Linq.
nums int. C#
IEnumerable<T>.
C# ,
LINQ.
, nums
.
var posNums = from n in nums
where n > 0
select n;
posNums .
, .
var posNums .
, posNums
. ,
( IEnumerable<T>).
posNums .
from, .
, .
n.
( nums).
. n int.
from.
from _ in _
where, ,
, .
where.
where _
_ bool.
.
where. where.
where n > 0
,
. n > 0
n n .
, . ,
where ,
.
select group.
select, ,
. , ,
.
, ,
where. ,
19. LINQ
641
. ,
. ,
select , .
.
, posNums ,
. , ,
. ,
, ,
.
posNums ,
.
.
foreach(int i in posNums) Console.WriteLine(i + " ");
posNums ,
. foreach
, 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#
// .
nums[1] = 99;
Consofe.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
643
,
. ,
. ,
#. ,
IEnumerable<T>,
. ( ,
IEnumerable<T> , , ,
.)
IEnumerable, .
from.
int n.
var posNums = from int n in nums
// ...
, ,
IEnumerable<T>,
.
, ,
IEnumerable<T>, . ,
IEnumerable<T>,
, select.
int,
int. ( , n int,
nums.)
IEnumerable<int>
.
IEnumerable<int> posNums = from n in nums
where n > 0
select n;
, , select,
, IEnumerable<T>,
.
var ,
select. ,
, select
, .
foreach,
, .
int. :
,
var. , var
, .
,
- .
644
I. 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 ,
, .
. .
where
, where ,
.
,
.
, , where.
, ,
10.
// 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.
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 ts n < 10
select n;
, where
C# , . ,
.
. netAddrs ,
".net". ,
, .net
.
// 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.EndsWithC.net",
StringComparison.Ordinal)
select addr;
// .
foreach(var str in netAddrs) Console.WriteLine(str);
}
}
646
I. C#
.
hsNameB.net
hsNameC.net
, where
EndsWith().
true,
, .
orderby
. ,
:
.
, ,
LINQ, orderby.
orderby
.
. orderby
:
orderby
, .
, ,
.
ascending
descending . ,
ascending, , .
, orderby
int .
// orderby.
using System;
using System.Linq;
class OrderbyDemo {
static void Main() {
int[] nums = { 10, -19, 4, 7, 2, -5, 0 };
// .
19. LINQ
647
.
: -19 -5 0 2 4 7 10
, descending, .
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
648
I. #
new
new
new
new
new
new
new
new
new
new
new
};
//
// .
// ,
// , , ,
var accInfo = from in accounts
orderby acc.LastName, acc.FirstName, acc.Balance
select acc;
Console.WriteLine(" : ");
string str = "";
// .
foreach(Account acc in accInfo) {
if(str != acc.FirstName) {
Console.WriteLine();
str = acc.FirstName;
}
Console.WriteLine("{0}, {1}\tHoep : {2}, {3,10:C}",
acc.LastName, acc.FirstName,
acc. AccountNumber, acc.Balance);
}
Console.WriteLine();
}
}
.
:
, : 108, $10.98
,
,
,
: 434, ($123.32)
: 454, $987.13
: 436CD, $1,923.85
, : 968, $5,146.67
,
: 897CD, $3,223.19
, : 445, ($213.67)
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
orderby
.
var accInfo = from acc 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 accInfo = 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)
,
: .
select
select , .
.
select
650
I. C#
select
.
. select
.
,
,
, .
.
select
.
, 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 r in sqrRoots)
Console.WriteLine("{0:#.##}", r);
}
}
.
,
:
4.05
3.48
10.04
5.02
select.
select Math.Sqrt(n);
.
Math.Sqrt(),
19. LINQ
651
. ,
, ,
, nums. ,
. , select
,
, .
,
select. EmailAddress,
. ,
. ,
EmailAddress. , ,
, .
// .
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("Tom", "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. #
Tom@HerbSchildt.com
Sara@HerbSchildt.com
select.
select entry.Address;
(Address). ,
, EmailAddress.
s foreach string.
, , ,
, select.
select
, ,
. .
ContactInfo, ,
. ,
EmailAddress, . Main()
ContactInfo, ,
,
EmailAddress. ,
, select, EmailAddress,
ContactInfo, .
//
// EmailAddresses ContactInfo.
using System;
using System.Linq;
class ContactInfo {
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public ContactInfo(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
ContactInfo[] contacts = {
new Contactlnfo("", "Herb@HerbSchildt.com", "555-1010"),
new Contactlnfo("Tom", "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,
, ContactInfo,
contacts. , EmailAddress
select .
from
from,
. from ,
.
, from
.
,
.
// from
// , X, Y Z.
using System;
using System.Linq;
// .
class ChrPair {
public char First;
654
I. C#
19. LINQ
655
, ch1 ch2
from.
ChrPair,
.
from
, .
" let
" .
group
group, .
,
, .
group ,
, . group
, . ( ,
, select.) group.
group _ by
, ,
.
group ,
IGrouping<TKey, TElement>, .. ,
System.Linq.
. ,
, IEnumerable<IGrouping<TKey, TElement>>. IGrouping
Key, ,
.
, group.
, -,
,
, .org .com.
// 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", "hsNameI.tv"
};
// -,
// .
656
I. C#
var webAddrs = from addr in websites
where addr.LastIndexOf('.') != -1
group addr by addr.Substring(addr.LastIndexOf('.'));
// .
foreach(var sites in webAddrs) {
Console.WriteLine("-, " +
" " + sites.Key);
foreach(var site in sites)
Console.WriteLine(" " + site);
Console.WriteLine();
}
}
}
.
-, .m
hsNameA.com
hsNameD.com
-, .net
hsNameB.net
hsNameC.net
hsNameH.net
-, .org
hsNameE.org
hsNameF.org
-, .tv
hsNameG.tv
hsNameI.tv
, , ,
-.
, group .
var webAddrs = from addr in websites
where addr.LastlndexOf('.') != -1
group addr by addr.Substring(addr.LastIndexOf('.'));
LastIndexOf()
Substring(), string. (
7, . Substring(),
, , ,
, .)
- LastIndexOf().
Substring() ,
. ,
where , .
LastIndexOf() -1,
.
19. LINQ
657
, ,
webAddrs, ,
foreach.
,
. foreach
IGrouping, .
string.
sites IGrouping<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();
}
into
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", "hsNameI.tv"
};
// -,
// ,
// , .
// ws ,
// .
var webAddrs = from addr in websites
where addr.LastIndexOf('.') != -1
group addr by addr.Substring(addr.LastIndexOf('.'))
into ws
where ws.Count() > 2
select ws;
// .
Console.WriteLine(" " +
" .\n");
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
,
.net, ,
.
.
group addr by addr.Substring(addr.LastIndexOf('.'))
into ws
where ws.Count() >2
select ws;
19. LINQ
659
group
where.
ws. ,
group. where
, ,
. Count(),
IEnumerable.
. (
.)
select.
let
. , ,
, ,
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
chrArray , str.
ToCharArray().
let chrArray = str.ToCharArray()
let chrArray
, . C#
IEnumerable<T>, chrArray
, from.
, from
,
.
let
.
IntoDemo .
var webAddrs = from addr in websites
let idx = addr.LastIndexOf('.')
where idx != -1
group addr by addr.Substring(idx)
into ws
where ws.Count() > 2
select ws;
idx. Substring().
.
join
,
, . ,
19. LINQ
661
- ,
, ,
.
,
, .
- "" ( ).
LINQ, join.
join ( from).
from __ in __
join __ in __
on __. equals __.
join, ,
, .
__ __
, .
on . __.
__. , "
" . , join ,
, .
, join ,
, . , join
, ,
. -.
, 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#
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 statusList :
. on/equals join
,
, .
, select Temp,
.
select new Temp(item.Name, entry.InStock);
, , ,
Temp.
join .
. , into join,
, ,
. (
.) , ,
join, ,
.
. , ,
.
C# ,
LINQ. ,
664
I. C#
, .
, select.
, ,
(, , join),
.
.
,
.
:
new { _ = _, _ = _, ... }
, ,
,
.
new { Count = 10, Max = 100, Min = 0 }
: Count, Min, 10, 100 0 .
. ,
. 8,
.
,
. (, , .
, , .)
, ,
.
.
myOb, ,
.
var myOb = new { Count = 10, Max = 100, Min = 0 }
, .
Console.WriteLine(" " + myOb.Count);
if(i <= myOb.Max && i >= myOb.Min) // ...
,
, .
.
.
, ,
. ,
C# .
,
,
join. , Temp
, join.
19. LINQ
665
- ,
.
.
//
// , 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 {
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("", 6411)
};
InStockStatus[] statusList = {
new InStockStatus(1424, true),
new InStockStatus(7892, false),
new InStockStatus(8534, true),
new InStockStatus(6411, true)
};
// , Item
// InStockStatus
// . .
var inStockList = from item in items
join entry in statusList
on item.ItemNumber equals entry.ItemNumber
666
I. C#
select new { Name = item.Name,
InStock = entry.InStock };
Console.WriteLine("\t\n");
// .
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 .
foreach, .
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 lst
select new { How = how, Tlist = lst };
// .
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 lst
select new { How = how, Tlist = lst };
. from
how travelTypes. ,
travelTypes : ,
, .
join . , ,
. into
join ,
. lst. , select
, ,
19. LINQ
669
how ( ) .
foreach.
foreach(var t in byHow) {
Console.WrifeLine(" <{0} > :", t.How);
foreach(var m in t.Tlist)
Console.WriteLine(" " + m.Name);
Console.WriteLine();
}
,
, , .
.
, ,
#. , ,
.
,
, .
System.Linq.Enumerable
IEnumerable<T>.
( System.Linq.Queryable,
IQueryable<T>,
.)
, .
C# 3.0 .
, ,
IEnumerable<T>.
Enumerable ,
, .
. ,
, , ,
.
.
select
where
orderby
Select(selector)
Where(predicate)
OrderBy(keySelector)
OrderByDescending(keySelector)
Join(inner, outerKeySelector, innerKeySelector,
resultSelector)
GroupBy(keySelector)
join
group
670
I. #
Join(),
,
Func<T, TResult>. ,
:
delegate TResult Func<in , out TResult>(T arg)
TResult , , .
selector, predicate keySelector
, . , Where()
predite .
.
, .
Join() . (inner)
,
, Join().
outerKeySelector,
LnnerKeySelector.
resultSelector. outerKeySelector
Func<TOuter, >, innerKeySelector Func<TInner,
>, resultSelector Func<TOuter, Tinner, TResult>,
TOuter ; Tinner
; TResult
, .
,
Func,
. -.
15, - ,
, , , ,
C# - ,
Func. -
,
, .
-,
, , C#
. .
.
,
Where() Select() .
// .
// .
using System;
using System.Linq;
class SimpQuery {
static void Main() {
19. LINQ
671
672
I. #
class GroupByDemo {
static void Main() {
string[] websites = {
"hsNameA.com", "hsNameB.net", "hsNameC.net",
"hsNameD.com", "hsNameE.org", "hsNameF.org",
"hsNameG.tv", "hsNameH.net", "hsNameI.tv"
};
//
// - .
var webAddrs = websites.Where(w => w.LastIndexOf('.') != 1).
GroupBy(x => x.Substring(x.LastIndexOf(".", 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,
k1 => k1.ItemNumber,
k2 => k2.ItemNumber,
(k1, k2) => new Temp(k1.Name, k2.InStock) );
Temp
, .
.
var inStockList = items.Join(statusList,
k1 => k1.ItemNumber,
19. LINQ
673
k2 => k2.ItemNumber,
(k1, k2) => new { k1.Name, k2.InStock} );
, C#
, . ,
, ,
. , .
where < 10
.
Where( => < 10)
,
.
,
#? ,
, #,
.
,
, , #,
,
. .NET Framework
IEnumerable<T> Enumerable.
, .
, .
All(predicate)
true,
,
predicate
Any(predicate)
true,
,
predicate
Average()
Contains(value) true,
Count()
, ..
First()
Last()
Max()
Min()
Sum()
674
I. #
Count() .
, .
// , Enumerable.
using System;
using System.Linq;
class ExtMethods {
static void Main() {
int[] nums ={ 3, 1, 2, 5, 4 };
Console.WriteLine(" " + nums.Min());
Console.WriteLine(" " + nums.Max());
Console.WriteLine(" " + nums.First());
Console.WriteLine(" " + nums.Last());
Console.WriteLine(" " + nums.Sum());
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.
, ,
, , #.
. , Average()
,
, .
// Average() .
using System;
using System.Linq;
class ExtMethods2 {
static void Main() {
19. LINQ
675
:
LINQ : .
,
, foreach.
.
, ,
,
. , , Count().
,
, Count().
,
. , ,
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() .
.
,
, rray() ToList().
Enumerable. ToArray()
, ToList() List. (
25.)
. ,
, posNums,
.
int[] pnums = posNum.rr(); //
foreach(int i in pnums)
Console.Write(i + " ");
}
, LINQ, ,
- . , -
19. LINQ
677
, .
System.Linq.Expressions.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, bool>>
IsFactorExp = (n, d) => (d != 0) ? (n % d) == 0 : false;
// .
Func<int, int, bool> IsFactor = IsFactorExp.Compile();
// .
if(IsFactor(10, 5))
Console.WriteLine(" 5 10.");
if(!IsFactor (10, 7))
Console.WriteLine(" 7 10.");
Console.WriteLine();
}
}
.
678 I. C#
5 10.
7 10.
.
.
Expression<Func<int, int, bool>>
IsFactorExp = (n, d) => (d != 0) ? (n % d) == 0 : false;
-
. , ,
IsFactorExp.
.
Funccint, int, bool> IsFactor = IsFactorExp.Compile();
IsFactorExp ,
, .
, <Func<int, int, bool>
. Func int
bool.
Func, -,
. -
Func .
, Func .
,
, .
, , ,
. , , .
LINQ.
, .
, . ,
this. ,
, .
. , , ,
-
, , .
.
static _ (this __ ob, _)
, _ ,
, 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, CultureInfo.
CurrentCulture);
else temp += Char.ToLower(ch, CultureInfo.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());
// RevCase().
Console.WriteLine(str + " : " +
str.RevCase());
// AbsDivideBy().
Console.WriteLine(" val.AbsDivideBy(-2): " +
val.AbsDivideBy(-2));
}
}
.
680
I. #
8 0.125
Alpha Beta Gamma : aLPHA b g
val.AbsDivideBy(-2): 4
MyExtMeths. ,
. ,
, . (
System.
Linq, ,
LINQ.)
,
. ,
.
val.AbsDivideBy(-2)
val n AbsDivideBy(),
-2 d.
, Reciprocal() AbsDivideBy()
double, ,
.
8.0.Reciprocal()
8.0.AbsDivideBy(-1)
, RevCase() .
"AbCDe".RevCase()
.
PLINQ
.NET Framework 4.0 LINQ
PLINQ.
.
. PLINQ ,
, 24.
20
, ,
#,
.
.
.
C# ,
C++,
. ,
C#
,
Java.
,
,
.
,
.
C# "
" .
.
, ,
(CLR).
1, C#
.
,
CLR.
682
I. C#
, ,
, , -
. , ,
- . , ,
.
,
? , .
C++,
, ,
, .. - #.
,
, .
,
. ,
, .
#. -
(,
), C# .
,
.
C# , C/C++.
, C/C++, #.
, C# .
. , , ,
#. ,
/unsafe.
,
.
, -
, . ,
, , .
,
. .
- .
-:
*
_;
, .
, C# .
.
* . .
_ -.
20. , ,
683
. ip
int, .
int* ip;
float , .
float* fp;
, *,
, .
, ,
. ip
int, fp float.
, , , .
.
/++,
C# C/C++.
C/C++ * .
:
int* , q;
int q int.
.
int* ;
int q;
C# * ,
int* , q;
-. .
int* ;
int* q;
C/C++ #.
* &
: * &. &
. (,
.) , :
int* ip;
int num = 10;
ip = #
ip num.
num .
num. ip
10, num, ,
. &
, . ,
: " ip
num."
684
I. C#
, *, &.
, ,
. , ,
. , ip
num, , :
int val = *ip;
val 10 num,
ip. * .
: " val ,
ip."
* .
, ,
.
*ip = 100;
100 ,
ip, .. num.
: " 100 ,
ip."
unsafe
, ,
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
fixed
fixed,
" ".
, , ,
.
" ", , .
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#
.num: 19
.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 = 20; // ->
Console.WriteLine(" " + p->Sum());
: ++,
--, + -. ,
, . ,
p1 2000, ..
2000.
p1++;
p1 2004, 2001! ,
p1 int.
int C# 4 ,
p1 4. :
p1 4.
p1--;
, p1 1996,
2000!
:
,
,
, .
20. , ,
687
.
. , :
p1 = p1 + 9;
p1
, .
,
, , .
,
.
,
, .
, float
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) (fp));
ip++;
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
,
. , int
4 , double 8 ,
.
, ==, <
>. ,
- . ,
p1 2 ,
, , .
p1 2 ,
, .
C# . ,
fixed
. .
/*
. */
using System;
class PtrArray {
unsafe static void Main() {
int[] nums = new int [10];
fixed(int* p = &nums[0], p2 = nums) {
if(p == p2)
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; //
for(int 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
p[1]: 1
p[2]: 2
p[3]: 3
p[4]: 4
p[5]: 5
p[6]: 6
p[7]: 7
[8]: 8
[9]: 9
.
*(+0) : 0
*(+1) : 1
*(+2) : 2
*(+3) : 3
*(+4) : 4
690
I. C#
*(+5)
*(+6)
*(+7)
*(+8)
*(+9)
:
:
:
:
:
5
6
7
8
9
,
*(ptr + i)
.
ptr[i]
, .
-, .
. -,
Length, .
, , .
C# .
. char*
fixed.
fixed(char* = str) { // ...
fixed
, .
, .. .
. /++
, , ,
char* , , C/C++.
,
char*.
// 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 int.
int** q;
, , , q
, int.
,
, *, .
using System;
class MultipleIndirect {
692
I. #
, .
int
.
int * [] ptrs = new int * [3];
var int
, .
ptrs[2] = Svar;
var,
.
*ptrs[2]
sizeof
C# .
sizeof. :
sizeof()
, . ,
sizeof , ,
: .
stackalloc
, , stackalloc.
.
:
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
2
3
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 Name[80]; //
public double Balance;
public long ID;
}
Name,
FixedBankRecord 80 Name.
C++. ,
FixedBankRecord 96, .. .
, .
// .
using System;
// .
unsafe struct FixedBankRecord {
public fixed byte Name[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.Nullble<>, , .
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 100.
count = 100;
, ,
. -,
. , count , ,
, .
if (count != null) //
count , .
-,
HasValue Nullable<T>, ,
. .
bool HasValue
HasValue true, ,
, ,
false. ,
count
HasValue.
if(count.HasValue) //
,
Value Nullable<T>.
Value
20. , ,
697
Value ,
.
, System.
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.Value);
else
Console.WriteLine(" count ");
}
}
.
count
count : 100
,
. ,
.
.
,
.
.
// .
using System;
class NullableDemo {
static void Main() {
698
I. 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
??
System.
InvalidOperationException, .
, , ,
.
, ??,
. ,
,
. .
??.
_ ?? __
_ ,
?? . ??
__.
, balance
. currentBalance
0.0, ,
.
20. , ,
699
,
, .
:
<, >, <= >=, ,
, .. 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 ()
null ().
& | bool?.
P
true
false
null
null
null
Q
null
null
true
false
null
P| Q
true
null
true
null
null
P&Q
null
false
null
false
null
, ! bool?,
(null),
(null).
2.0, C# ,
. partial.
.
partial ,
:
partial _ { // ...
_ , ,
.
partial.
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 xy1.cs, 2.cs 3.cs,
Test test.cs,
.
csc test.cs xy1.cs xy2.cs .cs
: C# .
,
.
, partial
. 3.0, C#
. ,
. , partial
.
702 I. 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 XY(1, 2);
xy.ShowXY();
}
}
, Show() XY,
.
X Y. , Show() ShowXY(),
:
20. , ,
703
X Y. Show(),
ShowXY() .
.
void.
. out.
, 3, C#
. , ,
, ,
, .
,
, ,
.
, COM-
,
, , , IronPython. C# 4.0
.
C# 4.0 dynamic.
, dynamic object,
.
object , dynamic
, object
.
, ,
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(CultureInfo.CurrentCulture);
Console.WriteLine(" str : " + str);
val = val + 2,Console.WriteLine(" val : " + val + '\n');
string str2 = str.ToLower(CultureInfo.CurrentCulture);
Console.WriteLine(" str2 : " + str2);
// .
int = val * 2;
Console.WriteLine(" x : " + );
}
}
.
str :
val : 10
str :
val : 12
str2 :
: 24
str val,
dynamic. ,
.
.
str ToUpper() ToLower() String,
.
,
, .
, , ,
.
""
, , ,
, . , val
, ,
. str ,
. , , ,
, ,
dynamic .
.
: dynamic
dynamic. ,
dynamic . ,
,
20. , ,
705
. ,
:
bool b = val;
-
int ( val ) bool.
,
.
,
. , str val object,
.
, object ,
, . , ,
object dynamic.
,
object ,
object. dynamic,
, ,
.
, dynamic
,
. 17, ,
, , ,
Invoke(). ,
, . ,
,
, , .
, ,
. ,
, , ,
, .
dynamic, Invoke(), .
MyClass.cs.
.
public class DivBy {
public bool IsDivBylint 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 MyClass.dll.
,
.
csc /t:library MyClass.cs
706
I. #
, MyClass.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];
// .
ConstructorInf[] ci = t.GetConstructors();
int j;
for(j = 0; j < ci.Length; j++)
if(ci[j].GetParameters().Length == 0) break;
if(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.dll, DivBy.
obj dynamic. ,
IsDivBy() IsEven() obj ,
Invoke(). ,
obj DivBy.
.
.
, dynamic ,
. ,
, , , ,
dynamic,
. , .
dynamic, ,
dynamic ,
.
dynamic object , dynamic
object .
.
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.Office.Interop.Execl.Application.
708
I. C#
"O" 1-
Excel ,
.
myXLapp.get_Range("C1", "3").set_Value(Type.Missing, "OK");
get_Range(), .
set_Value(), (
) . Range
Value, .
,
. , Type.Missing
, , .
, C# 4.0,
, .
myXLapp.Range["C1", "3"].Value = "OK";
, .Missing ,
.
, ref
. , ,
ref , . ,
,
, ref
.
.
.
,
. ,
InternalsVisibleTo.
I
, C#
.
lock
lock .
23,
.
.
20. , ,
709
C# .
, ,
.. .
,
, .
,
.
lock. :
lock(obj) {
//
}
obj , .
, ,
.
,
.
.
lock 23.
readonly
,
readonly.
,
. ,
. ,
readonly .
, , ,
. ,
readonly.
, readonly
const, .
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];
int[] 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 !
}
}
MyClass.SIZE 10.
, . ,
. .
const volatile
, , const
, .
. ,
const, , . ,
:
const int i = 10;
i const 10. const
readonly, .
readonly , const .
, , volatile ,
. ,
. , C#
,
, .
, volatile.
20. , ,
711
, volatile
, .
using
using,
using . :
using (obj) {
// obj
}
using ( obj = ) {
// obj
}
obj ,
, System.IDisposable.
, using.
using, .
using obj Dispose(),
System.IDisposable. , using
, ,
. , , , using
, System.IDisposable.
using.
// using.
using System;
using System.IO;
class UsingDemo {
static void Main() {
try {
StreamReader sr = new StreamReader("test.txt");
// using.
using(sr) {
// ...
}
} catch(IOException exc) {
// ...
}
try {
// StreamReader using.
using(StreamReader sr2 = new StreamReader("test.txt")) {
// ...
}
} catch(IOException exc) {
// ...
}
}
}
712
I. C#
IDisposable StreamReader
( TextReader).
using.
Dispose() , .
, using
,
, . ,
using .
, using .
.NET Framework ,
IDisposable.
using.
extern
extern .
.
extern
#. , ,
. ,
.
,
extern. ,
.
extern _ _(_);
.
extern
DllImport, DLL,
. DllImport System.Runtime.
InteropServices. , , ,
DLL, .
, . ( ++,
DLL
.)
, ,
, .
ExtMeth., AbsMax().
#include <stdlib.h>
int __declspec(dllexport) AbsMax(int a, int b) {
return abs(a) < abs(b) ? abs(b) : abs(a);
}
AbsMax()
. _
declspec(dllexport).
20. , ,
713
Microsoft.
AbsMax() DLL, .
ExtMeth. .
CL /LD /MD ExtMeth.
DLL ExtMeth.dll.
#,
AbsMax().
using System;
using System.Runtime.InteropServices;
class ExternMeth {
// .
[DllImport("ExtMeth.dll")]
public extern static int AbsMax(int a, int b);
static void Main() {
// .
int max = AbsMax(-10, 20);
Console.WriteLine(max);
}
}
DllImport
. DLL,
AbsMax(). ExtMeth.dll,
AbsMax() .
, , 20.
extern
, ,
. , test1
MyClass, test2 ,
.
. . ,
/r, .
/r:Asm1=test1
/r:Asm2=test2
extern,
.
.
extern alias _;
,
.
extern alias Asm1;
extern alias Asm2;
714
I. C#
MyClass
.
,
. .
, test1.cs.
using System;
namespace MyNS {
public class MyClass {
public MyClass() {
Console.WriteLine(" MyClass1.dll.");
}
}
}
test2.cs.
using System;
namespace MyNS {
public class MyClass {
public MyClass() {
Console.WriteLine(" MyClass2.dll.");
}
}
}
, , test1.cs test2.cs,
MyNS
MyClass. , MyClass
.
, test3.cs,
MyClass test1.cs test2.cs.
.
// .
20. , ,
715
test3.cs,
csc /r:Asm1=test1.dll /r:Asm2=test2.dll test3.cs
/r,
, .
Asm1 test1.dll, Asm2
test2.dll.
extern, .
extern alias Asm1;
extern alias Asm2;
Main()
MyClass.
MyClass.
Asm1::MyNS.MyClass
,
, ,
, , , , -.
.
.
MyClass1.dll.
MyClass2.dll.
II
C#
21
System
22
23
.
:
II #.
I, #
.NET Framework.
#, .NET
Framework .
.NET Framework
.
, ,
,
using . ,
,
.
.NET Framework ,
. (
!) II
,
System. ,
,
.
- 14.
24
.
:
TPL
25 ,
26
21
System
System.
.NET Framework.
, ,
, ,
C#
.NET Framework. ,
System
.
, System
,
, System.Net.
.
System.
720 II. C#
System
,
.
ActivationContext
AppDomainManager
Applicationldentity
Attribute
Buffer
Console
ContextStaticAttribute
Delegate
EventArgs
FlagsAttribute
GenericUriParser
Lazy<T>
LoaderOptimizationAttribute
Math
NetPipeStyleUriParser
NonSerializedAttribute
ObsoleteAttribute
Random
STAThreadAttribute
Th rea dStaticAttri bute
TimeZonelnfo.AdjustmentRule
Type
UriBuilder
UriTemplateEquivalenceComparer
UriTypeConverter
WeakReference
Activator
AppDomainSetup
Array
AttributeUsageAttribute
CharEnumerator
ConsoleCancelEventArgs
Convert
Enum
Exception
FtpStyleUriParser
GopherStyleUriParser
Lazy<T, TMetadata>
LocalDataStoreSlot
MTAThreadAttribute
NetTcpStyleUriParser
Nullable
OperatingSystem
ResolveEventArgs
String
TimeZone
Tuple
Unhandled ExceptionEventArgs
Uri Parser
UriTemplateMatch
ValueType
AppDomain
Applicationld
AssemblyLoadEventArgs
BitConverter
CLSCompliantAttribute
ContextBoundObject
DBNull
Environment
FileStyleUriParser
GC
HttpStyleUriParser
LdapStyleUriParser
MarshalByRefObject
MulticastDelegate
NewsStyleUriParser
Object
ParamArrayAttribute
SerializableAttribute
StringComparer
TimeZonelnfo
Tuple<...> ( )
Uri
UriTemplate
UriTemplateTable
Version
, System.
Arglterator
Byte
DateTime
Double
Int32
ModuleFlandle
RuntimeFieldFlandle
Sbyte
TimeZonelnfo.TransitionTime
Ulnt32
Void
ArraySegment<T>
Char
DateTimeOffset
Guid
Int64
Nullable<T>
RuntimeMethodHandle
Single
TypedReference
Ulnt64
Boolean
ConsoleKeylnfo
Decimal
Int16
IntPtr
RuntimeArgumentFlandle
RuntimeTypeHandle
TimeSpan
Ulnt16
UIntPtr
System .
21. System
_AppDomain
lCloneable
IConvertible
IEquatable<T>
IObservable<T>
lappDomainSetup
IComparable
ICustomFormatter
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>
CrossAppDomainDelegate
Func<...> ( )
UnhandledExceptionEventHandler
System .
ActivationContext.contextForm
Base64Formatting0ptions
ConsoleModifiers
DayOfWeek
EnvironmentVariableTarget
GenericUriParserOptions
PlatformID
TypeCode
UriHostNameType
UriPartial
AppDomainManagerlnitializationOptions
ConsoleColor
ConsoleSpecialKey
Environment.SpecialFolder
GCCollectionMode
LoaderOptimization
StringComparison
UriComponents
UrildnScope
AttributeTargets
ConsoleKey
DateTimeKind
Environment.SpecialFolderOption
GCNotificationStatus
MidpointRounding
StringSplitOptions
UriFormat
UriKind
, System
,
. , System,
Nullable<T>, Type, Exception Attribute, I
II. , System.String,
string #,
22.
,
C# .
Math
Math ,
, , .
Math , , , ,
static, Math , Math
. , Math,
. 21.1, .
Math :
public const double
public const double PI
E ,
; a PI .
722 II. C#
21.1. , Math
value
value
value
value
value
value
value
d. d
-1 1
d. d
-1 1
d
/
*b
long,
,
. , 1,02,
Ceiling() 2,0.
-1,02, Ceiling()
-1
,
d. , d 1,02, Ceiling()
2,0. d -1,02,
Ceiling() -1
d
d
21. System
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
/
d
newBase d
10 d
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
724 II. C#
. 21.1
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
val1 val2
,
(xy)
,
d,
value,
,
digits
d, ,
digits
value,
,
mode
d,
,
mode
value,
,
digits, mode
21. System
725
. 21.1
d, ,
digits, mode
public static int
-1, value ;
Sign(double value)
0, value ; 1,
value
public static int Sign (float -1, value ;
value)
0, value ; 1,
value
public static int
-1, value ;
Sign(decimal value)
0, value ; 1,
value
public static int Sign(int
-1, value ;
value)
0, value ; 1,
value
public static int Sign(short -1, value ;
value)
0, value ; 1,
value
public static int Sign (long -1, value ;
value)
0, value ; 1,
value
public static int Sign(sbyte -1, value ;
value)
0, value ; 1,
value
public static double
Sin(double a)
public static double
value
Sinh(double value)
public static double
d
Sqrt(double d)
public static double
Tan(double a)
public static double
Tanh(double value)
value
public static double
d
Truncate(double d)
public static decimal
d
Truncate(decimal d)
Sqrt()
.
726 II. C#
// .
using System;
class Pythagorean {
static void Main() {
double s1;
double s2;
double hypot;
string str;
Console.WriteLine(" : ");
str = Console.ReadLine();
s1 = Double.Parse(str);
Console.WriteLine(" : ");
str = Console.ReadLine();
s2 = Double.Parse(str);
hypot = Math.Sqrt(s1*s1 + s2*s2);
Console.WriteLine(" " + hypot);
}
}
.
: 3
: 4
: 5
, Pow()
,
, .
.
=
/ (1 + )
Pow() double,
double.
decimal.
/* ,
,
. */
using System;
class InitialInvestment {
static void Main() {
decimal initInvest; //
decimal futVal;
//
double numYears;
double intRate;
//
//
21. System
727
string str;
Console.Write(" : ");
str = Console.ReadLine();
try {
futVal = Decimal.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
}
Console.Write(" (, 0.085): ");
str = Console.ReadLine();
try {
intRate = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
}
Console.Write(" : ");
str = Console.ReadLine();
try {
numYears = Double.Parse(str);
} catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
}
initInvest =
futVal / (decimal) Math.Pow(intRate+1.0, numYears);
Console.WriteLine(" : {0:C}",
initInvest);
}
}
.
: 10000
(, 0.085): 0.07
: 10
: $5,083.49
.NET,
, C# ,
14, ,
, .
.NET .
.NET ,
#, .
728 II. C#
.NET
System.Boolean
System.Char
System.Decimal
System.Double
System.Single
System.Int16
System.Int32
System.Int64
System.UInt16
System.UInt32
System.UInt64
System.Byte
System.Sbyte
C#
bool
char
decimal
double
float
short
int
long
ushort
uint
ulong
byte
sbyte
, ,
.
.
, , C#
, IFormatProvider NumberStyles.
IFormatProvider , NumberStyles
System.Globalization.
22.
.
Byte
Int32
SByte
UInt32
Int16
Int64
Uint16
UInt64
.
Int32.
, ,
.
,
const.
. 21.2
MaxValue
MinValue
,
.
:
IComparable,
IComparable<T>,
IConvertible,
IFormattable
21. System
729
IEquatable<T>,
. , Int32 int.
21.2. , Int32
public int
CompareTo(object value)
value. ,
; ,
; , ,
,
value. ,
; ,
; , ,
,
true,
obj
true,
obj
-
TypeCode
. , Int32
TypeCode.Int32
,
s.
,
,
,
s,
,
provider.
,
,
,
s,
, styles.
,
,
730 II. C#
. 21.2
,
s, ,
styles,
,
provider.
,
,
, ,
format
,
provider
, ,
format,
,
provider
, s,
.
result
true,
false, Parse(),
, s,
,
styles,
,
provider.
result
true,
false,
Parse(),
: Double
Single. Single float.
. 21.3, . 21.4. Double double.
21. System
731
. 21.5, . 21.6.
, Parse() ToString()
,
, .
21.3. , Single
public int
CompareTo(object value)
public int
CompareTo(float value)
value. ,
; ,
, , ,
,
value. ,
; ,
, , ,
,
true,
obj
true,
obj
-
TypeCode
Single, .. TypeCode.Single
true,
f .
false
true, f
.
false
true,
f .
false
true, f
.
false
,
s.
float,
,
s,
,
provider.
float,
732 II. C#
. 21.3
,
s,
, styles.
float,
,
s,
,
provider,
, styles.
float,
, ,
format
,
provider
, ,
format,
,
provider
,
s, float.
result
true,
false, Parse(),
, s,
float, ,
format,
,
provider,
, ,
styles.
result
true,
false, Parse(),
,
float
,
float
,
,
,
21.5. , Double
value. ,
; ,
,
, , ,
value. ,
; ,
,
, , ,
true,
obj
true,
obj
-
TypeCode
Double, .. TypeCode.Double
true,
d .
false
true,
d .
false
true,
d .
false
734 II. C#
. 21.5
true,
d .
false
,
s.
double,
,
s,
,
provider.
double,
,
s,
, styles.
double,
,
s,
,
provider,
,
styles.
double,
,
, format
,
provider
, ,
format,
,
provider
,
s, double.
result
true,
false, Parse(),
, s,
double,
, format,
,
provider, ,
styles.
result true,
false,
Parse(),
21.6. , Double
,
double
,
double
,
,
,
Decimal
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 lo, int mid, int hi, bool IsNegative, byte scale)
. 96-
, , .
, 96- 32-
lo, mid hi;
IsNegative, false
, true
; scale,
0 28. 10 (.. 10scale),
.
Decimal
, ,
.
public Decimal(int[] bits)
int bits 96-
; 31- bits[3] (0
, 1 ); 16-23
.
Decimal : IComparable,
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. , Decimal
d1 + d2
,
decimal
d. , d 1,02, Ceiling()
2,0. d -1,02,
Ceiling() -1
public static int
d1
Compare(decimal d1, decimal d2) d2. ,
; , d1
d2; , , ,
d1 d2
public int CompareTo(object
value)
value. ,
;
,
; , , ,
public int CompareTo(decimal
value)
value. ,
;
,
; , , ,
public static decimal
d1 / d2
Divide(decimal d1,
decimal d2)
public bool Equals(decimal
value)
public override bool
Equals(object value)
public static bool
Equals(decimal d1, decimal d2)
public static decimal
Floor (decimal d)
true,
value
true,
value
true,
d1 d2
,
decimal
d , d 1,02, Floor()
1,0. d -1,02,
Floor() -2
, OLE
Automation,
738 II. C#
. 21.7
d int.
-
TypeCode Decimal, ..
TypeCode.Decimal
d1 * d2
21. System
739
. 21.7
d,
,
mode.
, d
d,
,
decimals,
0 28, mode
.
,
d
d1 - d2
value
byte. .
value
byte,
OverflowException
d double.
,
double ,
decimal
d short.
. d
short,
OverflowException
d int.
. d
int,
OverflowException
d long.
. d
long,
OverflowException
value
,
OLE Automation,
740
II. C#
. 21.7
public string
ToString(IFormatProvider
provider)
value
sbyte. .
value
sbyte,
OverflowException
d float.
. d
float,
OverflowException
,
,
format
,
provider
,
,
format, ,
provider
value
ushort. .
value
ushort,
OverflowException
d uint.
. d
uint,
OverflowException
d ulong.
. d
ulong,
OverflowException
d.
21. System
741
. 21.7
,
s, decimal.
result
true.
false,
Parse(),
,
s, decimal,
,
format, ,
provider,
,
styles.
result
true.
false,
Parse(),
21.8. , Decimal
,
decimal
-1 decimal
,
decimal
1 decimal
0 decimal
Char
Char char ,
,
. ,
, ToUpper(),
IsDigit() , .
742 II. C#
, Char, . 21.9. ,
, , , ConvertFromUtf32()
ConvertToUtf32(), UTF-16
UTF-32. 16 ,
char.
, 16 .
,
(UTF). , UTF-16
16- ,
16- .
16- ,
char. ,
. UTF-32
32- . Char
UTF-16 UTF-32 .
Char :
ToUpper() ToLower()
( ),
.
, CultureInfo
. CultureInfo System.
Globalization,
CultureInfo.CurrentCulture .
Char .
public const char MaxValue
public const char MinValue
, Char : IComparable,
IComparable<char>, IConvertible IEquatable<char>.
21.9. , Char
value. ,
; ,
; , , ,
value. ,
; ,
; , , ,
,
utf32 UTF-32,
UTF-16
21. System
743
. 21.9
,
highSurrogate
lowSurrogate UTF-16,
UTF-32
UTF-16,
s[index], UTF-32
true,
obj
true,
obj
-
,
.
-1
,
s[index],
.
-1
TypeCode
Char, .. TypeCode.Char
UnicodeCategory .
UnicodeCategory
System.Globalization
UnicodeCategory ,
s[index].
UnicodeCategory
System.Globalization
true,
,
false
true,
, s[index],
,
false
true,
,
false
744
II. C#
. 21.9
true,
, s[index],
,
false
true,
UTF-32,
false
true,
,
s[index],
UTF-32,
false
true,
,
false
true,
, s[index],
,
false
true,
,
false
true,
, s[index],
,
false
true,
,
false
true,
, s[index],
,
false
true,
UTF-32,
false
true,
,
s[index],
UTF-32,
false
true,
(
),
false
21. System
745
. 21.9
true,
, s[index],
( ),
false
true,
,
false
true,
, s[index],
,
false
true,
,
false
true,
, s[index],
,
false
true,
,
false
true,
highSurrogate
lowSurrogate
true,
,
,
false
true,
, s[index],
,
,
false
true,
,
false
true,
, s[index],
,
false
746
II. C#
. 21.9
true,
,
,
false
true,
,
s[index], ,
,
false
char
s. s
,
FormatException
,
.
,
.
.
,
culture, CultureInfo
,
System.Globalization
Char
Char
,
provider
,
.
,
.
.
,
culture, CultureInfo ,
System.
Globalization
21. System
747
. 21.9
s
char.
result
true. s
,
false,
Parse(),
,
, 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#
Console.WriteLine(" : " + str);
// .
string newstr = "";
for(i=0; i < str.Length; i++)
newstr += Char.ToUpper(str[i], CultureInfo.CurrentCulture);
Console.WriteLine(" : " + newstr);
}
}
.
.
$
2
3
: . $23
: . $23
Boolean
Boolean bool. ,
, . 21.10. ,
.
public static readonly string FalseString
public static readonly string TrueString
true false
. , FalseString
WriteLine(), "False".
Boolean : IComparable,
IComparable<bool>, IConvertible IEquatable<bool>.
21. System
749
21.10. , Boolean
public int
CompareTo(object obj)
value. ,
;
,
false, value
true; , , ,
true,
value false
obj. ,
;
,
false, obj
true; , , ,
true,
obj false
true,
obj
true,
obj
-
TypeCode
Boolean, .. TypeCode.Boolean
bool
s. s Boolean.
TrueString, Boolean.FalseString,
FormatException,
,
:
,
TrueString, FalseString
,
TrueString, FalseString.
provider
s bool.
result
true. s Boolean.
TrueString, Boolean.FalseString,
false,
, :
, Parse(),
750 II. C#
Array
Array
System. #. ,
C#
. , Array,
. 21.11, . 21.12.
Array : ICloneable, ICollection,
IEnumerable, IStructuralComparable, IStructuralEquatable, IList.
, ICloneable, System.
Collections, 25.
IComparer
IComparer<T>. IComparer System.
Collections. Compare()
, .
int Compare(object , object )
, ;
, ; , , , .
IComparer<T> System.Collections.
Generic. Compare(), .
int Compare( , )
, ,
, , , , ,
, . IComparer<T>
, .
, ,
.
.
21.11. , Array
21. System
751
. 21.11
public static
ReadOnlyCollection<T>
AsReadOnly<T>(T[] array)
public static int
BinarySearch(Array array,
object value)
, ,
array
value
array.
. ,
. array
value
array.
. ,
. array
value
, array,
,
comparer.
. ,
. array
value
array, ,
comparer.
.
, .
array
value
array. ,
index,
, length.
. ,
. array
752
II. C#
. 21.12
value
array. ,
index,
, length.
. ,
. array
value
array, ,
comparer.
, index,
,
length.
. ,
. array
value
array, ,
comparer.
, index,
,
length.
. ,
. array
array
, null
false
: , .
, ,
,
index, ,
length
.
, ,
".
, , ,
,
,
length,
sourceArray, ,
sourceIndex,
destinationArray, ,
21. System
753
. 21.12
destinationIndex.
,
ConstrainedCopy()
,
.
,
destinationArray
public static []
ConvertAll<TInput,
>(TFrom[] array,
Converter<TOutput, TTo>
converter)
public static void
Copy(Array sourceArray,
Array destinationArray, int
length)
array TInput
TOutput
. .
,
converter
,
length, sourceArray
destinationArray,
.
, ()
" ,
.
,
destinationArray
,
length, sourceArray
destinationArray,
.
, ()
" ,
.
,
destinationArray
,
length, sourceArray,
,
sourceArray[sourceIndex],
destinationArray, ,
destinationArray[desti
nationIndex].
, ()
",
.
,
destinationArray
754
II. C#
. 21.12
,
length, sourceArray,
,
sourceArray[sourceIndex],
destinationArray, ,
destinationArray[desti
nationIndex].
, ()
" ,
.
,
destinationArray
array, ,
array[index].
,
array
array, ,
array[index].
,
array
,
elementType,
length
length1length2.
elementType
length1length2length3.
elementType
,
lengths.
elementType
,
lengths.
elementType
21. System
755
. 21.12
public static T
FindLast<T>(T[] array,
Predicate<T> match)
,
lengths.
elementType.
lowerBounds.
, ,
,
true,
array ,
,
match,
false
array,
,
match,
default()
array,
,
match,
array, ,
match,
-1
array,
, match.
,
array[startIndex].
, ,
, -1
array,
, match.
,
array[startIndex],
, count.
,
, , -1
array,
,
match,
default()
756
II. C#
. 21.12
array, ,
match,
-1
array, ,
match.
,
array[startIndex],
array[0]. ,
, ,
-1
array, ,
v.
,
array[start],
, count.
,
, , -1
,
action, array
.
.
25
-
.
,
0
dimension,
1 ..
long.
,
0 dimension,
1 ..
, .
dimension
21. System
757
. 21.12
public object
GetValue(long[] indices)
,
0 dimension,
1 ..
. dimension
,
0
dimension,
1 ..
index.
index.
[index1, index2].
[index1, index2].
[index1, index2,
index3].
[index1, index2,
index3].
.
indices
.
indices
,
value array.
,
-1. (
,
, 1.)
758
II. C#
. 21.12
,
value array.
,
-1
,
value array.
,
array[startIndex].
-1, . (
,
, 1.)
,
value array.
,
array[startIndex].
-1,
,
value array.
,
array[startIndex],
,
count. -1,
. (
,
, 1.)
,
value array.
,
array[startIndex],
,
count. -1,
,
.
,
value array.
,
-1. (
,
, 1.)
21. System
759
. 21.12
,
value
array. ,
-1
public static int
,
LastlndexOf(Array array,
value array.
object value, int startIndex) ,
array[startIndex],
[0].
-1, . (
,
, 1.)
public static int
,
LastIndexOf<T>(T[] array, T
value array.
value, int startIndex)
, [startIndex],
[0].
-1,
public static int
,
LastIndexOf(Array array,
value array.
object value, int startIndex, ,
int count)
array[startIndex],
,
count. -1,
. (
,
, 1.)
public static int
,
LastIndexOf<T>(T[]array, T
value array.
value, int startIndex, int
,
count)
array[startIndex],
,
count. -1,
public static void
newSize array
Resize<T>(ref T[] array, int
newSize)
public static void
Reverse(Array array)
array
public static void
Reverse(Array array, int
array ,
index, int length)
,
array[index], ,
length
760
II. C#
. 21.12
value
index.
public void SetValue(object
value
value, long index)
index.
public void SetValue(object
value
value, int index1, int index2) [index1,
index2].
public void SetValue(object
value
value, long index1, long index2)
[index1,
index2].
public void SetValue(object
value
value, int index1, int
[index1, index2,
index2, int index3)
index3].
public void SetValue(object
value
value, long index1, long
[index1, index2,
index2, long index3)
index3].
public void SetValue(object
value
value, int[] indices)
.
indices
public void SetValue(object
value
value, long[]indices)
.
indices
public static void
array .
Sort(Array array)
public static void
array .
Sort<T>(T[]array)
public static void
array ,
Sort(Array array, IComparer
,
comparer)
comparer.
public static void
array ,
Sort<T> (T[] array,
,
Comparison<T> comparer)
comparer.
public static void
array ,
Sort<T> (T[] array,
,
IComparer<T> comparer)
comparer.
public static void
Sort(Array keys, Array
. keys
items)
, items ,
. ,
-.
21. System
761
. 21.12
. keys
, items ,
. ,
-.
public static void
Sort(Array keys, Array
, ,
items, Icomparer comparer)
comparer. keys
, items ,
. ,
-.
public static void
Sort<TKey, TValue>(TKey[]
, ,
keys, TValue[] items,
comparer. keys
IComparer<TKey> comparer)
, items ,
. ,
-.
public static void
array
Sort(Array array, int index,
, ,
int length)
array[index],
, length.
public static void
array
Sort<T>(T[] array, int
, ,
index, int length)
array[index],
, length.
public static void Sort(Array array
array, int index, int length, , ,
IComparer comparer)
array[index],
, length,
,
v.
public static void
array
Sort<T>(T[] array, int
, ,
index, int length,
array[index],
Icomparer<T> comparer)
, length,
,
comparer.
762
II. C#
. 21.12
, ,
index,
, length.
keys ,
items ,
. ,
-.
, ,
index,
, length.
keys ,
items ,
. ,
-.
, ,
index,
, length,
,
comparer. keys
, items ,
. ,
".
, ,
index,
, length,
,
comparer. keys
, items ,
. ,
..
21. System
763
. 21.12
true,
array
, match.
,
false
.
Array . ,
Sort()
,
"-".
, BinarySearch().
, Sort()
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 24 -1 0
: -1 0 1 3 4 5 6 8 9 14 17 24
14: 9
764 II. C#
int,
. , Array,
C# .
.
,
IComparable IComparable<T>.
,
. , ,
IComparable IComparable<T>, .
IComparable .
int CompareTo(object obj)
,
obj. ,
obj, ;
, , obj,
.
IComparable<T>
IComparable.
CompareTo().
int CompareTo( other)
CompareTo()
.
, other.
, other, ;
, ,
other, . 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[1]
nums[2]
nums[3]
nums[4]
=
=
=
=
=
new MyClass(5);
new MyClass(2);
new MyClass(3);
new MyClass(4);
new 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#
StringComparer System ,
, IComparer IComparer<T>.
StringComparer
IComparer. , StringComparer
, StringComparer
.
.
StringComparer,
.
,
StringComparer.Ordinal.
string[] strs = { "xyz", "one" , "beta", "Alpha" };
// ...
Array.Sort(strs, StringComparer.Ordinal);
int idx = Array.BinarySearch(strs, "beta", StringComparer.Ordinal);
, ,
, .
Reverse().
.
.
// .
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 obj)
, ,
obj. obj ,
true, false.
Array, : Exists(), Find(),
FindIndex() FindAll().
,
. ,
, .
Exists() Find().
// .
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
Exists() Find()
IsNeg().
IsNeg().
static bool IsNeg(int v) {
Exists() Find()
v. , IsNeg()
v .
Action
Action Array.ForEach()
. Action,
. .
public delegate void Action<T> (T obj)
, ,
obj. Action
Array.ForEach(), obj.
770 II. C#
, Action ForEach(),
.
Action ForEach(). MyClass,
Show() ,
. Neg().
, Show()
. ForEach().
// 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[1]
nums[2]
nums[3]
nums[4]
=
=
=
=
=
new
new
new
new
new
MyClass(5);
MyClass(2);
MyClass(3),
MyClass(4);
MyClass(1);
21. System
771
.
nums: 5 2 3 4 1
nums : -5 -2 -3 -4 -1
BitConverter
. ,
, , .
,
,
. .NET
BitConverter.
BitConverter . ,
. 21.13. , .
public static readonly bool IsLittleEndian
true,
, .
.
, , IsLittleEndian
false. .
Intel Pentium .
21.13. , BitConverter
772 II. C#
. 21.13
value
value double
,
value[startIndex],
bool .
true,
false
,
value[index], char
,
value[startIndex],
double
,
value[startIndex],
short
,
value[startIndex],
int
,
value[startIndex],
long
,
value[startIndex],
float i
value
. ,
value
, value[startIndex].
,
value
, value[startIndex]
,
length. ,
,
value[startIndex],
ushort
,
value[startIndex],
uint
21. System
773
. 21.13
,
value[startIndex],
ulong
Random
Random.
,
.
,
.
Random .
public Random()
public Random(int seed)
Random,
.
seed, .
, Random, . 21.14.
21.14. , Random
,
0 Int32.
MaxValue-1
,
0 maxValue-1
,
minValue
maxValue-1
buffer
.
0 Byte.MaxValue-1
,
, 0,0 1,0
,
, 0,0 1,0.
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
voidAddMemoryPressure(long
bytesAllocated)
public static void
CancelFullGCNotification()
public static void Collect()
public static void Collect(int
generation)
public static void Collect(int
generation, GCCollectionMode
mode)
public static int
CollectionCount(int generation)
public static int
GetGeneration(object obj)
bytesAllocated
,
0
generation
" "
0
generation ,
mode
,
generation
, obj
21. System
775
. 21.15
, " ,
wo. "
( ),
.
forceFullCollection
true,
obj,
.
KeepAlive()
" .
maxGenerationThreshold
,
.
largeObjectHeapThreshold
,
.
1 99
bytesAllocated
,
obj.
SuppressFinalize()
obj
,
.
GCNotificationStatus ,
System
,
,
,
millisecondsTimeout.
GCNotificationStatus ,
System
.
GCNotificationStatus ,
System
public static
GCNotificationStatus
WaitForFullGCComplete()
776
II. C#
. 21.15
public static
GCNotificationStatus
WaitForFullGCComplete(int
milliseconds Timeout)
" ,
millisecondsTimeout.
GCNotif icationStatus
,
System
,
, GC
:
public static int MaxGeneration { get; }
MaxGeneration ,
. .
, .
" ".
GC .
. ,
" " Collect()
. , " " ,
. ,
, ,
. , " "
.
" ".
GC:AddMemoryPressure() RemoveMemoryPressure().
,
. ,
.
,
,
.
AddMemoryPressure(), CLR
.
RemoveMemoryPressure(), CLR
. , ,
, RemoveMemoryPressure()
,
AddMemoryPressure().
21. System
777
object
object # object. Object
11, #,
. 21.16. object
public Object()
.
21.16. , Object
protected Finalize()
true,
,
, obj.
false
true,
obj ,
obj.
false
" ". C# Finalize()
-,
"" .
, ,
true,
obj obj
.
false
,
Tuple
.NET Framework 4.0
( ). Tuple,
Create()
, Tuple<...>,
.
Create(), .
778
II. C#
IComparable IComparable<T>
IComparable
IComparable<T>, ,
, .NET Framework. IComparable
IComparable<T> 18,
,
. , Array
.
, .
IComparable ,
.
int CompareTo(object obj)
,
obj. ,
obj, ;
, , obj,
.
IComparable
.
public interface IComparable<T>
. CompareTo()
, .
int CompareTo( other)
, CompareTo(),
. , IComparable<T>
.
#, IComparable.
IEquatable<T>
IEquatable<T> ,
.
, Equals(), .
21. System
779
IConvertible
IConvertible , String
DateTime. .
, , .
ICloneable
ICloneable,
. ICloneable , Clone(),
.
object Clone()
,
. ,
: . ,
. ,
, .
,
, . ,
, ,
,
, . , Clone()
.
MemberwiseClone(), Object.
,
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 ob1 = new Test(10, 20);
obi.Show("ob1");
Console.WriteLine(" ob2 b1.");
Test ob2 = (Test) ob1.Clone();
ob2.Show("ob2");
Console.WriteLine(" b1.. 99, " +
" b1.b - 88.");
b1.. = 99;
b1.b = 88;
b1.Show("b1");
ob2.Show("b2");
}
}
.
b1: .: 10, b: 20
b2 b1.
b2: .: 10, b: 20
b1.. 99, b1.b 88.
b1: .: 99, b: 88
b2: .: 10, b: 20
, b2
b1, .
.
Test, X .
X ,
X .
21. System
781
MemberwiseClone(),
Object Clone().
Clone() .
// .
public object Clone() {
Test temp = (Test) MemberwiseClone();
return temp;
}
.
b1: .: 10, b: 20
b2 b1.
b2: .: 10, b: 20
b1.. 99, b1.b 88.
b1: .: 99, b: 88
b2: .: 99, b: 20
, b1 b2
X.
. b int ,
.
IFormatProvider IFormattable
IFormatProvider GetFormat(),
,
. GetFormat():
object GetFormat(Type formatType)
formatType , .
IFormattable
. :
string ToString(string format, IFormatProvider formatProvider)
format , a formatProvider
.
22.
IObservable<T> IObserver<T>
.NET Framework 4.0 ,
: IObservable<T> IObserver<T>.
( ) (
782 II. C#
).
. Subscribe(),
IObservable<T>
IObserver<T>, .
.
,
IObserver<T>. , OnNext() ,
OnError() , OnCompleted() ,
.
22
String,
C# string.
,
.
String
, ,
.
.
,
C# ,
, .
C#
7,
.
#,
String.
,
.
, C++,
, C#
string.
, string . ,
string .NET
System.String. , C#
, , ,
String.
784
II. C#
. C#
. ,
.
, ,
, "" , .
" ", ""
. , , , ,
, , .
.
, , C#
StringBuilder, System.Text.
string, StringBuilder.
String
String System.
: IComparable, IComparable<string>, ICloneable, IConvertible,
IEnumerable, IEnumerable<char> IEquatable<string>. , String
, , . String
#. C# string
.NET Framework.
String.
String
String ,
.
.
public String(char[ ] value)
public String(char[ ] value, int startIndex, int length)
,
value. value
(length), ,
startIndex.
,
, , :
public String(char , int count)
; a count .
, ,
.
public String(char* value)
public String(char* value, int startIndex, int length)
22.
785
,
value. , ,
value, , .
,
value, (length), ,
startIndex. ,
.
, ,
.
public String(sbyte* value)
public String(sbyte* value, int startIndex, int length)
public String(sbyte* value, int startIndex, int length, Encoding enc)
, value. ,
, value, .
, value,
(length), ,
startIndex.
. Encoding
System.Text. ,
.
.
, .
string str = " ";
, String
String .
public static readonly string Empty
Empty , .. ,
. String,
.
, String ,
.
public char this[int index] { get; }
.
, , . String
, , String
, .
, String ,
.
public int Length { get; }
Length .
786 II. C#
String
String : == !=. ==
. ==
, ,
. == String,
.
!=. String,
. ,
< >=, String ,
. ,
, Compare(), String.
,
. = = !=.
. ( ,
,
, .. .) ,
.
,
. -
, :
.NET Framework . -,
,
, .
, . -,
, . ,
( ), , ,
.
.
,
, Microsoft.
, , , .
. ,
,
(, ,
). ,
,
22.
787
, , , - ,
, . ,
.
String ,
. 22.1. Compare().
,
, , StringComparison,
,
CultureInfo. Compare(),
StringComparison,
. ,
CultureInfo,
. , ,
CultureInfo ,
StringComparison.
22.1.
strA strB.
, strA strB;
, strA
strB; , strA strB .
strA strB.
, strA strB;
, strA
strB; , strA strB .
ignoreCase true,
.
.
strA strB.
, strA strB;
, strA strB; ,
strA strB . comparisonType
strA strB,
, culture.
, strA
strB; , strA
strB; , strA strB .
ignoreCase
true,
.
. CultureInfo
System.Globalization
788 II. C#
. 22.1
strA strB.
strA[indexA] strB[indexB]
,
length. ,
strA strB;
, strA
strB; , strA strB
.
strA strB.
strA[indexA] strB[indexB]
,
length. ,
strA strB;
, strA
strB; , strA strB
. ignoreCase
true,
.
.
strA strB.
strA[indexA] strB[indexB]
,
length. ,
strA strB;
, strA
strB; , strA strB
. comparisonType
strA strB,
,
culture.
strA[indexA] strB[indexB]
, length.
, strA
strB; ,
strA strB; ,
strA strB .
ignoreCase true,
.
. CultureInfo
System.Globalization
22.
789
. 22.1
strA strB,
,
culture, ,
options.
, strA strB;
, strA strB; ,
strA strB . CultureInfo
CompareOptions
System.Globalization
strA strB,
, culture,
,
options.
strA[indexA] strB[indexB]
, length.
,
strA strB; ,
strA strB; ,
strA strB .
CultureInfo CompareOptions
System.Globalization
strA strB
, .
, strA
strB; , strA
strB; , strA strB
strA strB
, .
strA[indexA] strB[indexB]
,
count. ,
strA strB;
, strA strB; ,
strA strB
value. ,
value;
,
value; ,
strB.
,
strB; ,
strB; ,
public int
CompareTo(object
value)
public int
CompareTo(string
strB)
790 II. C#
. 22.1
true,
,
obj.
,
true,
,
value.
,
true,
,
value. comparisonType
true,
, b.
,
true,
, b.
comparisonType
public bool
Equals(string value)
public bool
Equals(string value,
StringComparison
comparisonType)
public static bool
Equals(string a,
string b)
public static bpol
Equals(string a,
string b,
StringComparison
comparisonType)
StringComparison ,
, . 22.2. ,
, .
, StringComparison
Compare() , , Equals().
.
.
, , StringComparison
, .
22.2. , StringComparison
CurrentCulture
CurrentCultureIgnoreCase
InvariantCulture
,
, ..
22.
791
. 22.2
InvariantCultureIngoreCase
Ordinal
OrdinalIgnoreCase
, ..
.
,
,
,
,
.
, ,
,
Compare() ,
; ,
; , ,
. Compare() ,
, , ,
Equals() = =. , Compare()
. ,
,
, .
Equals(),
. ,
,
, = =.
Compare(),
CompareOrdinal().
, , CompareTo()
.
,
.
Compare(),
Equals(), CompareOrdinal(), = = !=
. ,
.
// .
using System;
class CompareDemo {
static void Main() {
string str1 = "alpha";
string str2 = "Alpha";
792
II. C#
string str3 = "Beta";
string str4 = "alpha";
string str5 = "alpha, beta";
int result;
//
// .
result = String.Compare(str1, str2, StringComparison.CurrentCulture)
Console.Write(" : ");
if(result < 0)
Console.WriteLine(str1 + " " + str2);
else if(result > 0)
Console.WriteLine(str1 + " " + str2);
else
Console.WriteLine(str1 + " " + str2);
result = String.Compare(str1, str2, StringComparison.Ordinal);
Console.Write(" : ");
if(result < 0)
Console.WriteLine(str1 + " " + str2);
else if(result > 0)
Console.WriteLine(str1 + " " + str2);
else
Console.WriteLine(str1 + " " + str4);
// CompareOrdinal().
result = String.CompareOrdinal(str1, str2);
Console.Write(" CompareOrdinal():\n");
if(result < 0)
Console.WriteLine(str1 + " " + str2);
else if(result > 0)
Console.WriteLine(str1 + " " + str2);
else
Console.WriteLine(str1 + " " + str4);
Console.WriteLine();
// = = .
// .
if(str1 == str4) Console.WriteLine(str1 + " == " + str4);
// !=.
if(str1 != str3) Console.WriteLine(str1 + " != " + str3);
if(str1 != str2) Console.WriteLine(str1 + " != " + str2);
Console.WriteLine();
// ,
// Equals().
if(String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
Console.WriteLine(" Equals() " +
" OrdinalIgnoreCase:\n" +
str1 + " " + str2);
22.
793
Console.WriteLine ();
// .
if(String.Compare(str2, 0, str5, 0, 3,
StringComparison.CurrentCulture) > 0) {
Console.WriteLine(" :" +
"\n3 " + str2 +
" , 3 " + str5);
}
}
}
.
: alpha Alpha
: alpha Alpha
CompareOrdinal():
alpha Alpha
alpha == alpha
alpha != Beta
alpha != Alpha
Equals() OrdinalIgnoreCase:
alpha Alpha
:
3 Alpha , 3 alpha, beta
, .. , . -,
+, 7. -,
, String. ,
+,
.
, , Concat().
.
public static string Concat(string str0, string str1)
, str1,
str0. Concat(),
.
public static string Concat(string str0, string str1,string str2)
Concat() ,
str0, str1 str2.
Concat(), .
public static string Concat(string str0, string str1, string str2, string str3)
Concat() ,
.
794 II. C#
Concat()
:
public static string Concat(params string[] values)
values ,
. Concat()
, ?
.
,
.
Concat() .
// Concat().
using System;
class ConcatDemo {
static void Main() {
string result = String.Concat(" ", " ", " ",
" ", " ",
" ", "String." );
Console.WriteLine(": " + result);
}
}
.
: String.
, Concat(),
, .
Concat() ,
, . (
ToString(),
.) Concat().
public static stringConcat(object arg0)
public static stringConcat(object arg0, object arg1)
public static stringConcat(object arg0, object arg1, object arg2)
public static stringConcat(object arg0, object arg1, object arg2, object arg3)
22.
795
796 II. C#
4.0 .NET Framework Concat(),
.
public static string Concat<T>(IEnumerable<T> values)
public static string Concat(IEnumerable<string> values)
,
, ,
values ,
IEnumerable<T>. ,
values. (, , ,
,
StringBuilder.)
String .
, , , ,
. , , ,
.
IndexOf(). .
.
public int IndexOf(char value)
IndexOf() value
. value , -1.
.
, .
IndexOf(),
.
public int IndexOf(String value)
public int IndexOf(String value, StringComparison comparisonType)
,
value, .
StringComparison,
. ,
-1.
LastIndexOf().
.
.
public int LastlndexOf(char value)
LastIndexOf() ,
value
-1, .
LastIndexOf(),
.
22.
797
798
II. C#
string str = "C# .";
int idx;
Console.WriteLine(" str: " + str);
idx = str.IndexOf('');
Console.WriteLine(" 'o': " + idx);
idx = str.LastIndexOf('');
Console.WriteLine(" 'o': " + idx);
idx = str.IndexOf("", StringComparison.Ordinal);
Console.WriteLine(" \"\": " + idx);
idx = str.LastlndexOf("", StringComparison.Ordinal);
Console.WriteLine(" \"\": " + idx);
if(str.EndsWith(".", StringComparison.Ordinal))
Console.WriteLine(" str \".\"");
}
}
.
str: C# .
'': 3
'': 49
"": 22
"": 33
'', '' '': 4
str "C# "
str "."
Contains().
.
public bool Contains(string value)
Contains() true,
, value,
false.
. , ,
.
Contains().
// Contains().
using System;
22.
799
class ContainsDemo {
static void Main() {
string str = "C# .";
if(str.Contains(""))
Console.WriteLine(" \"\".");
if(str.Contains(""))
Console.WriteLine(" \"\".");
if(!str.Contains(""))
Console.WriteLine(" \"!" .");
}
}
.
"".
"".
"" .
,
Contains()
, .
"", "".
"", .
,
. . 22.3 ,
String.
22.3. , String
true,
value. value
,
false
true,
value.
false
true,
value.
false.
comparisonType
true,
value,
800 II. C#
. 22.3
false.
ignoreCase
true,
.
.
,
culture
value .
,
-1
value .
,
-1
value .
,
startIndex.
-1,
value .
,
startIndex.
-1,
value .
,
startIndex,
,
count. -1,
value .
,
startIndex,
,
count. -1,
value .
22.
801
. 22.3
comparisonType
.
-1,
public int IndexOf(string value,
int startIndex, StringComparison
value .
comparisonType)
,
startIndex.
comparisonType
.
-1,
public int IndexOf(string value,
int startIndex, int count,
value .
StringComparison comparisonType)
,
startIndex,
,
count. comparisonType
. -1,
public int LastlndexOf(char value)
value .
,
-1
public int IndexOfAny(char[] anyOf)
anyOf,
.
-1,
anyOf.
public int IndexOfAny(char[] anyOf,
int startIndex)
anyOf,
.
,
startIndex
-1,
anyOf.
public int IndexOfAny(char[] anyOf,
int startIndex, int count)
anyOf,
.
,
startIndex,
802
II. C#
. 22.3
count. -1,
anyOf.
public int LastIndexOf(string value)
value .
,
-1
public int LastIndexOf(char value,
int startIndex)
value .
,
,
startIndex,
.
-1,
public int LastIndexOf(string value,
int startIndex)
value
.
, ,
startIndex,
.
-1,
public int LastIndexOf(char value,
int startIndex, int count)
value
.
, ,
startIndex,
,
count. -1,
public int LastIndexOf(string value,
int startIndex, int count)
value
.
, ,
startIndex,
,
count. -1,
public int LastIndexOf(string value,
StringComparison comparisonType)
value .
comparisonType
.
-1,
22.
803
. 22.3
value
.
, ,
startIndex,
.
comparisonType
.
-1,
value
.
, ,
startIndex,
,
count. comparisonType
. -1,
anyOf,
.
-1,
anyOf.
anyOf,
.
, startIndex,
. -1,
anyOf.
anyOf,
.
,
,
startIndex,
, count,
,
count. -1,
804
II. C#
. 22.3
anyOf.
true,
value.
false
true,
value.
false.
comparisonType
true,
value.
false.
ignoreCase
true,
.
.
,
culture
.
,
. String
Split(), Join().
Split().
, , C# 1.0.
public string[ ] Split(params char[ ] separator)
public string[ ] Split(params char[ ] separator, int count)
Split()
. , ,
. , ,
separator. separator ,
.
, count.
Join(). ,
, 2.0 .NET Framework.
22.
805
:
| | | | | |
"" "".
, "" ,
", ". .
( )
.
806
II. C#
Split(),
StringSplitOptions. ,
. Split().
public string[] Split(params char[] separator,StringSplitOptions options)
public string[] Split(string[] separator, StringSplitOptions options)
public string[] Split(params char[] separator, int count,
StringSplitOptions options)
public string[] Split(string[] separator, int count,
StringSplitOptions options)
Split()
, ,
. , , separator.
separator , .
,
count. options
, ,
. StringSplitOptions
: None RemoveEmptyEntries. options
None,
, . options
RemoveEmptyEntries,
.
,
string[] parts = str.Split(seps);
.
string[] parts = str.Split(seps, StringSplitOptions.RemoveEmptyEntries);
.
:
:
| | | | |
, , - , ""
, .
,
, . ,
Split() " 100"
, "" "100".
, "" (
), "".
22.
807
, ,
, 10 + 5, ,
.
// .
using System;
class TokenizeDemo {
static void Main() {
string[] input = {
"100 + 19",
"100 / 3,3",
"-3 * 9",
"100 - 87"
};
char[] seps = {' '};
for(int i=0; i < input.Length; i++) {
//
string[] parts = input[i].Split(seps);
Console.Write(": ");
for(int j=0; j < parts.Length; j++)
Console.Write(parts[j] + " ");
Console.Write(", : ");
double n = Double.Parse(parts[0]);
double n2 = Double.Parse(parts[2]);
switch(parts[1]) {
case "+":
Console.WriteLine(n
break;
case
Console.WriteLine(n
break;
case "*":
Console.WriteLine(n
break;
case "/":
Console.WriteLine(n
break;
}
+ n2);
- n2);
* n2);
/ n2);
}
}
}
.
:
:
:
:
100 + 19 , : 119
100 / 3,3 , : 30,3030303030303
-3 * 9 , : -27
100 - 87 , : 13
808
II. C#
.
. ,
"print",
.
. , ,
. ,
,
, .
C# .
Trim().
public string Trim()
public string Trim(params char[] trimChars)
Trim()
.
trimChars.
.
.
PadLeft().
public string PadLeft(int totalWidth)
public string PadLeft(int totalWidth, char paddingChar)
PadLeft()
, totalWidth.
, paddingChar,
,
totalWidth.
. totalWidth ,
.
PadRight().
public string PadRight(int totalWidth)
public string PadRight(int totalWidth, char paddingChar)
PadLeft()
, totalWidth.
22.
809
, paddingChar,
,
totalWidth. B
. totalWidth ,
.
.
// .
using System;
class TrimPadDemo {
static void Main() {
string str = "";
Console.WriteLine(" : " + str);
// .
str = str.PadLeft(10);
Console.WriteLine (" | " + str + "|");
// ,
str = str.PadRight(20);
Console.WriteLine("|" + str + "|");
// .
str = str.Trim();
Console.WriteLine("|" + str + "|");
// # .
str = str.PadLeft(10,'#');
Console.WriteLine("|" + str + "|");
// # .
str = str.PadRight(20, '#');
Console.WriteLine("|" + str + "|");
// #.
str = str.Trim('#');
Console.WriteLine("|" + str + "|");
}
}
.
:
|
|
|
|
||
|######|
|################|
||
810
II. C#
,
Insert():
public string Insert(int startIndex, string value)
value ,
startIndex. .
Remove(). .
public string Remove(int startIndex)
public string Remove(int startIndex, int count)
Remove() , ,
startIndex, .
,
count, , startIndex.
.
Replace(). .
public string Replace(char oldChar, char newChar)
public string Replace(string oldValue, string newValue)
Replace() oldChar
newChar.
oldValue newValue.
.
Insert(),
Remove() Replace().
// , .
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 ,
, ToUpper() ToLower().
.
public string ToLower()
public string ToUpper()
ToLower() ,
ToUpper() .
. ,
.
public string ToLower(CultureInfo culture)
public string ToUpper(CultureInfo culture)
.
.
, T o U p p e r I n v a r i a n t ( )
ToLowerInvariant().
public string ToUpperlnvariant()
public string ToLowerlnvariant()
ToUpper() ToLower(), ,
.
Substring()
Substring().
.
public string Substring(int startIndex)
public string Substring(int startIndex, int length)
Substring() , ,
startIndex, .
,
, length, ,
startIndex. .
Substring().
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
String
, String
IEnumerable<T>. , , C# 3.0,
String , Enumerable
Queryable, System.Linq.
LINQ,
, .
. 19.
C# , int double,
,
. C#
, ,
. , I ,
.
C# ,
Console.WriteLine(), String.Format() ToString().
. ,
.
:
.
22.
813
. ,
,
. ,
(.. ) .
,
. ,
, .
C#
. ,
.
IFormatProvider, GetFormat().
.NET Framework
. ,
, ,
.
,
, .
3,
.
Console.WriteLine(),
, .
WriteLine().
WriteLine(" ", arg0, arg1, ... , argN);
WriteLine() , +.
:
, , .
:
{argnum, width: fmt}
argnum , ; width
, a fmt . width fmt
.
. ,
{0} arg0, {1} arg1 ..
,
, argnum. ,
,
.
.
fmt,
. ,
. width,
. width
, .
.
814
II. C#
,
. 22.4. ,
. ,
, F2.
22.4.
,
(
)
.
, D
( .
)
( .
)
, F
. F
: F
. f
: f
(
)
, N
,
,
Parse()
. (
"" )
(
A-F)
.
(
A-F)
.
F
f
G
g
N
R r
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#
WriteLine(). ,
, .
.
using System;
class FormatDemo2 {
static void Main() {
// .
Console.WriteLine("{0:F2} {0:F3} {0:}", 10.12345);
// .
Console.WriteLine("{2:d} {0:d} {l:d}", 1, 2, 3);
}
}
.
10.12 10.123 1.012345+001
3 1 2
WriteLine() 10.12345
. ,
.
WriteLine() .
, - ,
, .
.
String.Format()
ToString()
WriteLine(), ,
, .
,
.
, Windows, -
, -.
,
.
String.Format(),
ToString(), # .
.
String.Format()
Format(),
String, .
22.
817
arg0
,
format. format,
public static string
arg0
Format(string format,
,
object arg0, object arg1) format, arg1
. format,
public static string
arg0, arg1 arg2
Format(string format,
,
object arg0, object arg1, format. format,
object arg2)
public static string
, args,
Format(string format,
,
params object[] args)
format.
format,
public static string
, args,
Format(IFormatProvider
,
provider, string format,
format,
params object[] args)
provider. format,
,
String.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}", x);
Console.WriteLine(str);
str = String.Format("{0:C}", 189.99);
Console.WriteLine(str);
}
}
WriteLine(), String.Format()
,
.
,
1 10.
// Format().
using System;
class FormatDemo2 {
static void Main() {
int i;
int sum = 0;
int prod = 1;
string str;
/*
1 10. */
for(i=1; 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);
Format()
: ( sum),
( prod). ,
, WriteLine(),
Format() , , , ": ".
.
ToString()
, ,
Int32 Double, ToString().
ToString().
public string ToString(" ")
ToString()
, "
", . ,
188.99
.
string str = 189.99.ToString("");
,
ToString() . ,
WriteLine() Format(),
, ToString()
.
,
ToString()
. , .
// ToString() .
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 = v2.ToString("p");
Console.WriteLine(str);
str = x.ToString("X");
Console.WriteLine(str);
str = x.ToString("D12");
Console.WriteLine(str);
str = 189.99.ToString("C");
Console.WriteLine(str);
}
}
, C# ,
.. , , ,
. ,
,
(.. ) . I
, .
-
,
( ) , .
, . 22.6.
.
.
- # , .
.
, #,
.
22.
821
. #
,
.
.
, #,
,
. #
. , ,
, . ,
, , #.##,
, .
- 0.
22.6. -
-
#
.
, ,
,
%
0
;
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 \n.
-
.
, .
.
. ,
"". ,
"". ,
+ +.
, , - -.
; ,
.
, ;.
_; _; _
.
Console.WriteLine("{0:#.##; (#.##);0.00}", num);
num ,
. num ,
,
. num ,
0.00. ,
. ,
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%
,
: DateTime. , .
.
.
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
m
O
o
R
r
S
,
, M
, . ,
O,
.
, O
, R
22.
825
. 22.7
;
(UTC)
, Y
U
u
Y
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(" T: {0:T}", dt);
Console.WriteLine(" f: {0:f}", dt);
Console.WriteLine(" F: {0:F}", dt);
Console.WriteLine(" g: {0:g}", dt);
Console.WriteLine(" G: {0:G}", dt);
Console.WriteLine(" m: {0:m}", dt);
Console.WriteLine(" M: {0:M}", dt);
Console.WriteLine(" : (0:o)", dt);
Console.WriteLine(" O: (0:O}", 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:}", dt);
Console.WriteLine("Y format: {0:Y}", dt);
}
}
, , ,
.
826
II. C#
d:
D:
t:
T:
f:
F:
g:
G:
m:
M:
:
:
r:
R:
s:
u:
U:
:
Y:
2/11/2010
Thursday, February 11, 2010
11:21 AM
11:21:23 AM
Thursday, February 11, 2010 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-11T11:21:23
2010-02-11 11:21:23Z
Thursday, February 11, 2010 5:21:23 PM
February, 2010
February, 2010
.
, .
ToString() 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 = dt.ToString("T");
if(dt.Minute==0 && dt.Second==0)
t = t + "\a"; //
Console.WriteLine(t);
}
}
}
}
22.
827
,
.
. , (.. ) ,
.
-, . 22.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)
DateTime.Kind. (
Z.)
. 1 9
1 12
1 12.
1 9
. 1 9
" , .. ( )
P.M. ( )
ddd
dddd
f, ff, fff, ffff,
fffff, ffffff, fffffff
g
h
hh
H
HH
m
mm
M
MM
MMMM
s
ss
t
828
II. C#
. 22.8
tt
A.M. P.M.
,
. 1
9
.
1 9
,
fmt
z
zz
zzz
:
/
%fmt
. 22.8, , - d, f, g, m, 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
TimeSpan , .
TimeSpan ,
DateTime .
TimeSpan ,
.
TimeSpan
: , g G.
,
( ). ,
TimeSpan ,
. 22.9. ,
, %.
22.9. -
-
. -
d, , ,
,
( , ).
hh,
,
( , ).
mm,
,
( , ).
ss,
,
. -
f ,
. -
F ,
h, hh
m, mm
s, ss
830
II. C#
TimeSpan ,
1000 for.
// TimeSpan.
using System;
class TimeSpanDemo {
static void Main() {
DateTime start = DateTime.Now;
//
for(int i = 1; i <=
Console.Write(i +
if((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
d
F
f
G
g
X
, D
.
,
,
, , Flags
, F
.
Flags,
, , ,
, G
.
( )
, X
.
// .
using System;
class EnumFmtDemo {
enum Direction { North, South, East, West }
[Flags] enum Status { Ready=0x1, OffLine=0x2,
Waiting=0x4, TransmitOK=0x8,
ReceiveOK=0x10, 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
23
.
:
#
.
, .
. ,
.
,
#, , .NET
Framework. C#
,
. , C#
.
4.0 .NET Framework
,
. TPL
(Task Parallel Library
), PLINQ (Parallel LINQ
).
,
()
. , TPL
.
,
834
II. C#
TPL,
.
- . -,
,
.
, , . -,
, TPL, -
, . -,
TPL , ,
- ,
. TPL
, .
, ,
,
.
. ,
.
:
. .
.
,
. ,
,
.
,
.
.
" ".
, . ,
. ,
, ,
.
:
,
.
,
,
,
. , -,
, , ,
, ().
23. . :
835
- .
-
. ,
,
, ,
.
. ,
; ,
; , :. ;
; ;
, .
.NET Framework :
.
, .
, ,
.
,
.
C# ,
.
,
, . ,
.
.
C# .NET Framework
: . C#
, , .
,
,
. C#
, ,
C#
.
, ,
System.Threading. C#
.
using System.Threading;
Thread
Thread,
. Thread , ..
. Thread ,
.
.
836
II. C#
Thread,
.. , System.Threading.
Thread:
public Thread(ThreadStart )
, ,
a ThreadStart , .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 Run() {
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 _)
_ ,
. _
, ,
, .
Main() Thread
.
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(mt.Run);
// , .
newThrd.Start();
,
MyThread.
Thread,
mt.Run(). , Start().
838 II. C#
mt.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
=
=
=
=
=
=
=
=
=
=
0
1
2
3
4
5
6
7
8
9
,
, .
, .
, ,
.
, .
. Count
do-while Main(),
10, Sleep().
,
.
,
, . -,
, .
Thread MyThread.
-, MyThread ,
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 Run() {
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + Thrd.Name + ", Count = " + Count);
Count++;
} while(Count < 10);
Console.WriteLine(Thrd.Name + " .");
}
}
class MultiThreadImproved {
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 Run() {
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 mt1 = new MyThread(" #1");
MyThread mt2 = new MyThread(" #2");
MyThread mt3 = new MyThread(" #3");
do {
Console.Write(".");
Thread.Sleep(100);
} while(mt1.Count < 10 ||
mt2.Count < 10 ||
mt3.Count < 10);
Console.WriteLine(" .");
}
}
.
. #1 .
#2 .
#3 .
.... #1, Count = 0
#2, Count = 0
#3, Count = 0
23. . :
..... #1, Count
#2,Count = 1
#3,Count = 1
..... #1, Count
#2, Count = 2
#3, Count = 2
..... #1, Count
#2, Count = 3
#3, Count = 3
..... #1, Count
#2, Count = 4
#3, Count = 4
..... #1, Count
#2, Count = 5
#3, Count = 5
..... #1, Count
#2, Count = 6
#3, Count = 6
..... #1, Count
#2, Count = 7
#3, Count = 7
..... #1, Count
#2, Count = 8
#3, Count = 8
..... #1, Count
#1 .
#2, Count = 9
#2 .
#3, Count = 9
#3 .
.
841
= 1
= 2
= 3
= 4
= 5
= 6
= 7
= 8
= 9
, ,
.
, ,
.
, .
Count.
. ,
Thread
. , ,
IsAlive, .
public bool IsAlive { get; }
IsAlive true, ,
, - . "" IsAlive
MoreThread
, .
842
II. C#
// IsAlive .
class MoreThreads {
static void Main() {
Console.WriteLine(" .");
// .
MyThread mt1 = new MyThread(" #1");
MyThread mt2 = new MyThread(" #2");
MyThread mt3 = new MyThread(" #3");
do {
Console.Write(".");
Thread.Sleep(100);
} while(mt1.Thrd.IsAlive &&
mt2.Thrd.IsAlive &&
mt3.Thrd.IsAlive);
Console.WriteLine(" .");
}
}
,
. ,
IsAlive .
Join(). .
public void Join()
Join() , , ,
. ,
. ,
ThreadStateException. Join()
,
.
Join() ,
.
// 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 Run() {
23. . :
843
=
=
=
=
=
=
=
=
=
=
=
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
ParameterizedThreadStart, ThreadStart, ,
. ParameterizedThreadStart
, .
public delegate void ParameterizedThreadStart(object obj)
, object.
Thread ,
, object.
.
// .
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'| mt2.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().
IsBackground
, .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
ThreadPriority.
Normal.
,
, :
. MyThread.
Run() ,
. , 1000000000
stop true.
stop false. ,
1000000000, true
stop.
. currentName
. ,
, . ,
,
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 Run() {
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 mt1 = new MyThread(" ");
MyThread mt2 = new MyThread(" ");
// .
mt1.Thrd.Priority = ThreadPriority.AboveNormal;
mt2.Thrd.Priority = ThreadPriority.BelowNormal;
// .
mt1.Thrd.Start();
mt2.Thrd.Start();
mt1.Thrd.Join();
mt2.Thrd.Join();
Console.WriteLine();
Console.WriteLine(" " + mt1.Thrd.Name +
23. . :
849
,
.
.
,
. ,
,
.
, , .
- ,
, .
.
850
II. C#
,
.
,
. ,
.
#.
. lock.
C# ,
, .
# .
:
lock(lockObj) {
//
}
lockObj .
, . lock
, , ,
, .
, .
.
,
.
, . , ,
, ,
,
.
lock(this).
, this .
,
lock(this), .
, .
, .
C# lock(this).
,
.
SumIt(),
.
// .
using System;
using System.Threading;
class SumArray {
int sum;
object lockOn = new object(); // ,
//
public int SumIt(int[] nums) {
23. . :
851
lock(lockOn) { //
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 Run() {
Console.WriteLine(Thrd.Name + " .");
answer = sa.SumIt(a);
Console.WriteLine(" " + Thrd.Name + " " + 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, SumIt(),
. MyThread,
sa SumArray. ,
SumArray MyThread.
.
, sum SumArray.
SumIt() ,
sum, .
, SumIt()
. , , Sync, ,
.
lock SumIt()
. , lock
lockOn . ,
. Sleep()
, ,
. SumIt() ,
. ,
, SumIt() ,
.
.
,
SumIt().
SumIt() , ,
.
sum, ,
SumIt(). ,
SumIt() ,
23. . :
853
, sum
.
SumIt().
#1 .
#2 .
#1 .
#2 .
#1 1
#2
#1
#2
#1
#2
#1
#2
#1
#2
#1 29
1
3
5
8
11
15
19
24
29
#2 29
,
SumIt() ,
sum.
.
,
.
,
, ,
.
,
.
,
,
. , ,
- .
,
. lock
. ? ,
:
,
lock.
. , SumIt()
, lockOn .
SumIt() MyThread.
// .
using System;
854
II. C#
using System.Threading;
class SumArray {
int sum;
public int SumIt(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 Run() {
Console.WriteLine(Thrd.Name + " .");
// SumIt().
lock(sa) answer = sa.SumIt(a);
Console.WriteLine(" " + Thrd.Name +
" " + answer);
Console.WriteLine(Thrd.Name + " .");
}
}
class Sync {
static void Main() {
int[] a = (1, 2, 3, 4, 5};
MyThread mt1 = new MyThread(" #1", a);
MyThread mt2 = new MyThread(" #2", a);
mt1.Thrd.Join();
mt2.Thrd.Join();
}
}
23. . :
855
sa.SumIt(),
SumIt(). ,
.
// SumIt().
lock(sa) answer = sa.SumIt();
sa ,
.
, .
Monitor
lock C#
, Monitor,
System.Threading. , ,
. ,
Enter(), Exit().
:
public static void Enter(object obj)
public static void Exit(object obj)
obj . ,
Enter() ,
. Enter() Exit() ,
lock
. lock " "
#.
, Monitor .
TryEnter(), .
public static bool TryEnter(object obj)
true,
obj, false.
.
TryEnter()
, .
, Monitor Wait(), Pulse() PulseAll(),
.
Wait(), Pulse() PulseAll()
. lock,
R, .
? ,
R, ,
. ,
856
II. C#
. ,
.
,
,
. C#
Wait(), Pulse() PulseAll().
Wait(), Pulse() PulseAll() Monitor
.
. ,
Wait(). ,
,
. ,
, Pulse() PulseAll().
Pulse() ,
. PulseAll()
.
Wait().
public static bool Wait(object obj)
public static bool Wait(object obj, int _)
, ,
, _.
obj , .
Pulse() PulseAll():
public static void Pulse(object obj)
public static void PulseAll(object obj)
obj .
Wait(), Pulse() PulseAll() ,
, lock,
SynchronizationLockException.
Wait() Pulse()
Wait() Pulse(),
,
"" "". TickTock,
: Tick() (). Tick()
"", () "".
: Tick(), ().
, ,
"" "",
"-", .
// Wait() Pulse() .
using System;
using System.Threading;
23. . :
class TickTock {
object lockOn = new object();
public void Tick(bool running) {
lock(lockOn) {
if(!running) { //
Monitor.Pulse(lockOn); //
return;
}
Console.Write(" ");
Monitor.Pulse(lockOn); // Tock()
Monitor.Wait(lockOn); // Tock()
}
}
public void Tock(bool running) {
lock(lockOn) {
if(!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 Run() {
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);
}
}
}
857
858
II. C#
class TickingClock {
static void Main() {
TickTock tt = new TickTock();
MyThread mt1 = new MyThread("Tick", tt);
MyThread mt2 = new MyThread("Tock", tt);
mt1.Thrd.Join();
mt2.Thrd.Join();
Console.WriteLine(" ");
}
}
.
. Main() tt
TickTock, .
Run() MyThread Tick,
"", Tick(). ,
"", ().
true apiy. , true,
, false.
Tick() (). Tick(),
.
public void Tick(bool running) {
lock(lockOn) {
if((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
Wait(). Pulse()
, Wait() Tick()
, Pulse() .
, Tick(), "" ,
,
.
Tock() Tick(), ,
"". , Tock()
"", Pulse(), Tock()
. Tick() Tock()
, .. .
, Pulse() ,
Wait(). , Wait()
, Tick() Tock(), .
, ,
. Pulse() ,
.
Pulse() , .
, "",
<Ctrl+C>. , Wait()
Tock(), Pulse() , ,
Tock() ,
.
, , ,
, , , Wait() Pulse(),
.
TickTock .
Wait() Pulse() .
// 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) {
if(!running) { //
return;
}
Console.WriteLine("");
}
}
}
860
II. C#
, Tick() k() !
,
. ,
, ,
, , , -
. , ,
. ,
, !
,
, .
TickTock . ,
Pulse() Tick() k()
, ""
. -
, ,
.
. , "
", .
,
. ,
,
.
, :
. , " ",
, .
, , .
,
.
MethodImplAttribute
MethodImplAttribute.
lock , .
23. . :
861
MethodImplAttribute
Sstem.Runtime.
CompilerServices. ,
:
public MethodImplAttribute(MethodImplOptions methodImplOptions)
methodImplOptions .
MethodImplOptions.Synchronized.
,
this. static, .
.
, ,
TickTock, MethodImplOptions
.
// MethodImplAttribute .
using System;
using System.Threading;
using System.Runtime.CompilerServices;
// TickTock,
// MethodlmplOptions.Synchronized.
class TickTock {
/* Tick(). */
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void Tick(bool running) {
if(!running) { //
Monitor.Pulse(this); //
return;
}
Console.Write(" ");
Monitor.Pulse(this); // Tock()
Monitor.Wait(this); // Tock()
}
/* Tock(). */
[MethodImplAttribute(MethodImplOptions.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 Run() {
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 mt1 = new MyThread("Tick", tt);
MyThread mt2 = new MyThread("Tock", tt);
mt1.Thrd.Join();
mt2.Thrd.Join();
Console.WriteLine(" ");
}
}
, .
, lock
MethodImplAttribute .
. lock
#, , , .
MethodImplAttribute
. lock,
, .
, ,
lock. , , ,
23. . :
863
, ,
.NET Framework.
: .
. , .
,
. ,
,
.
.
System.Threading.Mutex.
. .
public Mutex()
public Mutex(bool initiallyOwned)
,
.
, initiallyOwned true.
.
,
WaitOne() . WaitOne() Mutex
Thread.WaitHandle. .
public bool WaitOne();
WaitOne() , ,
. ,
, .
true.
,
ReleaseMutex(), .
public void ReleaseMutex()
ReleaseMutex() ,
, .
WaitOne() ReleaseMutex() ,
.
Mutex myMtx = new Mutex();
// ...
myMtx.WaitOne(); //
// .
myMtx.ReleaseMutex(); //
864
II. C#
WaitOne()
, .
ReleaseMutex()
.
.
.
IncThread DecThread, :
SharedRes.Count. IncThread SharedRes.Count
, DecThread .
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 Run() {
Console.WriteLine(Thrd.Name + " .");
// .
SharedRes.Mtx.WaitOne();
Console.WriteLine(Thrd.Name + " .");
do {
Thread.Sleep(500);
SharedRes.Count++;
Console.WriteLine(" " + Thrd.Name +
", SharedRes.Count = " + SharedRes.Count);
num--;
} while(num > 0);
23. . :
865
866
II. C#
mt2.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
0
, (
SharedRes.Count) ,
.
,
, WaitOne()
ReleaseMutex() .
,
.
,
,
,
,
,
,
,
,
,
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
SharedRes.Count
=
=
=
=
=
=
=
=
=
1
0
1
0
1
0
1
0
1
,
SharedRes.Count , ,
, .
, , ,
. ,
- . .
, .
public Mutex(bool initiallyOwned, string )
public Mutex(bool initiallyOwned, string , out bool createdNew)
.
initiallyOwned
23. . :
867
true, .
,
false.
createdNew true,
, false,
. Mutex,
MutexSecurity.
.
: , ,
WaitOne()
ReleaseMutex(),
. , WaitOne()
, . WaitOne()
ReleaseMutex()
.
, ,
, .
.
, .
, . ,
. .
, .
, ,
. ,
, .
, .
, ,
. ,
.
. , ,
, .
,
. ,
, . ,
, , .
.
System.Threading.Semaphore,
.
:
public Semaphore(int initialCount, int maximumCount)
initialCount
, .. ; maximumCount
, .. ,
.
868 II. C#
, .
WaitOne()
. Semaphore WaitHandle.
WaitOne() , ,
. , ,
.
, ,
Release(). .
public int Release()
public int Release(int releaseCount)
Release() ,
, releaseCount.
,
.
WaitOne()
Release(). WaitOne()
Release() .
, Release(int num),
,
WaitOne().
,
. MyThread
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 Run() {
Console.WriteLine(Thrd.Name + " .");
sem.WaitOne();
23. . :
869
.
MyThread(" #1");
MyThread(" #2");
MyThread(" #3");
mt1.Thrd.Join();
mt2.Thrd.Join();
mt3.Thrd.Join();
}
}
MyThread sem, .
static Semaphore sem = new Semaphore(2, 2);
,
.
, MyThread.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 initialCount, int maximumCount, string )
public Semaphore(int initialCount, int maximumCount, string ,
out bool createdNew)
, .
, , ,
, initialCount maximumCount.
, initialCount maximumCount
. createdNew
true, .
initialCount maximumCount .
createdNew false, ,
initialCount maximumCount
. Semaphore,
SemaphoreSecurity.
.
C# : .
:
. ManualResetEvent AutoResetEvent
. EventWaitHandle,
, ,
.
, ,
.
ManualResetEvent AutoResetEvent.
public ManualResetEvent(bool initialState)
public AutoResetEvent(bool initialState)
initialState true,
. false,
.
. , ManualResetEvent
. , ,
WaitOne() , .
,
23. . :
871
WaitOne().
, .
,
, Set(). Set()
, .
WaitOne(), .
Reset() .
AutoResetEvent ManualResetEvent
.
ManualResetEvent ,
Reset(), AutoResetEvent
, ,
,
. AutoResetEvent,
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 Run() {
Console.WriteLine(" " + Thrd.Name);
for(int i=0; i<5; i++) {
Console.WriteLine(Thrd.Name);
Thread.Sleep(500);
}
Console.WriteLine(Thrd.Name + " !");
// .
mre.Set();
}
}
872 II. C#
class ManualEventDemo {
static void Main() {
ManualResetEvent evtObj = new ManualResetEvent(false);
MyThread mt1 = new MyThread(" 1", evtObj);
Console.WriteLine(" .");
// .
evtObj.WaitOne();
Console.WriteLine(" " +
" .");
// .
evtObj.Reset();
mt1 = new MyThread(" 2", evtObj);
// .
evtObj.WaitOne();
Console.WriteLine(" " +
" .");
}
}
,
.
1
1
.
1
1
1
1
1 !
.
2
2
2
2
2
2
2 !
.
, ManualResetEvent
MyThread.
Run() MyThread, Set(),
. Main()
evtObj ManualResetEvent,
, .
23. . :
873
MyThread, evtObj.
. evtObj
,
, MyThread
Set(), evtObj .
.
, ,
. ,
,
. ,
WaitOne() Main().
AutoResetEvent ManualResetEvent,
Reset() Main() .
,
, , .
ManualResetEvent AutoResetEvent
Reset(). , .
Interlocked
, , Interlocked.
,
. ,
Interlocked, , ,
. ,
. Interlocked
, ,
, 64- . .
Interlocked:Increment() Decrement().
:
public static int Increment(ref int location)
public static int Decrement(ref int location)
location ,
.
// .
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 Run() {
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 Run(){
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 mt1 = new IncThread(" ");
DecThread mt2 = new DecThread(" ");
mt1.Thrd.Join();
mt2.Thrd.Join();
}
}
23. . :
875
, .NET
Framework. .NET Framework 4.0
. .
Barrier
CountdownEvent
ManualResetEventSlim
SemaphoreSlim
,
,
ManualResetEvent
Semaphore
, ,
,
.
. ,
- .
.
Thread.
Abort(). .
public void Abort()
Abort()
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 Run() {
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 + " .");
}
}
class StopDemo {
static void Main() {
MyThread mt1 = new MyThread(" ");
Thread.Sleep(1000); //
Console.WriteLine(" .");
mt1.Thrd.Abort();
mt1.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
.
.
Abort() ,
.
, , .
Abort()
Abort(),
:
23. . :
877
}
class UseAltAbort {
static void Main() {
MyThread mt1 = new MyThread(" ");
Thread.Sleep(1000); //
Console.WriteLine(" .");
mt1.Thrd.Abort (100);
mt1.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
Abort() .
ExceptionState ThreadAbortException,
.
Abort()
.
ThreadAbortException, ResetAbort().
, .
ResetAbort().
public static void ResetAbort()
ResetAbort() ,
.
ResetAbort().
// 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 Run() {
Console.WriteLine(Thrd.Name + "..");
for(int i = 1; i <= 1000; i++) {
23. . :
879
try {
Console.Write(i + " ");
if((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
}
} catch(ThreadAbortException exc) {
if((int)exc.ExceptionState == 0) {
Console.WriteLine(" ! " +
" " + exc.ExceptionState);
Thread.ResetAbort();
}
else
Console.WriteLine(" , " +
exc.ExceptionState);
}
}
Console.WriteLine(Thrd.Name + " .");
}
}
class ResetAbort {
static void Main() {
MyThread mt1 = new MyThread(" ");
Thread.Sleep(1000); //
Console.WriteLine(" .");
mt1.Thrd.Abort(0); //
Thread.Sleep(1000); //
Console.WriteLine(" .");
mt1.Thrd.Abort(100); //
mt1.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()
, ,
ResetAbort(), .
.
.NET Framework
Thread.Suspend() Thread.
Resume().
. , , ,
Suspend() ,
, ,
, , .
.
, .
ThreadState,
Thread. .
public ThreadState ThreadState{ get; }
,
ThreadState. , .
ThreadState.Aborted
ThreadState.Background
ThreadState.Stopped
ThreadState.Suspended
ThreadState.Unstarted
ThreadState.AbortRequested
ThreadState.Running
ThreadState.StopRequested
ThreadState.SuspendRequested
ThreadState.WaitSleepJoin
, .
ThreadState.WaitSleepJoin ,
Wait(), Sleep() Join().
, C#
, .
, .
, .
Thread,
. CurrentThread,
Thread. .
public static Thread CurrentThread{ get; }
23. . :
881
, .
CurrentThread
, .
, ,
.
, .
// .
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(" .\n");
Thrd.Name = " ";
Thrd.Priority = ThreadPriority.AboveNormal;
Console.WriteLine(" : " +
Thrd.Name);
Console.WriteLine(" : " + Thrd.Priority);
}
}
.
.
: Normal
.
:
: AboveNormal
, , ,
. , Main() Join():
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 ,
CloseMainWindow(),
.
public bool CloseMainWindow()
, .
true, ,
false,
. , , , CloseMainWindow()
.
, .
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 = Process.Start("wordpad.exe");
Console.WriteLine(" .");
newProc.WaitForExit();
newProc.Close(); //
Console.WriteLine(" .");
}
}
WordPad,
" .".
WordPad. WordPad
" .".
24
.
: TPL
, ,
4.0 .NET Framework,
(TPL).
. -,
. -,
. , TPL
. TPL
.
, 4.0 .NET Framework,
(PLINQ). PLINQ
,
, ,
. ,
.
, PLINQ
.
,
TPL PLINQ,
.
.
,
. , ,
,
886
II. C#
. ,
- .
, , TPL PLINQ.
( ) .
TPL System.Threading.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
Task
TPL Task.
TPL Task, Thread. Task
Thread , , .
Thread . ,
- ,
.
Task -.
, ,
. , , ,
. Task ( TPL)
System.Threading.Tasks.
Task
. Task
, Start(). Task
. ,
:
public Task(Action )
, ,
Action , System.
Action, , .
public delegate void Action()
, ,
. ( ,
Action .)
, ,
Start(). .
public void Start()
Start() .
. MyTask().
Main(),
. MyTask() Main() .
// .
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// .
888
II. C#
0
1
2
3
4
5
6
7
8
9
, .
, .
Thread.Sleep()
,
MyTask(). ,
, .
24. . : TPL
889
,
, .
. , ,
, MyTask(),
, .
// .
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 mc = new MyClass();
// me.MyTask().
Task tsk = new Task(mc.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
, . Id
int. .
public int Id { get; }
, .
, .
, .
CurrentId. ,
static .
public static Nullable<int> CurrentID { get; }
,
.
,
.
// Id CurrentId.
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// , .
static void MyTask() {
Console.WriteLine("MyTask() " + Task.CurrentId + " ");
for(int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTask() #" + Task.CurrentId +
", " + count );
}
Console.WriteLine("MyTask " + Task.CurrentId + " ");
}
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, 0
MyTask() 2, 0
..... MyTask() 2, 1
MyTask() 1, 1
..... MyTask() 1, 2
MyTask() 2, 2
..... MyTask() 2, 3
MyTask() 1, 3
..... MyTask() 1, 4
MyTask() 2, 4
..... MyTask() 1, 5
MyTask() 2, 5
..... MyTask() 2, 6
MyTask() 1, 6
..... MyTask() 2, 7
MyTask() 1, 7
..... MyTask() 1, 8
MyTask() 2, 8
..... MyTask() 1, 9
MyTask 1
MyTask() 2, 9
MyTask 2
......... .
, ,
Main(), ,
Thread.Sleep(). .
892
II. C#
,
, Task.
Wait(),
, .
.
public void Wait()
.
ObjectDisposedException.
, Dispose().
, AggregateException, ,
. ,
.
, , , ,
AggregateException.
, ,
, .
, ,
.
,
Wait() .
Main(), ,
tsk tsk2.
// Wait().
using System;
using System.Threading;
using System.Threading.Tasks;
class DemoTask {
// , .
static void MyTask() {
Console.WriteLine("MyTask() " + Task.CurrentId + " ");
for(int count = 0; count < 10; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTask() #" + Task.CurrentId +
", " + count );
}
Console.WriteLine("MyTask " + Task.CurrentId + " ");
}
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 tsk2. , ,
,
tsk tsk2 Wait(). ,
tsk2, tsk.Wait() -
tsk. tsk2.Wait()
, tsk2 .
894
II. C#
Wait(),
,
WaitAll(). .
, .
.
public static void WaitAll(params Task[] tasks)
, ,
tasks. params,
Task
. ,
AggregateException.
, WaitAll() ,
.
tsk.Wait();
tsk2.Wait();
Task.WaitAll(tsk, tsk2);
,
.
,
, . ,
, WaitAll() .
,
, . , WaitAll()
, ,
. ( Wait(),
, .)
,
. WaitAny().
.
public static int WaitAny(params Task[] tasks)
, ,
tasks Task
Task. , .
.
WaitAny() ,
.
Task.WaitAny(tsk, tsk2);
, Main() , ,
.
Wait(), WaitAll()
WaitAny(), ,
. (
.)
24. . : TPL
895
Dispose()
Task IDisposable,
Dispose(). .
public void Dispose()
Dispose() Task, ,
. , , Task,
" " ( ).
, Dispose().
, ,
.
, , , Dispose()
. ,
, Dispose(),
, , Wait().
Wait(), Dispose().
Dispose() ,
InvalidOperationException.
, , ,
, Dispose()
. ( Dispose()
.
, ,
.)
- Dispose()
Task
. Dispose()
, , . ,
, , Dispose()
.
TaskFactory
,
, ,
StartNew(), TaskFactory. TaskFactory
, .
TaskFactory Factory,
Task. ,
TaskFactory. StartNew()
. :
public Task StartNew(Action action)
action . StartNew()
Task ,
action, . ,
Start() .
896 II. C#
, StartNew()
tsk .
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
.
- ,
, tsk.Dispose()
, tsk.Wait().
, Dispose() .
, tsk.Dispose()
tsk.Wait().
, .
TPL
. ,
.
, , ContinueWith(), Task.
:
public Task ContinueWith(Action<Task> _)
_ ,
. Action
Task. , Action,
, .
public delegate void Action<in T>(T obj)
T Task.
.
// .
using System;
using System.Threading;
898
II. C#
using System.Threading.Tasks;
class ContinuationDemo {
// , .
static void MyTask() {
Console.WriteLine("MyTask() ");
for(int count = 0; count < 5; count++) {
Thread.Sleep(500);
Console.WriteLine(" MyTask() " + 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(" .");
}
}
.
.
MyTask()
MyTask() 0
24. . : TPL
MyTask()
MyTask()
MyTask()
MyTask()
MyTask()
0
1
2
3
4
.
899
1
2
3
4
,
, . , Main()
. ,
MyTask() ContTask
. , MyTask()
, , .
, .
.
// -.
. .
-, ,
. . -,
,
. ,
.
900
II. C#
, ,
Task<TResult> Task.
Task:
public Task(Func<TResult> )
public Task(Func<Object, TResult> , Object )
. ,
Func, Action. Func ,
. ,
, Object,
. .
, StartNew(),
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. ,
SumIt(), , 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
AggregateException
4.0 .NET Framework ,
, .
.
Task, , StartNew().
,
, TPL PLINQ.
.
902
II. C#
, , .
.
,
. (
.) , .
,
ThrowIfCancellationRequested() .
, .
.
CancellationToken,
.. , System.Threading.
CancellationToken ,
. -,
IsCancellationRequested, .
public bool IsCancellationRequested { get; }
true,
, false. -,
ThrowIfCancellationRequested(), .
public void ThrowIfCancellationRequested()
, ,
, OperationCanceledException.
.
,
. ,
AggregateException,
InnerException InnerExceptions. (
InnerExceptions .
25.)
,
CancellationTokenSource,
System. Threading. ,
CancellationTokenSource. (
CancellationTokenSource.) , ,
Token,
.
public CancellationToken Token { get; }
, .
.
: ,
. ,
.
IsCancellationRequested .
true, , ,
24. . : TPL
903
. ,
. , ,
IsCancellationRequested ,
.
, ThrowIfCancellationRequested(),
, ,
Task,
StartNew().
.
StartNew().
public Task StartNew(Action<Object> action, Object ,
CancellationToken _)
,
_. ,
, , Task.
, Action.
public delegate void Action<in T>(T obj)
Object.
obj CancellationToken.
:
, Dispose().
.
: IsCanceled
Task. true, .
.
.
, ThrowIfCancellationRequested()
MyTask(). ,
. IsCancellationRequested.
true,
Cancel() ,
ThrowIfCancellationRequested()
.
// .
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(" MyTask() " + 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("\n tsk \n");
// :
// Console.WriteLine();
} finally {
tsk.Dispose();
cancelTokSrc.Dispose();
}
Console.WriteLine(" .");
}
}
.
2 .
.
MyTask()
24. . : TPL
MyTask()
MyTask()
MyTask()
MyTask()
,
905
0
1
2
3
.
tsk
.
, MyTask()
Main() . ,
MyTask() .
AggregateException, . tsk ,
,
. , , , AggregateException
, ,
, .
,
AggregateException.
,
,
.
. . ,
, ,
,
.
Aggregate
Exception, ,
. Flatten(),
AggregateException
AggregateException. , Handle(),
, AggregateException.
, .
TaskCreationOptions Task
StartNew(). , TaskFactory
FromAsync(),
( Asynchronous Programming Model).
,
TaskScheduler. ,
, .NET Framework.
. ,
.
906
II. C#
Parallel
, , ,
TPL , Thread.
, TPL
. Parallel,
, :
.
Parallel , For(),
ForEach() Invoke(). .
, For() for, ForEach()
foreach,
. Invoke()
. ,
,
.
.
Invoke()
Invoke(), Parallel,
, .
, , .
.
public static void Invoke(params Action[] actions)
Action. , Action .
public delegate void Action()
, , Invoke()
, , .
actions 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
MyMeth() 4
MyMeth()
MyMeth2() 4
MyMeth2()
.
: Main() ,
Invoke(). , Main(),
MyMeth() MyMeth2(), .
Invoke() , ,
.
,
Invoke() .
,
Invoke() -.
// 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(" .");
}
}
,
.
For()
TPL , , For(),
Parallel. .
, :
public static ParallelLoopResult
For (int fromInclusive, int toExclusive, Action<int> body)
fromInclusive ,
; , ,
; a toExclusive , .
. ,
fromInclusive
toExclusive .
, body.
Action<int>, .
public delegate void Action<in T>(T obj)
For() T , , int.
, obj,
. , body,
. For()
ParallelLoopResult, .
. (
.)
For() , ,
, . , ,
. ,
,
. , , ,
-
, - ,
, .
For() . data,
1000000000 . For(), ""
MyTransform(). ,
data.
. ,
,
- .
.
910
II. C#
// Parallel.For()
// .
using System;
using System.Threading.Tasks;
class DemoParallelFor {
static int[] data;
// , .
// .
<
>
>
>
10000) data[i] = 0;
10000 & data[i] < 20000) data[i] = 100;
20000 & data[i] < 30000) data[i] = 200;
30000) 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.For(0, data.Length, MyTransform);
Console.WriteLine(" .");
}
}
. , , for
data. ,
For(), data .
,
. For()
MyTransform() ,
. ,
,
For() .
, , ,
, . , , ,
,
, . for
For() .
,
, , ,
, ,
.
24. . : TPL
911
for,
.
//
// for.
using System;
using System.Threading.Tasks;
using System.Diagnostics;
class DemoParallelFor {
static int[] data;
// , .
// .
<
>
>
>
1000) data[i] = 0;
1000 & data[i] < 2000) data[i] = 100;
2000 & data[i] < 3000) data[i] = 200;
3000) data[i] = 300;
}
static void Main() {
Console.WriteLine(" .");
// Create Stopwatch
// .
Stopwatch sw = new Stopwatch();
data = new int[100000000];
// .
sw.Start();
// .
Parallel.For(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.For(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.For(0, data.Length, (i) => data[i] = i );
"" -. (, .) ,
For() .
-, Stopwatch
. System.
Diagnostics. ,
, Start(), ,
Stop(), . Reset()
.
.
Elapsed, TimeSpan.
TotalSeconds ,
. , Stopwatch
.
, For()
ParallelLoopResult. , .
public bool IsCompleted { get; }
public Nullable<long> LowestBreakIteration { get; }
IsCompleted true,
. ,
true.
, false.
LowestBreakIteration
,
ParallelLoopState.Break().
ParallelLoopState
For(),
. For() .
public static ParallelLoopResult For(int fromInclusive, int toExclusive,
ActionCint, ParallelLoopState> body)
Action, ,
.
public delegate void Action<in T1, in T2>(T argl, T2 arg2)
For() T1 int,
2 ParallelLoopState. , Action
, rg2.
Break(),
ParallelLoopState ,
body. Break() .
public void Break()
914
II. C#
Break()
,
Break(). Break()
. , ,
. , 10 , ,
10 10 .
, For(),
. , ,
.
,
.
Break() , For().
, ,
MyTransform() ParallelLoopState
, Break()
. ,
, data Main().
. IsCompleted
false, data
. , .
( ,
, :
.)
// ParallelLoopResult ParallelLoopState,
// Break() For() .
using System;
using System.Threading.Tasks;
class DemoParallelForWithLoopResult {
static int[] data;
// , .
// .
<
>
>
>
1000) data[i] = 0;
1000 & data[i] < 2000) data[i] = 100;
2000 s data[i] < 3000) data[i] = 200;
3000) 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.For(0, data.Length, MyTransform);
// , .
if(!loopResult.IsCompleted)
Console.WriteLine("\n - , " +
" \n" +
" " +
loopResult.LowestBreakIteration + "\n");
Console.WriteLine(" .");
}
}
, ,
.
.
- ,
1000
.
,
1000 . , Break()
MyTransform()
.
For()
.
, long int
. For(),
, , , ,
.
, : ,
For(), ,
,
Stop(), Break().
ForEach()
ForEach(),
foreach. ForEach().
:
916
II. C#
using System;
using System.Threading.Tasks;
class DemoParallelForWithLoopResult {
static int[] data;
// , .
// v
// , .
static void DisplayData(int v, ParallelLoopState pls) {
// .
if(v < 0) pls.Break();
Console.WriteLine(": " + v);
}
24. . : TPL
917
PLINQ
PLINQ
LINQ TPL. PLINQ , ,
. ,
. TPL, PLINQ ,
.
ParallelEnumerable
PLINQ ParallelEnumerable,
System.Linq. ,
918
II. C#
, .
, LINQ
Enumerable. ParallelQuery,
ParallelQuery. ParallelQuery
,
. , .
ParallelQuery ,
ParallelEnumerable. ,
AsParallel(), .
AsParallel()
PLINQ
. AsParallel()
. AsParallel() ParallelEnumerable
, ParallelQuery.
.
,
. ( ,
, , .) ,
AsParallel()
, LINQ LINQ.
.
, AsParallel().
:
public static ParallelQuery AsParallel(this IEnumerable source)
public static ParallelQuery<TSource>
AsParallel<TSource> (this IEnumerable<TSource> source)
TSource
source.
, PLINQ.
// PLINQ.
using System;
using System.Linq;
class PLINQDemo {
static void Main() {
int[] data = new int[10000000];
// .
for(int i=0; i < data.Length; i++) data[i] = i;
// .
data[1000] = -1;
data[14000] = -2;
data[15000] = -3;
data[676000] = -4;
24. . : TPL
919
data[8024540] = -5;
data[9908000] = -6;
// PLINQ .
var negatives = from val in data.AsParallel()
where val < 0
select val;
foreach(var v in negatives)
Console.Write(v + " ");
Console.WriteLine();
}
}
data,
.
.
. .
var negatives = from val in data.AsParallel()
where val < 0
select val;
AsParallel() ,
data.
data, :
.
. ,
data.
.
-5 -6 -1 -2 -3 -4
, , ,
-5 -6 , -1 ,
. , , , -
,
. ,
.
AsOrdered()
,
. ,
.
, AsOrdered(),
ParallelEnumerable.
:
920
II. C#
, .
CancellationToken,
CancellationTokenSource.
WithCancellation().
Cancel(), .
:
, OperationCanceledException,
AggregateException. ,
, OperationCanceledException
AggregateException.
.
WithCancellation():
public static ParallelQuery<TSource>
WithCancellation<TSource> (
this ParallelQuery<TSource> source,
CancellationToken CancellationToken)
source , a CancellationToken
. , .
, .
, 100
, . ,
foreach, , Main()
.
// .
using System;
24. . : TPL
921
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class PLINQCancelDemo {
static void Main() {
CancellationTokenSource cancelTokSrc = new CancellationTokenSource();
int[] data = new int[10000000];
// .
for(int i=0; i < data.Length; i++) data[i] = i;
// .
data[1000] = -1;
data[14000] = -2;
data[15000] = -3;
data[676000] = -4;
data[8024540] = -5;
data[9908000] = -6;
// PLINQ .
var negatives = from val in data.AsParallel().
WithCancellation(cancelTokSrc.Token)
where val < 0
select val;
// 100 .
Task cancelTsk = Task.Factory.StartNew( () => {
Thread.Sleep(100);
cancelTokSrc.Cancel();
});
try {
foreach(var v in negatives)
Console.Write(v + " ");
} catch(OperationCanceledException exc) {
Console.WriteLine(exc.Message);
} catch(AggregateException exc) {
Console.WriteLine(exc);
} finally {
cancelTsk.Wait();
cancelTokSrc.Dispose();
cancelTsk.Dispose();
}
Console.WriteLine();
}
}
.
,
.
, WithCancellation.
922
II. C#
PLINQ
, PLINQ .
, PLINQ. PLINQ
,
. , WithDegreeOfParallelism()
, ,
AsSequential()
. ,
foreach, ,
ForAll(). ParallelEnumerable.
, PLINQ
, WithExecutionMode(),
ParallelExecutionMode.ForceParallelism.
PLINQ
,
. TPL, ,
, ""
, . ,
, ,
.
Microsoft.
25
.NET Framework:
. #
. .NET Framework
,
.
,
,
. , .NET Framework
,
, , , -.
, ,
#.
.
C# 2.0 .NET Framework
.
.
(TPL) 4.0 .NET
Framework ,
,
.
, Collections API
.NET Framework.
,
, :
.
foreach.
924
II. C#
,
.
.
, ArrayList, Hashtable, Stack Queue,
- .
, .
.NET Framework : ,
, , .
,
, , , , "-".
:
object.
,
, .
, ,
object.
System.Collections.
- . ,
, ,
. System.
Collections.Specialized.
Collections API
BitArray. BitArray
, .. ,
, ,
. BitArray
System.Collections.
, , , .
.
, ,
.
.
System.Collections.Generic.
.
, System.Collections.
Concurrent.
System.Collections.ObjectModel
,
.
,
IEnumerator IEnumerable,
IEnumerator<T> IEnumerable<T>.
.
, .
25. ,
925
IEnumerable,
,
IEnumerator IEnumerator<T>. , ,
, .
,
foreach .
,
IEnumerator IEnumerable,
IEnumerator<T> IEnumerable<T>.
.
, .
IEnumerable,
,
IEnumerator IEnumerator<T>. , ,
, .
,
foreach .
,
. ,
, foreach.
.
:
C++, , , ,
(Standard Template Library STL),
C++. , C++ ,
C# . Java.
Collections Framework Java,
C# .
(,
, , )
.
.NET Framework 1.0.
System.Collections.
,
. , ,
.
.
, . ,
.
,
, .
926 II. C#
,
. .
System.Collections
.
, ,
. ,
, . 25.1.
.
25.1.
ICollection
IComparer
IDictionary
IDictionaryEnumerator
IEnumerable
IEnumerator
IEqualityComparer
IHashCodeProvider
IList
IStructuralComparable
IStructuralEquatable
,
Compare() ,
, "-"
,
IDictionary
GetEnumerator(),
,
.
IEqualityComparer
,
CompareTo(),
Equals(),
, . ,
GetHashCode()
ICollection
ICollection ,
.
. IEnumerable.
ICollection .
Count ,
, . Count
, .
ICollection .
void (Array target, int startIdx)
25. ,
927
true,
,
false.
.
,
() target,
, startIdx. , ()
C# .
ICollection IEnumerable,
,
IEnumerable. GetEnumerator(), .
IEnumerator GetEnumerator()
.
IEnumerable
ICollection :
AsParallel(), AsQueryable(), Cast() OfType(). , AsParallel()
System.Linq.ParallelEnumerable, AsQueryable()
System.Linq.Queryable, Cast() OfType() System.
Linq.Enumerable. LINQ,
.
IList
IList ,
.
ICollection IEnumerable.
, , IList
. . 25.2.
.
,
NotSupportedException.
25.2. , IList
value .
,
void Clear()
bool Contains (object value) true,
value,
false
int Add(object value)
928 II. C#
. 25.2
value,
.
value ,
-1
value
index. ,
index , ,
value
value
. ,
, ,
"
,
index. ,
,
,
IList Add().
, Add() object.
object ,
, ,
.
Remove() RemoveAt().
, Remove() , RemoveAt()
. Clear().
, ,
Contains(). IndexOf(),
Insert().
IList .
bool IsFixedSize { get; }
bool IsReadOnly { get; }
, IsFixedSize
true. ,
, . ,
IsReadOnly true. ,
.
, IList .
object this[int index] { get; set; }
.
.
Add(). ,
.
25. ,
929
IDictionary
IDictionary
,
. ,
. , , IDictionary,
"-". ,
. IDictionary
ICollection IEnumerable. , IDictionary,
. 25.3. ArgumentNullException
, .
25.3. , IDictionary
true,
key ,
false
,
key
IDictionaryEnumerator
GetEnumerator()
void Remove(object key)
"-" IDictionary
Add(). ,
.
Remove(). Clear().
, ,
Contains() .
GetEnumerator() ,
IDictionary. "-".
IDictionary .
true,
bool IsReadOnly { get; }
true,
ICollection Keys { get; }
ICollection Values { get; }
, , ,
Keys Values.
, IDictionary .
object this[object key] { get; set; }
930 II. C#
,
.
, .
IEnumerable, IEnumerator IDictionaryEnumerator
IEnumerable ,
. ,
IEnumerable ,
ICollection.
GetEnumerator(), IEnumerable.
IEnumerator GetEnumerator()
. IEnumerable
foreach.
IEnumerator .
.
"-" (), GetEnumerator()
IDictionaryEnumerator, IEnumerator.
IDictionaryEnumerator IEnumerator
, .
IEnumerator MoveNext() Reset()
Current.
. , Current ,
. MoveNext()
, Reset() .
IComparer IEqualityComparer
IComparer
.
Compare()
IStructuralComparable IStructuralEquatable
IStructuralComparable IStructuralEquatable
4.0 .NET Framework. IStructuralComparable
CompareTo(),
. ( , CompareTo()
, .) .
int CompareTo(object other, IComparer comparer)
25. ,
931
-1,
other; 1, other; , 0,
.
, comparer.
IStructuralEquatable
.
.
bool Equals(object other, IEqualityComparer comparer)
int GetHashCode(IEqualityComparer comparer)
Equals() true,
other . GetHashCode()
- . , ,
. ,
comparer.
DictionaryEntry
System.Collections DictionaryEntry.
"-"
DictionaryEntry. .
public object Key { get; set; }
public object Value { get; set; }
,
. DictionaryEntry
:
public DictionaryEntry(object key, object value)
key , a value .
, ,
, .
, BitArray,
.
ArrayList
, .. ,
- -
, ,
-
, , "
Hashtable
Queue
SortedList
Stack
932 II. C#
ArrayList
ArrayList ,
. C#
, .
, .
. ArrayList.
ArrayList ,
.
ArrayList . ,
.
. ArrayList
#.
. ArrayList
, .
ArrayList ICollection, IList, IEnumerable
ICloneable. ArrayList.
public ArrayList()
public ArrayList(ICollection c)
public ArrayList(int capacity)
ArrayList
. ArrayList
,
. ,
, city.
,
. ArrayList
.
ArrayList , ,
, .
ArrayList . 25.4.
ArrayList , Sort().
BinarySearch()
. ArrayList ,
Reverse().
25.4. , ArrayList
ArrayList
value. .
,
.
25. ,
933
. 25.4
value, ,
comparer.
. ,
.
value, ,
comparer. ,
index,
, count.
.
,
.
array,
array, ,
arrayIndex.
,
, index,
, count,
array, ,
arrayIndex.
list ArrayList
ArrayList.
, index,
,
count.
,
value
.
, -1
, ,
index
value .
, -1
934
II. C#
. 25.4
list
ArrayList, ,
,
, index,
,
count
, ,
index, ,
count
,
, index,
,
, comparer.
comparer ,
,
,
, comparer.
,
index, ,
count.
comparer ,
,
ArrayList,
list
,
,
.
type
Capacity
Count
ArrayList ,
. , ArrayList
, InsertRange().
RemoveRange().
25. ,
935
ArrayList
SetRange(). ,
, .
ArrayList .
, ,
Synchronized().
ArrayList Capacity,
, , .
public virtual int Capacity { get; set; }
Capacity
ArrayList. ,
ArrayList .
, ArrayList ,
.
, .
.
,
ArrayList,
Capacity. Count.
, Count ICollection
, .
Capacity Count
ArgumentOutOfRangeException.
ArrayList,
, Capacity
Count. TrimToSize().
ArrayList. ArrayList,
, .
, .
,
. , .
// ArrayList.
using System;
using System.Collections;
class ArrayListDemo {
static void Main() {
// .
ArrayList al = new ArrayList();
Console.WriteLine(" : " + al.Count);
Console.WriteLine();
Console.WriteLine(" 6 ");
// .
al.Add('');
936
II. C#
al.Add('A');
al.Add('E');
al.Add('');
al.Add('D');
al.Add('F');
Console.WriteLine(" : " + al.Count);
// ,
// .
Console.Write(" : ");
for(int i=0; i < al.Count; i++)
Console.Write(al[i] + " ");
Console.WriteLine("\n");
Console.WriteLine(" 2 ");
// .
al.Remove('F');
al.Remove('A');
Console.WriteLine(" : " + al.Count);
// , foreach.
Console.Write(": ");
foreach(char in al)
Console.Write( + " ");
Console.WriteLine("\n");
Console.WriteLine(" 20 ");
// ,
// .
for (int i=0; i < 20; i++)
al.Add((char)('a' + i));
Console.WriteLine(" : " + al.Capacity);
Console.WriteLine(" 20 : " +
al.Count);
Console.Write(": ");
foreach(char in al)
Console.Write( + " ");
Console.WriteLine("\n");
// ,
// .
Console.WriteLine(" ");
al[0] = 'X';
al[1] = 'Y';
al[2] = 'Z';
Console.Write(": ");
foreach(char in al)
Console.Write(c + "
Console.WriteLine();
}
}
25. ,
937
.
: 0
6
: 6
: D F
2
: 4
: D
20
: 32
20 : 24
: C E B D a b c d e f g h i j k l m n o p q r s t
: X Y Z D a b c d e f g h i j k l m n o p q r s t
ArrayList
ArrayList Sort().
BinarySearch()
.
.
// ArrayList .
using System;
using System.Collections;
class SortSearchDemo {
static void Main() {
// .
ArrayList al = new ArrayList();
// .
al.Add(55);
al.Add(43);
al.Add(-4);
al.Add(88);
al.Add(3);
al.Add(19);
Console.Write(" : ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
// .
al.Sort();
// , foreach.
938
II. C#
Console.Write(" : ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
Console.WriteLine(" 43: " +
al.BinarySearch(43));
}
}
.
: 55 43 -4 88 3 19
: -4 3 19 43 55 88
43: 3
ArrayList
.
. ,
, .
,
. .
ArrayList
ArrayList
. rr().
. :
, , .
ArrayList
, .
// ArrayList .
using System;
using System.Collections;
class ArrayListToArray {
static void Main() {
ArrayList al = new ArrayList();
// .
al.Add(1);
al.Add(2);
al.Add(3);
al.Add(4);
Console.Write(": ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine();
// .
25. ,
939
Hashtable
Hashtable ,
-. ,
- ,
. , , .
- ,
, . -
, - .
,
,
. Hashtable IDictionary,
ICollection, IEnumerable, ISerializable, IDeserializationCallback
ICloneable.
Hashtable .
.
public
public
public
public
Hashtable()
Hashtable(IDictionary d)
Hashtable(int capacity)
Hashtable(int capacity,
float loadFactor)
Hashtable.
Hashtable
d. Hashtable
, , capacity.
Hashtable ,
capacity loadFactor.
, ,
940
II. C#
0,1 1,0. -
. , ,
, . ,
,
1,0.
Hashtable , ,
, .
. 25.5. ,
, Hashtable,
ContainsKey(). ,
, ContainsValue().
Hashtable GetEnumerator(),
IDictionaryEnumerator. , IDictionaryEnumerator
, ,
"-".
25.5. , Hashtable
true,
Hashtable
key,
false
true,
Hashtable
value,
false
Hashtable
IDictionaryEnumerator
Hashtable,
table
public virtual
IDictionaryEnumerator
GetEnumerator()
public static Hashtable
Synchronized(Hashtable table)
Hashtable ,
, . ,
Keys Values,
Hashtable. IDictionary
.
public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
Hashtable ,
. ,
Hashtable EqualityComparer.
, hcp comparer, .
"-" Hashtable
DictionaryEntry,
25. ,
941
,
. , , Hashtable
, Add(), :
.
, , ,
Hashtable . ,
, , .
,
Hashtable.
// Hashtable.
using System;
using System.Collections;
class HashtableDemo {
static void Main() {
// -.
Hashtable ht = new Hashtable();
// .
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
// .
ht[""] = " ";
// .
ICollection = ht.Keys;
// .
foreach(string str in )
Console.WriteLine(str + ": " + ht[str]);
}
}
.
:
:
:
:
:
, "-"
. ,
- ht.
Keys. - ht
, . ,
,
IDictionary Hashtable.
942
II. C#
SortedList
SortedList , "" , .
SortedList IDictionary, ICollection, IEnumerable
ICloneable.
SortedList , .
public
public
public
public
SortedList()
SortedList(IDictionary d)
SortedList(int initialCapacity)
SortedList(IComparer comparer)
,
.
SortedList, d.
.
SortedList,
, initialCapacity.
, .
comparer ,
. ,
.
SortedList
. ,
, .
SortedList
. ,
, ,
.
SortedList , ,
, .
. 25.6. ,
, SortedList,
Contains(). ,
SortedList, ContainsValue().
SortedList GetEnumerator(),
IDictionaryEnumerator.
,
IDictionaryEnumerator ,
, "-". ,
,
SortedList, Synchronized().
25.6. , SortedList
true,
SortedList
key,
false
25. ,
943
. 25.6
true,
SortedList
value,
false
,
index
SortedList
IDictionaryEnumerator
,
index
SortedList
,
SortedList
SortedList
,
SortedList
key.
, -1
value .
, -1
Index
value
SortedList,
list
Capacity
Count
. ,
GetByIndex(),
SetByIndex().
GetKey(),
GetKeyList(). ,
GetValueList().
IndexOfKey(),
IndexOfValue(). , SortedList
, IDictionary
.
SortedList ,
, . Hashtable,
, Keys Values,
944
II. C#
SortedList. IDictionary
.
public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
SortedList.
Hashtable, "-"
SortedList DictionaryEntry, ,
,
, SortedList.
SortedList. ,
Hashtable,
SortedList. ,
,
.
// SortedList.
using System;
using System.Collections;
class SLDemo {
static void Main() {
// .
SortedList sl = new SortedList();
// .
sl.Add("", " ");
sl.Add("", " ");
sl.Add("", " ");
sl.Add("", " ");
// ,
sl[""] = " ";
// .
ICollection = sl.Keys;
// .
Console.WriteLine(" .");
foreach(string str in )
Console.WriteLine(str + ": " + sl[str]);
Console.WriteLine();
// , .
Console.WriteLine(" .");
for(int i=0; i < sl.Count; i++)
Console.WriteLine(sl.GetByIndex(i));
Console.WriteLine();
// .
25. , 945
Console.WriteLine(" .");
foreach(string str in )
Console.WriteLine(str + ": " + si.IndexOfKey (str));
}
}
.
.
:
:
:
:
:
.
.
: 0
: 1
: 2
: 3
: 4
Stack
,
, " ".
,
. , , .
. , , ,
,
, , Stack.
ICollection, IEnumerable ICloneable.
,
. , ,
.
Stack .
public Stack()
public Stack(int initialCapacity)
public Stack(ICollection col)
,
, ,
initialCapacity, ,
col.
.
946
II. C#
Stack , ,
, .
. 25.7.
. ,
Push(). ,
Pop(). ,
, k(). Pop() k(),
, InvalidOperationException.
25.7. , Stack
Count ,
, ,
true,
obj ,
false
,
,
,
,
obj
Stack,
stack
,
,
, .
// Stack.
using System;
using System.Collections;
class StackDemo {
static void ShowPush(Stack st, int a) {
st.Push(a);
Console.WriteLine(" : Push(" + a + ")");
Console.Write(" : ");
foreach(int i in st)
Console.Write(i + " ");
Console.WriteLine();
}
static void ShowPop(Stack st) {
Console.Write(" : Pop -> ");
int a = (int) st.Pop();
25. ,
947
Console.WriteLine(a);
Console.Write(" : ");
foreach(int i in st)
Console.Write(i + " ");
Console.WriteLine();
}
static void Main() {
Stack st = new Stack ();
foreach(int i in st)
Console.Write(i + " ");
Console.WriteLine();
ShowPush(st, 22);
ShowPush(st, 65);
ShowPush(st, 91);
ShowPop(st);
ShowPop(st);
ShowPop(st);
try {
ShowPop(st);
} catch (InvalidOperationException) {
Console.WriteLine(" .");
}
}
}
. ,
InvalidOperationException,
.
:
:
:
:
:
:
:
:
:
:
:
:
:
Push (22)
22
Push(65)
65 22
Push (91)
91 65 22
Pop -> 91
65 22
Pop -> 65
22
Pop -> 22
Pop -> .
Queue
,
: . ,
, .
948
II. C#
.
, .
, , ,
,
. ,
.
, , Queue.
ICollection, IEnumerable ICloneable.
, ,
. , ,
, 2,0.
Queue .
public
public
public
public
Queue()
Queue (int capacity)
Queue (int capacity, float growFactor)
Queue (ICollection col)
2,0.
, ,
city, 2,0.
( capacity),
( growFactor
1,0 10,0). ,
col.
, 2,0.
Queue , ,
, .
. 25.8.
. ,
Enqueue().
, Dequeue(). ,
, k().
Dequeue() k() , ,
InvalidOperationException.
25.8. , Queue
Count ,
, ,
true,
obj ,
false
.
obj
25. ,
949
. 25.8
,
Queue,
queue
,
Capacity
Count
Queue.
// Queue.
using System;
using System.Collections;
class QueueDemo {
static void ShowEnq(Queue q, int a) {
q.Enqueue(a);
Console.WriteLine(" : Enqueue(" + a + ")");
Console.Write(" : ");
foreach(int i in q)
Console.Write(i + " ");
Console.WriteLine ();
}
static void ShowDeq(Queue q) {
Console.Write(" : Dequeue -> ");
int a = (int) q.Dequeue();
Console.WriteLine(a);
Console.Write(" : ");
foreach(int i in q)
Console.Write(i + " ");
Console.WriteLine();
}
static void Main() {
Queue q = new Queue();
foreach(int i in q)
Console.Write(i + " ");
Console.WriteLine();
950
II. C#
ShowEnq(q, 22);
ShowEnq(q, 65);
ShowEnq(q, 91);
ShowDeq(q);
ShowDeq(q);
ShowDeq(q);
try {
ShowDeq (q);
} catch (InvalidOperationException) {
Console.WriteLine(" .");
}
}
}
.
: Enqueue(22)
: 22
: Enqueue(65)
: 22 65
: Enqueue(91)
: 22 65 91
: Dequeue -> 22
: 65 91
: Dequeue -> 65
: 91
: Dequeue -> 91
:
: Dequeue -> .
BitArray
BitArray .
, ,
. BitArray
ICollection IEnumerable
. , BitArray
ICloneable.
BitArray . ,
BitArray
.
public BitArray(bool[] values)
values
. , values
. , values
.
BitArray ,
.
public BitArray(byte[] bytes)
25. ,
951
bytes,
bytes[0] 8 , bytes[1] 8
.. , BitArray
, .
public BitArray(int[ ] values)
values[0] 32 ,
values[1] 32 ..
BitArray,
:
public BitArray(int length)
length ,
false.
, .
public BitArray(int length, bool defaultValue)
defaultValue, .
, BitArray
, .
public BitArray(BitArray bits)
,
bits,
.
BitArray .
, .
BitArray , ,
, .
. 25.9. , BitArray
Synchronized(). ,
, IsSynchronized
false. BitArray
,
SyncRoot.
25.9. , BitArray
952
II. C#
. 25.9
value.
BitArray,
, Index,
value
value
value. BitArray,
BitArray , ,
, .
public int Length { get; set; }
Length
. , ,
Count, . Count,
Length , , ,
BitArray. ,
BitArray , .
BitArray ,
false, , .
, BitArray .
public bool this[int index] { get; set; }
.
BitArray.
// BitArray.
using System;
using System.Collections;
class BADemo {
public static void ShowBits(string rem,
BitArray bits) {
Console.WriteLine(rem);
for(int i=0; i < bits.Count; i++)
Console.Write("{0, -6} ", bits[i]);
Console.WriteLine("\n");
}
static void Main() {
BitArray ba = new BitArray(8);
byte[] b = { 67 };
BitArray ba2 = new BitArray(b);
25. ,
953
.NET Framework ,
. System.
Collections.Specialized .
CollectionsUtil
HybridDictionary
,
-"
ListDictionary.
Hashtable
, .
,
-, ,
string
,
-
,
-,
-, ,
string
ListDictionary
NameValueCollection
OrderedDictionary
StringCollection
StringDictionary
954
II. C#
, System.Collections
: CollectionBase, ReadOnlyCollectionBase DictionaryBase.
.
Collections API
,
. System.
Collections.Generic. ,
, . ,
LinkedList ,
.
, . , ArrayList
List, HashTable Dictionary.
,
. , ,
.
, ,
, , .
, ,
. ,
,
. ,
,
.
,
. .
System.Collections.Generic
,
. . 25.10.
25.10.
ICollection<T>
IComparer<T>
IDictionary<Tkey, TValue>
Compare()
,
,
"-
25. ,
955
. 25.10
IEnumerable<T>
GetEnumerator(),
,
,
Enumerator<T>
IEqualityComparer<T>
IList<T>
ICollection<T>
ICollection<T> ,
. ICollection<T>
ICollection,
.
, ICollection<T> .
int Count { get; }
bool IsReadOnly { get; }
Count ,
. IsReadOnly true,
. , ,
false.
, ICollection<T>
. ,
, .
item .
NotSupportedException,
void Clear()
bool Contains(T item)
true,
item,
false
void CopyTo(T[] array,
int arrayIndex)
array, ,
arrayIndex
void Remove(T item)
item
. true,
item .
,
false
NotSupportedException, .
956
II. C#
ICollection<T> IEnumerable
IEnumerable<T>,
GetEnumerator().
ICollection<T>
IEnumerable<T>, ,
Enumerable.
LINQ, ,
.
IList<T>
IList<T> ,
. IEnumerable, IEnumerable<T>
ICollection<T>
IList. , IList<T>, .
25.11. .
,
Insert() RemoveAt() NotSupportedException.
25.11. , IList<T>
item
. item
, -1
void Insert(int index,
item
T item)
index
void RemoveAtfint index) ,
index
, IList<T>
this[int index] { get; set; }
index.
IDictionary<TKey, TValue>
IDictionary<TKey, TValue>
,
. , ,
"-". IDictionary<TKey, TValue>
IEnumerable, IEnumerable<KeyValuePair<TKey,
TValue>> ICollection<KeyValuePair<TKey, TValue>>
IDictionary. ,
IDictionary<TKey, TValue>, . 25.12.
ArgumentNullException
.
25. ,
957
, key value.
ArgumentException,
key
bool Contains(TKey key)
true,
key
, false
bool Remove(TKey key)
,
key
bool TryGetValue(TKey key,
out TValue value)
key
value.
true,
false. key
, value ,
void Add(TKey key, TValue
value)
, IDictionary<TKey, TValue>
.
IEnumerable<T> IEnumerator<T>
IEnumerable<T> IEnumerator<T>
IEnumerable
IEnumerator. ,
. ,
, .
IEnumerable<T> GetEnumerator()
.
IEnumerator<T> GetEnumerator()
. ,
.
958
II. C#
, IEnumerable<T> ,
: MoveNext() Reset().
Current.
Current { get; }
. ,
Current .
IEnumerator IEnumerator<T>
: IEnumerator<T> IDisposable,
IEnumerator . IDisposable
Dispose(), .
IEnumerable<T>
IEnumerable. ,
GetEnumerator(). , IEnumerable<T>
IEnumerator, ,
Current.
IComparer<T>
IComparer<T>
IComparer. ,
IComparer<T> .
Compare() .
int Compare( , )
.
, , ;
, ;
.
IEqualityComparer<T>
IEqualityComparer<T>
EqualityComparer. .
bool Equals ( , )
int GetHashCode( obj)
Equals() true,
. GetHashCode() - obj.
, - .
ISet<T>
ISet<T> 4.0 .NET Framework.
, .
IEnumerable, IEnumerable<T>,
ICollection<T>. ISet<T> ,
25. ,
959
. 25.13. ,
IEnumerable<T>. ,
, ISet<T>
ISet<T>
25.13. , ISet<T>
void ExceptWith(Ienumerable<T> ,
other)
other
void
IntersectWith(IEnumerable<T>
other)
other
bool
true,
IsProperSubsetOf(IEnumerable<T>
other)
other,
false
bool IsProperSupersetOf(IEnumera
true,
ble<T> other)
other,
false
bool IsSubsetOf(IEnumerable<T> true,
other)
other,
false
bool
true,
IsSupersetOf(IEnumerable<T>
other)
other,
false
bool Overlaps(IEnumerable<T>
true,
other)
other
,
false
bool SetEquals(IEnumerable<T> true,
other)
other ,
false.
,
other
void SymmetricExceptWith
(IEnumerable<T> other)
other
void UnionWith(IEnumerable<T>
other)
other
960
II. C#
KeyValuePair<TKey, TValue>
System.Collections.Generic
KeyValuePair<TKey, TValue>.
, "", , , Dictionary<TKey, TValue>.
.
public TKey Key { get; };
public TValue Value { get; };
.
KeyValuePair<TKey, TValue> :
public KeyValuePair(TKey key, TValue value)
key , a value .
,
,
.
. System.
Collections.Generic. . 25.14 ,
. .
25.14.
Dictionary<Tkey, TValue>
-".
,
Hashtable
,
.
,
ArrayList
.
, Queue
".
, SortedList
.
, Stack
HashSet<T>
LinkedList<T>
List<T>
Queue<T>
SortedDictionary<TKey,
TValue>
SortedList<TKey, TValue>
SortedSet<T>
Stack<T>
25. ,
961
System.Collections.Generic
: SynchronizedCollection<T>
IList<T>; SynchronizedReadOnlyCollection<T>,
lList<T>;
SynchronizedKeyCollection<K, >,
System.ServiceModel.UriSchemeKeyedCollection;
KeyedByTypeCollection<T> ,
.
List<T>
List<T> .
ArrayList.
ICollection, ICollection<T>, IList,
IList<T>, IEnumerable IEnumerable<T>. List<T>
.
public List()
public List(IEnumerable<T> collection)
public List(int capacity)
List
.
List ,
collection .
List, ,
capacity. ,
. ,
,
.
List<T> , ,
, .
. 25.15.
25.15. , List<T>
collection
ArrayList
, item.
.
,
.
962
II. C#
. 25.15
, item,
,
comparer.
. ,
.
, item,
,
comparer. ,
index,
,
count.
. ,
.
.
,
index,
, count.
,
item .
, -1
collection
, ,
index
item .
, -1
,
, index,
,
count
, ,
index,
, count
25. ,
963
. 25.15
public void
Sort(Imrr<> comparer)
public void
Sort(Comparison<T>
comparison)
public void Sort (int index,
int count, IComparer<T>
comparer)
,
,
comparer. comparer
, ,
,
,
,
comparer. ,
index,
, count.
comparer ,
,
,
, 10%
,
List<T> Capacity, ,
, .
.
public int Capacity { get; set; }
Capacity
. ,
.
, .
,
.
.
List<T> ,
IList<T>.
public this[int index] { get; set; }
, index.
List<T>. ,
ArrayList. , ,
ArrayList List,
.
964
II. C#
// List<T>.
using System;
using System.Collections.Generic;
class GenListDemo {
static void Main() {
// .
List<char> lst = new List<char>();
Console.WriteLine(" : " + lst.Count);
Console.WriteLine();
Console.WriteLine(" 6 ");
// .
lst.Add('');
lst.Add('');
lst.Add('');
lst.Add('');
lst.Add('D');
lst.Add('F');
Console.WriteLine(" : " + lst.Count);
// ,
// .
Console.Write(" : ");
for (int i=0; i < lst.Count; i++)
Console.Write(lst[i] + " ");
Console.WriteLine("\n");
Console.WriteLine(" 2 ");
// .
lst.Remove('F');
lst.Remove('');
Console.WriteLine(" : " + lst.Count);
// , foreach.
Console.Write(": ");
foreach(char in lst)
Console.Write( + " ");
Console.WriteLine("\n");
Console.WriteLine(" 20 ");
// ,
// .
for(int i=0; i < 20; i++)
lst.Add((char)('a' + i));
Console.WriteLine(" : " + lst.Capacity);
Console.WriteLine(" 20 : " +
lst.Count);
Console.Write(": ");
25. ,
965
foreach(char in lst)
Console.Write( + " ");
Console.WriteLine("\n");
// ,
// .
Console.WriteLine(" ");
lst[0] = 'X';
lst [1] = 'Y';
lst[2] = 'Z';
Console.Write(": ");
foreach(char in lst)
Console.Write( + " ");
Console.WriteLine();
// -
// .
// lst.Add(99); // , char!
}
}
, .
: 0
6
: 6
: D F
2
: 4
: D
20
: 32
20 : 24
: C E B D a b c d e f g h i j k l m n o p q r s t
: X Y Z D a b c d e f g h i j k l m n o p q r s t
LinkedList<T>
LinkedList<T>
. ICollection, ICollection<T>,
IEnumerable, IEnumerable<T>, ISerializable IDeserializationCallback.
.
LinkedList<T> .
public LinkedList()
public LinkedList(IEnumerable<T> collection)
,
, collection.
966
II. C#
, LinkedList<T>
, ,
.
LinkedListNode<T>. LinkedListNode<T>
.
public
public
public
public
Next Previous
,
. ,
. List.
Value ,
.
LinkedList<T> . . 25.16
. ,
LinkedList<T> , ,
, .
.
public LinkedListNode<T> First { get; }
public LinkedListNode<T> Last { get; }
First ,
Last .
25.16. , LinkedList<T>
public LinkedListNode<T>
AddAfter(LinkedListNode<T>
node, T value)
value
node.
node (null).
,
value
newNode
node.
node
(null). node
newNode
,
InvalidOperationException
public void
AddAfter(LinkedListNode<T>
node, LinkedListNode<T>
newNode)
public LinkedListNode<T>
AddBefore(LinkedListNode<T>
node, T value)
value
node.
node (null).
,
value
25. ,
967
. 25.16
public void
AddBefore(LinkedListNode<T>
node, LinkedListNode<T>
newNode)
public LinkedList<T>
AddFirst(T value)
public void
AddFirst(LinkedListNode
node)
public LinkedList<T>
AddLast(T value)
public void
AddLast(LinkedListNode node)
public LinkedList<T> Find(T
value)
public LinkedList<T>
FindLast(T value)
public void
Remove(LinkedList<T> node)
newNode
node.
node
(null). node
newNode
,
InvalidOperationException
value
. ,
value
node .
node ,
InvalidOperationException
value
. ,
value
node .
node ,
InvalidOperationException
,
value.
value ,
,
value.
value ,
,
value. true,
, .. value
;
false
,
node. node
,
InvalidOperationException
LinkedList<T>.
// LinkedList<T>.
using System;
using System.Collections.Generic;
968 II. C#
class GenLinkedListDemo {
static void Main() {
// .
LinkedList<char> ll = new LinkedList<char>();
Console.WriteLine(" : " + ll.Count)
Console.WriteLine();
Console.WriteLine(" 5 ");
// .
ll.AddFirst('');
ll.AddFirst('');
ll.AddFirst('');
ll.AddFirst('D');
ll.AddFirst('');
Console.WriteLine(" : " + ll.Count);
// , .
LinkedListNode<char> node;
Console.Write(" : ");
for(node = ll.First; node != null; node = node.Next)
Console.Write(node.Value + " ");
Console.WriteLine("\n");
// , foreach.
Console.Write(" foreach: ");
foreach(char ch in 11)
Console.Write(ch + " ");
Console.WriteLine("\n");
// , .
Console.Write(" : ");
for(node = ll.Last; node != null; node = node.Previous)
Console.Write(node.Value + " ");
Console.WriteLine("\n");
// .
Console.WriteLine(" 2 ");
// .
ll.Remove('');
ll.Remove('');
Console.WriteLine(" : " + ll.Count);
// foreach.
25. ,
969
Console.Write(" : ");
foreach(char ch in ll)
Console.Write(ch + " ");
Console.WriteLine("\n");
// .
ll.AddLast('X');
ll.AddLast('Y');
ll.AddLast('Z');
Console.Write(" : ");
foreach(char ch in ll)
Console.Write(ch + " ");
Console.WriteLine("\n");
}
}
.
: 0
5
: 5
: D
foreach: D
: D
2
: 3
: D
: D X Y Z
, , Next Previous.
, ,
.
Dictionary<TKey, TValue>
Dictionary<TKey, TValue> "-"
.
. Hashtable.
Dictionary<TKey, TValue> IDictionary,
IDictionary<TKey, TValue>, ICollection, ICollection<KeyValuePair<TKey,
TValue>>,
IEnumerable,
IEnumerable<KeyValuePair<TKey,
TValue>>,
ISerializable IDeserializationCallback.
. ,
.
970 II. C#
Dictionary<TKey, TValue> .
.
public Dictionary()
public Dictionary(IDictionary<TKey, TValue> dictionary)
public Dictionary(int capacity)
.
dictionary.
city , .
, , ,
, , ,
.
Dictionary<TKey, TValue> .
. 25.17.
25.17. ,
Dictionary<TKey, TValue>
-,
key value.
key ,
,
ArgumentException
true,
key
;
false
true,
value;
false
key .
true, key
false
, Dictionary<TKey, TValue>
, , , .
.
public IEqualityComparer<TKey>
Comparer { get; }
public Dictionary<TKey, TValue>.
KeyCollection Keys { get; }
public Dictionary<TKey, TValue>.
ValueCollection Values { get; }
25. ,
971
, , ,
Keys Values.
Dictionary<TKey, TValue>.KeyCollection Dictionary<TKey, TValue>.
ValueCollection ,
ICoirection IEnumerable.
, Dictionary<TKey, TValue>
, IDictionary<TKey, TValue>.
public TValue this[TKey key] { get; set; }
,
.
, .
Dictionary<TKey, TValue>
"-" KeyValuePair<TKey, TValue>.
, .
public TKey Key;
public TValue Value;
. , KeyValuePair<TKey, TValue>
, Dictionary<TKey, TValue>
.
Dictionary<TKey, TValue>, , foreach
KeyValuePair.
Dictionary<TKey, TValue>
, ,
. .
Dictionary<TKey, TValue>
.
Dictionary<TKey, TValue>.
//
// Dictionary<TKey, TValue>.
using System;
using System.Collections.Generic;
class GenDictionaryDemo {
static void Main() {
//
// .
Dictionary<string, double> dict =
new Dictionary<string, double>();
// .
diet.Add(", ", 73000);
diet.Add(", Capa", 59000);
diet.Add(", ", 45000);
diet.Add(", ", 99000);
972
II. C#
// , .. .
ICollection<string> = diet.Keys;
// , .. .
foreach(string str in )
Console.WriteLine("{0}, : {1:C}", str, diet[str]);
}
}
.
, , : $73,000.00
, , : $59,000.00
, , : $45,000.00
, , : $99,000.00
SortedDictionary<TKey, TValue>
SortedDictionary<TKey, TValue> "-"
, Dictionary<TKey, TValue>,
, .
SortedDictionary<TKey, TValue> IDictionary,
IDictionary<TKey, TValue>, ICollection, ICollection<KeyValuePair<TKey,
TValue>>, IEnumerable IEnumerable<KeyValuePair<TKey, TValue>>.
SortedDictionary<TKey, TValue> .
public
public
public
public
SortedDictionary()
SortedDictionary(IDictionary<TKey, TValue> dictionary)
SortedDictionary(IComparer<TKey> comparer)
SortedDictionary(IDictionary<TKey, TValue> dictionary,
IComparer<TKey> comparer)
,
dictionary.
comparer IComparer
, ,
, .
SortedDictionary<TKey, TValue> .
. 25.18.
25.18. ,
SortedDictionary<TKey, TValue>
"-,
key value.
key ,
,
ArgumentException
public bool ContainsKey(TKey true,
key)
key
; false
25. ,
973
. 25.18
public bool
ContainsValue(TValue value)
public bool Remove(TKey key)
true,
value;
false
key .
true,
key
false
, SortedDictionary<TKey, TValue>
, , ,
. .
974
II. C#
SortedDictionary<TKey, TValue>
, ,
. .
SortedDictionary<TKey, TValue>.
, Dictionary<TKey, TValue>.
,
.
//
// SortedDictionary<TKey, TValue>.
using System;
using System.Collections.Generic;
class GenSortedDictionaryDemo {
static void Main() {
//
// .
SortedDictionary<string, double> dict =
new SortedDictionary<string, double>();
// .
dict.Add(", ", 73000);
dict.Add(", Capa", 59000);
dict.Add(", ", 45000);
dict.Add(", ", 99000);
// , .. .
ICollection<string> = dict.Keys;
// , .. .
foreach(string str in )
Console.WriteLine("{0}, : {1:C}", str, diet[str]);
}
}
.
, , : $73,000.00
, , : $45,000.00
, , : $99,000.00
, , : $59,000.00
, ,
.
SortedList<TKey, TValue>
SortedList<TKey, TValue>
"-".
SortedList. SortedList<TKey, TValue> IDictionary,
IDictionary<TKey, TValue>, ICollection, ICollection<KeyValuePair<TKey,
TValue>>, IEnumerable IEnumerable<KeyValuePair<TKey, TValue>>.
25. ,
975
SortedList<TKey, TValue> ,
. SortedList<TKey, TValue>
SortedDictionary<TKey, TValue>, .
, SortedList<TKey, TValue> ,
SortedDictionary<TKey, TValue>
.
SortedList<TKey, TValue> .
.
public
public
public
public
SortedList()
SortedList(IDictionary<TKey, TValue> dictionary)
SortedList(int capacity)
SortedList(IComparer<TK> comparer)
.
dictionary.
capacity ,
. , ,
,
, , ,
.
comparer , .
SortedList<TKey, TValue>
, .
, .
SortedList<TKey, TValue>
.
, ,
, .
SortedList<TKey, TValue> ,
, , .
. 25.19.
, , GetEnumerator(),
"-",
KeyValuePair.
25.19. ,
SortedList<TKey, TValue>
"-,
key value.
key ,
,
ArgumentException
true,
key
; false
976
II. C#
. 25.19
public bool
ContainsValue(TValue value)
public
<TKey,
public
public
value)
public
public
public
true,
value;
false
IEnumerator<KeyValuePair
TValue>> GetEnumerator()
int IndexOfKey(TKey key)
key.
,
-1
int IndexOfValue(TValue
value .
,
-1
bool Remove(TKey key)
-
key.
true, key
false
void RemoveAt(int index) -"
index
void TrimExcess()
, SortedList<TK, TV> ,
, , .
.
, SortedList<TKey, TValue>
, IDictionary<TKey, TValueX
public TValue this[TKey key] { get; set; }
,
.
, .
SortedList<TKey, TValue>.
25. ,
977
.
SortedList.
//
// SortedList<TKey, TValue>.
using System;
using System.Collections.Generic;
class GenSLDemo {
static void Main() {
//
// .
SortedList<string, double> sl =
new SortedList<string, double>();
// .
sl.Add(", ", 73000);
sl.Add(", Capa", 59000);
sl.Add(", ", 45000);
sl.Add(", ", 99000);
// , .. .
ICollection<string> = sl.Keys;
// , .. .
foreach(string str in )
Console.WriteLine("{0}, : {1:C}", str, sl[str]);
Console.WriteLine();
}
}
.
, , : $73,000.00
, , : $45,000.00
, , : $99,000.00
, , : $59,000.00
, ,
.
Stack<T>
Stack<T>
Stack. ,
" ".
Collection, IEnumerable IEnumerable<T>. , Stack<T>
Clear(), Contains() (),
ICollection<T>. Add() Remove()
, , , IsReadOnly. Stack<T>
, ,
, . Stack<T>
.
978
II. C#
public Stack()
public Stack(int capacity)
public Stack(IEnumerable<T> collection)
, ,
city. ,
, collection.
.
Stack<T> , ,
, ,
ICollection<T>.
. 25.20. Stack,
. ,
Push(). ,
Pop(). ,
, k(). Pop() k(),
, InvalidOperationException.
25.20. , Stack<T>
public T Peek()
, ,
, ,
item
,
public T Pop()
public void Push(T item)
public T[] ToArray()
public void TrimExcess()
Stack<T>.
// Stack<T>.
using System;
using System.Collections.Generic;
class GenStackDemo {
static void Main() {
Stack<string> st = new Stack<string>();
st.Push("");
st.Push("");
st.Push("");
st.Push("");
st.Push("");
while(st.Count > 0) {
string str = st.Pop();
25. ,
979
Queue<T>
Queue<T>
Queue. ,
" ".
ICollection, IEnumerable IEnumerable<T>. , Queue<T>
Clear(), Contains() CopyTo(),
ICollection<T>. Add() Remove()
, , , IsReadOnly. Queue<T>
, ,
, . Queue<T>
.
public Queue()
public Queue(int capacity)
public Queue(IEnumerable<T> collection)
, ,
capacity. ,
, collection.
.
Queue<T> , ,
, ,
ICollection<T>.
. 25.21. Queue,
. ,
Enqueue().
, Dequeue(). ,
, k().
Dequeue() k() , ,
InvalidOperationException.
25.21. , Queue<T>
public Dequeue()
.
public void Enqueue( item) item
public T Peek()
,
980 II. C#
. 25.21
public virtual []
ToArray()
public void TrimExcess()
Queue<T>.
// Queue<T>.
using System;
using System.Collections.Generic;
class GenQueueDemo {
static void Main() {
Queue<double> q = new Queue<double>();
q.Enqueue(98.6);
q.Enqueue(212.0);
q.Enqueue(32.0);
q.Enqueue(3.1416);
double sum = 0.0;
Console.Write(" : ");
while(q.Count > 0) {
double val = q. Dequeued;
Console.Write(val + " ");
sum += val;
}
Console.WriteLine("\n " + sum);
}
}
.
: 98.6 212 32 3.1416
345.7416
HashSet<T>
HashSet<T> , .
-.
HashSet<T> ICollection<T>, ISet<T>, IEnumerable,
IEnumerable<T>, ISerializable, IDeserializationCallback.
HashSet<T> ,
. , .
. HashSet<T>
, ISet<T>,
, . HashSet<T>
,
.
25. ,
981
HashSet<T> ,
, .
,
HashSet<T>.
public
public
public
public
HashSet()
HashSet(IEnumerable<T> collection)
HashSet(IEqualityCompare comparer)
HashSet(IEnumerable<T> collection, IEqualityCompare comparer)
,
, collection.
comparer. ,
collection, comparer.
,
.
HashSet<T> ISet<T>, ,
.
RemoveWhere(), ,
, .
, ,
HashSet<T>, Comparer, .
public IEqualityComparer<T> Comparer { get; }
-.
HashSet<T>.
// HashSet<T>.
using System;
using System.Collections.Generic;
class HashSetDemo {
static void Show(string msg, HashSet<char> set) {
Console.Write(msg);
foreach(char ch in set)
Console.Write(ch + " ");
Console.WriteLine();
}
static void Main() {
HashSet<char> setA = new HashSet<char>();
HashSet<char> setB = new HashSet<char>();
setA.Addf'A');
setA.Add('B');
setA.Add('');
setB.Add('C');
setB.Add('D');
982 II. C#
setB.Add('');
Show(" setA: ", setA);
Show(" setB: ", setB);
setA.SymmetricExceptWith(setB);
Show(" setA " +
" SetB: ", setA);
setA.UnionWith(setB);
Show(" setA " +
" SetB: ", setA);
setA.ExceptWith(setB);
Show(" setA " +
" setB: ", setA);
Console.WriteLine();
}
}
.
setA: A B C
setB: D
setA SetB: D
setA SetB: D
setA setB:
SortedSet<T>
SortedSet<T> ,
4.0 .NET Framework.
, . SortedSet<T>
ISet<T>, ICollection, ICollection<T>, IEnumerable,
IEnumerable<T>, ISerializable, IDeserializationCallback.
SortedSet<T> ,
. , .
SortedSet<T> ,
ISet<T>, , .
SortedSet<T>
, SortedSet<T>
. SortedSet<T>
,
, .
,
SortedSet<T>.
public
public
public
public
SortedSet()
SortedSet(IEnumerable<T> collection)
SortedSet(IComparer comparer)
SortedSet(IEnumerable<T> collection, IComparer comparer)
25. ,
983
,
, collection.
comparer. ,
collection, comparer.
,
.
SortedSet<T> ISet<T>, ,
.
GetViewBetween(),
SortedSet<T>, RemoveWhere(), ,
, , Reverse(),
IEnumerable<T>,
.
, ,
SortedSet<T>, , .
public IComparer<T> Comparer { get; }
public T Max { get; }
public T Min { get; }
Comparer .
, Min
.
SortedSet<T>
HashSet SortedSet
, HashSet<T>.
4.0 .NET Framework System.
Collections.Concurrent. ,
.
, ,
. .
BlockingCollection<T>
IProducerConsumerCollection<T>
ConcurrentBag<T>
IProducerConsumerCollection<T>,
,
ConcurrentDictionary
"-, ,
<TKey, TValue>
ConcurrentQueue<T>
IProducerConsumerCollection<T>
ConcurrentStack<T>
IproducerConsumerCollection<T>
984
II. C#
,
IProducerConsumerCollection.
System.Collections.Concurrent.
IEnumerable, IEnumerable<T> ICollection. ,
TryAdd() TryTake(), "". ( "-"
. , .)
TryAdd() , TryTake()
. .
bool TryAdd( item)
bool TryTake(out T item)
TryAdd() true,
item. TryTake() true,
item . TryAdd() , item
. ( , IProducerConsumerCollection
(),
ICollection, ToArray(), .)
(TPL) PLINQ.
.
BlockingCollection<T>.
BlockingCollection<T>,
.
BlockingCollection<T>, ,
. ,
, ,
, .
, "-".
BlockingCollection<T> ICollection, IEnumerable,
IEnumerable<T>, IDisposable.
BlockingCollection<T> .
public
public
public
public
BlockingCollection()
BlockingCollection(int boundedCapacity)
BlockingCollection(IProducerConsumerCollection<T> collection)
BlockingCollection(IProducerConsumerCollection<T> collection,
int boundedCapacity)
BlockingCollection<T>
, ConcurrentQueue<T>.
,
BlockingCollection<T>.
boundedCapacity, ,
, .
boundedCapacity , .
TryAdd() TryTake(), ,
IProducerConsumerCollection<T>,
BlockingCollection<T> .
, .
25. ,
985
System;
System.Threading.Tasks;
System.Threading;
System.Collections.Concurrent;
class BlockingDemo {
static BlockingCollection<char> be;
// Z.
static void Producer() {
for(char ch = 'A'; ch <= 'Z'; ch++) {
be.Add(ch);
Console.WriteLine(" " + ch);
}
}
// 26 .
static void Consumer() {
for(int i=0; i < 26; i++)
Console.WriteLine(" " + bc.Take());
}
static void Main() {
// , 4 .
be = new BlockingCollection<char>(4);
// .
Task Prod = new Task(Producer);
Task Con = new Task(Consumer);
// .
Con.Start();
Prod.Start();
986
II. C#
// .
try {
Task.WaitAll(Con, Prod);
} catch(AggregateException exc) {
Console.WriteLine(exc);
} finally {
Con.Dispose();
Prod.Dispose();
bc.Dispose();
}
}
}
,
, . ,
bc 4 , ,
, .
bc
. ,
, -
. , .
.
BlockingCollection<T>
CompleteAdding(). .
public void CompleteAdding()
,
. , IsAddingComplete
true. , IsCompleted
true, () .
IsAddingComplete IsCompleted.
public bool IsCompleted { get; }
public bool IsAddingComplete { get; }
BlockingCollection<T>
, false.
CompleteAdding() true.
,
CompleteAdding(), IsCompleted
TryTake().
// CompleteAdding(), TryTake() IsCompleted.
using
using
using
using
System;
System.Threading.Tasks;
System.Threading;
System.Collections.Concurrent;
class BlockingDemo {
static BlockingCollection<char> bc;
// Z.
static void Producer() {
25. ,
987
988
II. C#
,
,
, ,
, int, string char.
.
, ,
.
ArrayList .
Inventory.
// .
using System;
using System.Collections;
class Inventory {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10}: {1,6:} : {2}",
name, cost, onhand);
}
}
class InventoryList {
static void Main() {
ArrayList inv = new ArrayList();
//
inv.Add(new
inv.Add(new
inv.Add(new
inv.Add(new
.
Inventory("", 5.95, 3));
Inventory("", 8.29, 2));
Inventory("", 3.50, 4));
Inventory("", 19.88, 8));
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
}
}
25. ,
989
.
:
: $5.95
: $8.29
: $3.50
: $19.88
:
:
:
:
3
2
4
8
,
Inventory.
object,
.
. ,
, .
, .
. List<T>,
, .
// Inventory
// List<T>.
using System;
using System.Collections.Generic;
class Inventory {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10}: {1,6:} : {2}",
name, cost, onhand);
}
}
class TypeSafeInventoryList {
static void Main() {
List<Inventory> inv = new List<Inventory>();
//
inv.Add(new
inv.Add(new
inv.Add(new
inv.Add(new
.
Inventory("", 5.95, 3));
Inventory("", 8.29, 2));
Inventory("", 3.50, 4));
Inventory("", 19.88, 8));
990
II. C#
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" + i);
}
}
}
Inventory
List<T>.
. , ,
, ,
.
: . ,
, ,
, 40 ,
. ,
,
.
, .
: . , ArrayList
List<T> Inventory.
. -, Inventory
IComparable,
. -, IComparer.
.
IComparable
,
, ,
SortedList, ,
.
, , IComparable
. IComparable :
. ,
, , , .
IComparable
,
,
IComparable.
CompareTo(), .
CompareTo().
int CompareTo(object obj)
25. ,
991
CompareTo() obj.
, ;
, obj;
, obj.
.
obj ,
CompareTo() ArgumentException.
IComparable. IComparable
Inventory,
. Inventory CompareTo() name
,
. ,
Inventory IComparable
.
// IComparable.
using System;
using System.Collections;
// IComparable.
class Inventory : IComparable {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10(: {1,6:} : {2}",
name, cost, onhand);
}
// IComparable.
public int CompareTo(object obj) {
Inventory b;
b = (Inventory) obj;
return name.CompareTo(b.name);
}
}
class IComparableDemo {
static void Main() {
ArrayList inv = new ArrayList();
// .
992
II. C#
inv.Add(new
inv.Add(new
inv.Add(new
inv.Add(new
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
Console.WriteLine();
// .
inv.Sort();
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
}
}
.
, Sort()
.
:
:
:
:
:
$5.95
$8.29
$3.50
$19.88
:
:
:
:
3
2
4
8
:
: $19.88 :
8
: $5.95 :
3
: $3.50 :
4
: $8.29 :
2
IComparable
,
,
IComparable<T>. IComparable
CompareTo().
int CompareTo ( other)
CompareTo()
other.
,
; ,
other; ,
other.
. IComparable<T>
.
25. ,
993
,
IComparable<>.
List<T> ArrayList.
// IComparable<T>.
using System;
using System.Collections.Generic;
// IComparable<T>.
class Inventory : IComparable<Inventory> {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10}: {1,6:} : {2}",
name, cost, onhand);
}
// IComparable<T>.
public int CompareTo(Inventory obj) {
return name.CompareTo(obj.name);
}
}
class GenericIComparableDemo {
static void Main() {
List<Inventory> inv = new List<Inventory>();
//
inv.Add(new
inv.Add(new
inv.Add(new
inv.Add(new
.
Inventory("", 5.95, 3));
Inventory("", 8.2 9, 2));
Inventory("", 3.50, 4));
Inventory("", 19.88, 8));
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
Console.WriteLine();
// .
inv.Sort();
Console.WriteLine(" :");
foreach(Inventory i in inv) {
994
II. C#
Console.WriteLine("
" + i);
}
}
}
, ,
.
IComparer
IComparable.
IComparer.
, IComparer,
, .
IComparer : .
,
, , , .
IComparer
IComparer
Compare().
25. ,
995
// IComparer Inventory.
class CompInv : IComparer {
// IComparer.
public int Compare(object x, object y) {
Inventory, a, b;
a = (Inventory) x;
b = (Inventory) y;
return string.Compare(a.name, b.name, StringComparison.Ordinal);
}
}
class Inventory {
public string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10} : {1,6:} : {2}",
name, cost, onhand);
}
}
class IComparerDemo {
static void Main() {
CompInv comp = new CompInv();
ArrayList inv = new ArrayList();
//
inv.Add(new
inv.Add(new
inv.Add(new
inv.Add(new
.
Inventory("", 5.95, 3));
Inventory("", 8.29, 2));
Inventory("", 3.50, 4));
Inventory ("", 19.88, 8));
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" + i);
}
Console.WriteLine();
// , IComparer.
inv.Sort(comp);
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine("
" + i);
}
}
}
, .
996
II. C#
IComparer<T>
IComparer<T> IComparer.
Compare().
int Compare( , )
,
;
, ; ,
.
, IComparer<T>.
, .
// IComparer<T>.
using System;
using System.Collections.Generic;
// IComparer<T> Inventory.
class CompInv<T> : IComparer<T> where T : Inventory {
// IComparer<T>.
public int Compare(T x, T y) {
return string.Compare(x.name, y.name, StringComparison.Ordinal);
}
}
class Inventory {
public string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-10} : {1,6:} : {2}",
name, cost, onhand);
}
}
class GenericIComparerDemo {
static void Main() {
CompInv<Inventory> comp = new CompInv<Inventory>();
List<Inventory> inv = new List<Inventory>();
// .
inv.Add(new Inventory("", 5.95, 3));
25. ,
997
StringComparer
. ,
. ,
,
, , ,
.
. ( )
IComparer.
StringComparer.
StringComparer 21
. IComparer,
IComparer<String>, IEqualityComparer, IEqualityComparer<String>.
, StringComparer
IComparer . StringComparer
,
StringComparer,
. 21,
: CurrentCulture, CurrentCultureIgnoreCase, InvariantCulture,
InvariantCultureIgnoreCase, Ordinal, OrdinalIgnoreCase.
.
, SortedList<TKey,
TValue> ,
.
SortedList<string, int> users =
new SortedList<string, int>(StringComparer.Ordinal);
998
II. C#
, ,
. ,
, foreach, ,
. ,
IEnumerator
IEnumerator<>.
IEnumerator , Current,
.
object Current { get; }
IEnumerator<T>
Current.
Current { get; }
Current
. Current ,
,
.
IEnumerator .
MoveNext(), .
bool MoveNext()
MoveNext()
.
true, , false,
. MoveNext()
Current . (
MoveNext() ,
.
MoveNext(), .)
,
, Reset().
void Reset()
Reset()
. , ,
MoveNext().
IEnumerator<T> MoveNext() Reset()
.
. -,
. ,
. -,
.
25. ,
999
,
.
GetEnumerator(), .
,
. ,
.
1. , ,
GetEnumerator().
2. , MoveNext().
, MoveNext() true.
3. Current.
, .
ArrayList,
, .
// .
using System;
using System.Collections;
class EnumeratorDemo {
static void Main() {
ArrayList list = new ArrayList(1);
for (int i=0; i < 10; i++)
list.Add(i);
// .
IEnumerator etr = list.GetEnumerator();
while(etr.MoveNext())
Console.Write(etr.Current + " ");
Console.WriteLine();
// .
etr.Reset();
while(etr.MoveNext())
Console.Write(etr.Current + " ");
Console.WriteLine();
}
}
.
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
1000
II. C#
,
foreach , .
,
.
IDictionaryEnumerator
, Hashtable,
IDictionary,
IDictionaryEnumerator IEnumerator.
IDictionaryEnumerator IEnumerator
. .
DictionaryEntry Entry { get; }
Entry "-"
DictionaryEntry. , DictionaryEntry
, Key Value,
, .
, IDictionaryEnumerator.
object Key { get; }
object Value { get; }
.
IDictionaryEnumerator
, ,
Entry, Key Value, Current. ,
IDictionaryEnumerator,
MoveNext(), .
MoveNext().
false, .
Hashtable
IDictionaryEnumerator.
// IDictionaryEnumerator.
using System;
using System.Collections;
class IDicEnumDemo {
static void Main() {
// -.
Hashtable ht = new Hashtable();
// .
ht.Add("", "555-7756");
ht.Add("", "555-9876");
ht.Add("", "555-3456");
ht.Add("", "555-3452");
25. ,
1001
// .
IDictionaryEnumerator etr = ht.GetEnumerator();
Console.WriteLine(" Entry.");
while(etr.MoveNext())
Console.WriteLine(etr.Entry.Key + ": " + etr.Entry.Value);
Console.WriteLine ();
Console.WriteLine(" " +
" Key Value.");
etr.Reset();
while(etr.MoveNext())
Console.WriteLine(etr.Key + ": " + etr.Value);
}
}
.
Entry.
: 555-9876
: 555-3456
: 555-3452
: 555-7756
Key Value.
: 555-9876
: 555-3456
: 555-3452
: 555-7756
IEnumerable IEnumerator
,
( ) foreach,
IEnumerator.
:
, , foreach,
IEnumerator IEnumerable.
,
foreach, IEnumerator IEnumerable
. , ,
.
IEnumerator
IEnumerable ,
, MyClass.
// IEnumerable IEnumerator.
using System;
using System.Collections;
1002
II. C#
25. ,
1003
MyClass,
char, -D.
idx, -1. MyClass
, IEnumerator IEnumerable. GetEnumerator()
,
. Current , .. ,
idx. MoveNext() idx
. false,
, true. ,
MoveNext().
, MoveNext() foreach
Current.
idx -1.
foreach.
.
Main() mc MyClass,
foreach.
, IEnumerator
IEnumerable . ,
, ,
. ,
, .
,
foreach.
.
,
IEnumerator IEnumerable .
// .
using System;
using System.Collections;
class MyClass {
char[] chrs = { 'A', 'B', 'C','D'};
// chrs.
public IEnumerator GetEnumerator() {
foreach(char ch in chrs)
yield return ch;
}
}
class ItrDemo {
static void Main() {
MyClass me = new MyClass();
1004
II. C#
foreach(char ch in me)
Console.Write(ch + " ");
Console.WriteLine();
}
}
.
D
, mc.chrs .
. -, ,
MyClass IEnumerator
. .
-, GetEnumerator(),
.
// chrs.
public IEnumerator GetEnumerator() {
foreach(char ch in chrs)
yield return ch;
}
MyClass. ,
GetEnumerator(), IEnumerable.
. foreach,
chrs.
yield return. ,
chrs.
mc MyClass foreach
Main().
yield C# .
, .
.
,
.
. ,
.
,
, .
for.
// ,
// .
using System;
using System.Collections;
class MyClass {
char ch = 'A';
//
// , .
25. ,
1005
yield.
yield break;
, ,
. , , .
,
.
// .
using System;
using System.Collections;
class MyClass {
char ch = 'A';
// 10 .
public IEnumerator GetEnumerator() {
for(int i=0; i < 26; i++) {
if(i == 10) yield break; //
yield return (char) (ch + i);
}
}
}
class ItrDemo3 {
static void Main() {
MyClass mc = new MyClass();
foreach(char ch in mc)
1006
II. C#
Console.Write(ch + " ");
Console.WriteLine();
}
}
.
A B C D E F G H I J
yield
yield.
.
.
// yield.
using System;
using System.Collections;
class MyClass {
// , , , D .
public IEnumerator GetEnumerator() {
yield return 'A';
yield return 'B';
yield return 'C';
yield return 'D';
yield return 'E';
}
}
class ItrDemo5 {
static void Main() {
MyClass me = new MyClass ();
foreach(char ch in mc)
Console.Write(ch + " ");
Console.WriteLine();
}
}
.
D
GetEnumerator()
yield. ,
, . ,
foreach Main() .
. .
, ,
25. ,
1007
IEnumerable.