Mc
Graw
Hill
,
,
C#.
- ,
C# , Microsoft
ET
N
ER
T
IN
:
3 !
C#
32.973.26-018.2.75
57
681.3.07
. ..
..
:
info@williamspublishing.com, http://www.williamspublishing.com
, .
57
C#. : . . . : , 2004.
752 . : . . . .
ISBN 5-8459-0563- (.)
C# ,
.NET,
: , , , , ,
, , , .
C#.
C C++, Java C#
,
, .
, C#.
32.973.26-018.2.75
.
,
, ,
Osborne Publishing.
Authorized translation from the English language edition published by McGraw-Hill
Companies, Copyright 2003
All rights reserved. No part of this book may be reproduced or transmitted in any form or
by any means, electronic or mechanical, including photocopying, recording or by any information
storage retrieval system, without permission from the Publisher.
Russian language edition published by Williams Publishing House according to the
Agreement with R&I Enterprises International, Copyright 2004
, 2004
by The McGraw-Hill Companies, 2003
I. C#
1. C#
2. C#
3. ,
4.
5.
6. ,
7.
8.
9.
10.
11.
12. ,
13.
14. -
15.
16. ,
17. ,
18. ,
II. C#
19. System
20.
21.
22.
23. Internet
III. C#
24.
25. Windows-
26.
IV.
. XML
. C#
18
21
22
30
53
80
102
126
154
179
224
256
277
319
349
375
409
431
449
484
501
502
541
575
610
645
669
670
689
707
731
732
737
740
I. C#
1. C#
C#
C,
C++
Internet Java
C#
C# .NET Framework
.NET Framework
CLR
2. C#
-
csc.exe
Visual Studio IDE
,
if
for
C#
C#
3. ,
C#
decimal
17
18
21
22
23
23
24
25
26
27
27
28
28
29
30
31
32
32
33
33
34
34
34
35
35
38
40
41
42
44
45
45
47
48
50
50
51
51
52
53
54
54
55
57
58
60
bool
4.
, ,
?
5.
if
if-
if-else-if
switch
switch
for
for
for
while
do-while
foreach
break
continue
return
goto
6. ,
61
62
65
65
66
66
68
68
69
70
72
73
74
76
78
80
81
82
84
87
89
89
90
90
96
99
99
101
101
102
103
104
105
106
110
110
112
112
114
115
116
116
117
117
119
120
120
122
123
123
126
127
127
Building
Building
Building
new
new
this
7.
Length
Length
foreach
switch-
8.
C#
public private
:
ref- out-
ref
out
ref out
128
132
133
134
134
137
138
140
142
144
144
146
146
147
148
149
149
151
154
155
155
157
158
159
159
160
161
162
164
165
167
168
172
172
173
175
177
178
179
180
180
182
182
187
189
191
191
193
195
197
199
this
Main()
Main()
Main()
static
9.
C#-
true false
,
10.
11.
base
sealed
object
object
202
203
208
212
213
213
213
215
218
223
224
225
226
228
232
236
237
240
240
242
246
250
251
256
257
257
260
263
264
266
271
271
277
278
281
283
285
286
290
291
293
296
297
301
305
305
309
313
313
315
317
12. ,
.NET Framework
:
13.
System.Exception
try- catch-
catch-
try-
finally
checked unchecked
14. -
C#- -
Stream
-
FileStream -
10
319
320
321
325
327
328
330
331
331
332
333
334
334
335
340
343
345
347
347
347
349
350
350
351
351
353
354
356
357
358
358
360
360
362
363
365
367
370
372
375
376
376
376
377
377
378
378
380
380
380
382
383
FileStream
FileStream
-
StreamWriter
Stream Reader
BinaryWriter
BinaryReader
-
MemoryStream
StringReader StringWriter
15.
System. Delegate
,
.NET Framework
EventHandler
:
16. ,
using
using
#define
#if #endif
#else #elif
#undef
#error
#warning
#line
#region #endregion
internal
internal
17. ,
is
383
385
386
387
389
389
391
392
394
394
395
396
400
402
404
405
409
410
413
415
416
416
418
419
421
425
426
428
429
431
432
432
434
436
437
438
440
441
441
442
442
444
445
446
446
446
447
447
447
449
450
450
11
as
typeof
: System.Type
GetMethods()
Attribute Usage
Conditional
Obsolete
18. ,
* &
unsafe
fixed
sizeof
lock
readonly
stackalloc
using
const volatile
II. C#
19. System
System
Math
12
451
453
454
454
455
455
458
459
462
466
471
474
474
474
475
475
477
480
480
481
482
484
485
486
486
487
487
488
489
489
491
492
492
494
494
495
496
496
496
496
497
498
499
501
502
503
504
509
510
511
Decimal
Char
Boolean
Array
BitConverter
Random
GC
Object
IComparable
IConvertible
ICloneable
IFormatProvider IFormattable
20.
C#
String
String
, String
String
String
,
Substring()
String.Format() ToString()
String.Format()
ToString()
-
21.
Thread
,
IsBackground
514
518
523
523
524
526
527
532
534
536
537
537
538
538
540
541
542
542
543
543
544
544
544
547
549
552
555
556
557
558
558
559
560
561
562
564
565
565
569
571
573
575
576
577
577
580
581
583
585
586
588
592
13
Monitor lock
Wait(), Pulse() PulseAll()
Wait() Pulse()
MethodImplAttribute
,
Abort()
Abort()
22.
ICollection
IList
IDictionary
IEnumerable, IEnumerator IDictionaryEnumerator
IComparer
IHashCodeProvider
DictionaryEntry
ArrayList
ArrayList-
Hashtable
SortedList
Stack
Queue
BitArray
IDictionaryEnumerator
,
IComparable
IComparer
23. Internet
System.Net
Internet-
WebRequest
WebResponse
HttpWebRequest HttpWebResponse
, Create()
, GetResponse()
14
593
594
594
595
598
599
601
603
604
606
606
608
608
610
611
612
612
613
614
615
615
616
616
616
617
621
622
623
625
629
631
633
636
636
637
638
639
641
642
644
645
646
647
647
648
650
650
650
653
653
654
, GetResponseStream()
URI
HTTP-
cookie-
LastModified
: MiniCrawler
WebClient
III. C#
24.
C#-
C#- COM-
IComponent
Component
CipherLib
, CipherComp
Dispose()
Dispose(bool)
using
25. Windows-
Windows-
Windows-,
Windows
Windows-
Form
Windows-,
Windows-
(IDE)
26.
654
654
656
657
658
659
660
661
665
669
670
671
671
672
672
672
673
673
674
675
676
677
678
683
684
685
686
688
689
690
691
691
692
692
692
694
694
695
695
696
696
696
697
699
700
702
706
707
708
709
15
IV.
. XML
XML
XML-
XML-
. C#
16
710
711
713
719
720
728
728
731
732
733
734
734
737
740
(Herbert Schildt)
, , C++, Java C#.
3 . .
, ,
C++, C++: A Beginner's Guide, C++ from the Ground Up, Java 2: A Beginner's Guide
Windows 2000 Programming from the Ground Up.
( . ).
: (217) 586-4683.
, - :
, .
, , ,
.
, - .
.
, .
, (, , )
. , :
. C#.
Microsoft .NET Framework, C#
.
(Anders Hejlsberg). C#
: C C++. C
, .
, C++. , C#
: Java. ,
, C# Java . ,
,
.
,
, C# ,
. , C#
, (), , .
, ;
, COM (Component Object Model
Microsoft , ,
). . Java
C# ,
. , Java, C#
. , C# C++
Java, (type
checking) (template class). ,
C# ,
( ).
,
. C# .
,
C# . ,
.
18
C# .
C# , C# .
,
.
I, C#.
II, C#.
III, C#.
I C#.
, , ,
, - ,
.
II C#.
.NET Framework.
.
.NET Framework , II
, System.
C#. , ,
.
, C#.
III C#. 24
, 25 Windows-
Windows Forms. 26
(recursive descent parser),
.
C++ Java, C# , C#
. ,
C#, ,
.
,
Visual Studio .Net 7 ( ),
.NET Framework.
- Web-
, , Web-
: www.osborne.com.
19
C# ,
. ,
.
C#
C#: A Beginner's Guide.
, C++, :
C++: A Beginner's Guide
C++
Teach Yourself C++
C++ from the Ground Up
STL Programming from the Ground Up
The C/C++ Programming Annotated Archives
, Java,
:
Java 2: A Beginner's Guide
Java
Java 2: Programmer's Reference
,
,
Teach Yourself
, , .
, ,
.
,
.
, Web-
. , ,
, ,
.
, ,
.
. :
E-mail
WWW
info@williamspublishing.com
http://www.williamspublishing.com
20
115419, , / 783
03150, , / 152
I
C#
I C#. ,
. ,
C#
(, -
),
C#.
1
C#
C# .
,
.
, , C#
.
C# ( Microsoft .NET Framework)
. C#
,
Windows, Internet, .
C# .
C# ,
,
. C# .NET Framework.
C#
. ,
.
,
,
.
. C#.
C# .
(C C++)
Java. C#.
C# .
,
.
(Dennis Ritchie) 1970- PDP-11
DEC (Digital Equipment Corporation),
UNIX. ,
Pascal, ,
C .
C 1960-
.
,
- (spaghetti code)
goto.
.
,
.
.
1. C#
23
, C ,
, , .
,
( ),
. , , ,
,
, .
1980- .
C .
.
,
.
, ,
, 5 000.
C++
1970- ,
C .
, .
- ().
, ,
. , C, ,
. - C
C++.
C++ (Bjarne Stroustrup) Bell
Laboratories ( , -), 1979-.
C , 1983
C++. C++ . , C
, C++. ,
, -
. , C++ - C.
C++ ,
. ,
- ,
- .
1980- C++ 1990-
.
,
. C++ -
.
, C++
.
. (
) ,
.
24
I. C#
Internet Java
Java, Oak ( . ).
1991 Sun Microsystems.
Java (James Gosling).
(Patrick Naughton), (Chris Warth), (Ed Frank)
(Mike Sheridan).
Java - ,
C++.
Java (
), . Internet
,
. ,
,
,
, .
Internet,
, .
, Java,
, , Java (
)
( ) ,
Java Internet,
,
. 1993
, ,
,
Internet. Internet ,
. ,
, .. Internet.
Java
, - (bytecode), .. , Java-. -
Java (Java Virtual Machine JVM) .
, Java- , JVM.
JVM ,
.
Java- - - C++,
. .
, /C++- ,
, . ,
/C++-, ,
() .
. , Java-
.
C#.
1. C#
25
, Java C C++.
, C++. Java-
C C++ , ,
, C/C++-
Java. , Java
( ),
.
C++,
Java
. , Java , C C++
.
C#
Java ,
Internet, .
(cross-language interoperability) ,
(mixed-language programming).
, ,
.
(),
, ,
.
, Java Windows.
Java- Windows (
Java), Java Windows .
Windows ,
Windows Java.
, Microsoft C#, C#
1990- .NET- Microsoft.
- 2000 . C#
(Anders Hejlsberg)
, . , 1980-
Turbo Pascal,
.
C# C, C++ Java. .
. ,
C C++, Java.
C# , ,
. ,
.
C# . 1.1. C# .
C C# , . , C#
, C++. C
C++, C# .
C# Java . , Java
C C++.
. Java C# .
C# Java. C# Java ,
,
26
I. C#
. Java, C#. ,
Java, , C#,
Java.
C++
Java
C#
. 1.1. C#
C# , .
.
C#
- . , C# ,
: ,
. -
.
C# .NET Framework
C# ,
.NET Framework. . -, C#
Microsoft ,
.NET Framework. -, ,
C#. C# .NET Framework, ,
.NET Framework ,
C#.
.NET Framework
.NET Framework
, .
,
Windows. , .NET Framework
Windows, .. , ,
, Windows.
.NET Framework C# .
, Common Language Runtime (CLR), ,
. CLR .NET
Framework, ,
.
, .NET-,
. , -,
, - , .NET-
1. C#
27
. ,
. ,
: - ,
.
, .NET- ,
(.. ), .NET-. C#
.NET- , C#-
.NET-.
CLR
CLR .NET-. .
C#- , ,
, Microsoft (Microsoft
Intermediate Language MSIL). MSIL ,
. , MSIL .
MSIL - Java, .
CLR-
. , , MSIL-,
, CLR-.
.NET Framework .
, Microsoft,
JI-. JIT . just-in-time,
(
). . .NET-
CLR- JIT-, MSIL-
, .
, C#- ,
, MSIL-. ,
,
,
MSIL-.
MSIL-
(metadata). , ,
. ,
MSIL-.
,
(managed code). CLR. ,
. , -,
28
I. C#
, MSIL-,
CLR-, , -,
.NET Framework.
, ,
,
.
? Windows-
.NET Framework , CLR. ,
C#-
.
,
CLR-, ,
,
(Common Language Specification
CLS). ,
. CLS-
, ,
. CLS-
(Common Type System CTS). CTS-
. , C# CLS-, CTS.
1. C#
29
2
C#
30
I. C#
, , ,
.
, , .
C# .
.
C#,
C#-, .
, C#.
I.
-
C# -
(). - C#,
C#- - . ,
,
.
,
.
, ,
. ,
(
) . ,
.
,
, .
(, FORTRAN COBOL),
.
,
.
, .
, ,
, - ,
.
- .
,
, .
,
- .
-
.
.
, :
(.. , , ), (.. ,
).
. ,
.
2. C#
31
- -.
, :
. -
,
. , ,
.
- , C#, : ,
.
, ()
, ,
. -
, .
.
. , , .
,
.
. ,
, .
, ( ,
) . ,
.
C# .
. , , . C#
. .
, , ,
.
, , . ,
, (instance variable), ,
, - (member method),
. , C# .
C C++, , , , , C# , C/C++- . C#
C++, ,
C#-.
( polymorphism, )
, .
. ()
,
. , :
,
. ,
.
, , , , ,
, .
32
I. C#
. , ,
(stack), .. ,
. , ,
. ,
, .
,
. -
, .
C# ,
. , ,
, .
:
. ,
. ,
. ( )
() . .
.
,
.
. ()
. ,
, ,
. ,
(, .),
. ,
(, .),
. , (
, .).
,
.
,
.
,
, ()
. ,
.
/*
*/
C#-.
C#-.
Example.cs.
2. C#
33
using System;
class Example {
// C#- Main().
public static void Main() {
Console.WriteLine(" C#-.");
}
csc.exe
, ,
Visual Studio, C#-
, . C# .
1. , .
2. .
3. .
, , Web-
Osborne : www.osborne.com.
. - ,
Notepad. ,
, ,
, C#. ,
Example.cs.
, C#-, csc.exe,
.
C:\>csc Example.cs
csc Example.exe,
MSIL- . MSIL- ,
-. Example. Common
Language Runtime JIT-. :
Example. ( -, MSIL) , .NET Framework,
CLR.
34
I. C#
csc. , ,
vcvars32.bat,
//Program Files/Microsoft Visual Studio.NET/Vc7/Bin.
. C#
Microsoft Visual Studio .NET , Visual Studio .NET Command Prompt , Visual Studio
.NET Tools , , .
.
C:\>Example
:
C#-.
2. C#
35
3. , Solution
Explorer ( ) ,
, Add , Add New Item ( ,
) , 2.2.
4. Add New Item ( )
Categories () Local Project Items
( ), Templates Code File
( ) ,
2.3.
36
I. C#
5. Example.cs. (,
, , Web-
Osborne : www.osborne.com.)
, . 2.4.
. 2.4. Example.cs
6. Build , Build Solution
( , ).
7. Debug , Start Without Debugging
( , ).
, . 2.5.
. 2.5.
,
,
. C#-.
. .
, ( )
, ,
, , .
2. C#
37
,
, Example.cs
, C#-.
, .
(, Java),
, C#-
.
Example.cs, , , Sample.cs, Test.cs X.cs.
C#- .cs,
.
, . ( ,
, ) Example.cs. C#-
,
. , .
.
/*
C#-.
*/
Example.cs.
.
C# ,
.
, ,
, .
Example.cs. ,
.
C# . ,
, .
/* , (*/). ,
, .
, , .
.
using System;
, System. C#
(namespace) .
, ,
.
, , ,
, .
System, ,
.NET Framework, C#.
38
I. C#
using ,
.
.
class,
. , C#
. Example .
({) (}) . ,
, ,
. , , C#
. , C# -.
.
// C#- Main().
, C#.
// .
,
, ()
.
.
public static void Main() {
Main(). , C#
(method).
,
. C#- Main(). (
: /C++- main().)
,
C#.
, .
public (access
specifier). ,
. public,
, , ,
. ( public
private,
, () .) Main()
public-,
( ) (
).
C#
, Main() public-.
,
Visual Studio .NET.
C#-.
Main() public.
,
Main().
static Main()
. ,
2. C#
39
Main() . void
, Main() . ,
. Main()
, . ,
Main() ( ) ,
.
((), Main().
,
.
. ,
Main().
Console.WriteLine(" C#-.");
C#-.
.
WriteLine(). , .
. ,
WriteLine() . Console
, - .
Console WriteLine(), ,
WriteLine() Console. , C#
,
- .
, , WriteLine(),
, using
System. C# .
, , ,
.
(}) Main(),
Example.
. C# .
. , Main
main WriteLine writeline,
. , C#-
, Main(), .
, Main (main),
. ,
, Example.exe .
, (
).
. ,
().
C#- -
, . ,
, .
,
40
I. C#
Main(), IDE
, 2.6.
(
csc)
. 2.6.
, ,
, .
,
,
. ,
, , . ,
,
.
.
using System;
, .
, .
, C#
, .
,
Console.WriteLine(" C#-.");
System.Console.WriteLine(" C#-.");
,
// using System.
class Example {
// C#- Main().
public static void Main() {
// Console.WriteLine .
System.Console.WriteLine(" C#-. ");
}
}
2. C#
41
System ,
, C#-
using System ( ,
). ,
, , .
,
. ,
.
. ,
, .
x y.
// .
using System;
class Example2 {
public static void Main() {
int x; // .
int y; // .
x = 100; // x 100.
:
x 100
y x / 2: 50
? ,
int x; // .
x . C#
.
, .
. x , ..
. C#
int. , int x;
x int.
y.
int y; // .
, ,
. .
, ,
:
42
I. C#
_;
,
_ . int, C#
.
x 100.
x = 100; // x 100.
C# (=).
, ,
, .
x,
x .
Console.WriteLine("x " + x);
,
x. ,
+, WriteLine()
.
y x,
2.
y = x / 2;
x 2,
y. , y
50. x .
, C#
, :
+
:
Console.Write("y x / 2: ");
Console.WriteLine(y);
. -, "y
x/2: " WriteLine(),
Write(). B
. ,
. , Write()
WriteLine(), ,
. -, ,
WriteLine() y , ..
. , WriteLine(),
Write() C#-,
,
. .
, x y
:
int x, y; // .
2. C#
43
int.
int . ,
. , int-
18, 18,3. , int
, C#. C#
, float double,
, . ( double
.)
double ,
:
double result;
result - double. result
double, , 122,23, 0,034 -19,0.
int double,
:
/*
int double.
*/
using System;
class Example3 {
public static void Main() {
int ivar; // int.
double dvar; // double.
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;
:
ivar: 100
dvar: 100
44
I. C#
ivar : 33
dvar : 33.3333333333333
, ivar 3
, 33, .. .
dvar 3 .
, ,
. ,
. , C# 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;
- :
314.16
,
.
, ,
.
, C#.
, ,
, .
if
if
. if C#
. C, C++ Java,
.
:
if() ;
2. C#
45
(
), ,
. ( )
. :
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 {
public static void Main() {
int a, b, c;
a = 2;
b = 3;
if(a < b) Console.WriteLine(" b");
// .
if(a == b) Console.WriteLine(
" .");
Console.WriteLine();
46
c = a - b; // c -1.
Console.WriteLine("c -1");
if(c >= 0) Console.WriteLine(
" c ");
if(c < 0) Console.WriteLine(" c ");
Console.WriteLine();
c = b - a; // c 1.
Console.WriteLine("c 1");
if(c >= 0) Console.WriteLine(
" c ");
if(c < 0) Console.WriteLine(" c ");
I. C#
:
b
c -1
c
c 1
c
.
int a, b, c;
,
. ,
, .
for
,
. C#
. for. C, C++
Java, , for C# ,
. for .
for(; ; ) ;
.
,
. , for
, .
, ,
. ,
for.
// for.
using System;
class ForDemo {
public static void Main() {
int count;
for(count = 0; count < 5; count = count+1)
Console.WriteLine(" : " + count);
Console.WriteLine("!");
:
: 0
: 1
: 2
: 3
: 4
!
2. C#
47
count.
for .
( ) count < 5.
, WriteLine(),
. ,
,
, .
, C#-,
, ,
. ,
, :
count = count + 1;
, C# ,
.
(++).
:
count++;
, for
:
for(count = 0; count < 5; count++)
,
, , .
C# (--). ,
.
, , C#
.
.
.
,
, . , , if-
for-. if-:
if(w < h)
{
v = w * h;
w = 0;
}
w h, , w < h,
. ,
,
. , ,
, .
.
,
.
// .
48
I. C#
using System;
class BlockDemo {
public static void Main() {
int i, j, d;
i = 5;
j = 10;
// if-
// , .
if(i != 0) {
Console.WriteLine("i ");
d = j / i;
Console.WriteLine("j / i " + d);
}
:
i
j / i 2
if- ,
. if- (
), , .
.
i = 5;
i = 0;
.
.
1 10 .
// 1 10.
using System;
class ProdSum {
static void Main() {
int prod;
int sum;
int i;
sum = 0;
prod = 1;
for(i=1; i <= 10; i++) {
sum = sum + i;
prod = prod * i;
}
Console.WriteLine(" " + sum);
Console.WriteLine(" " + prod);
:
2. C#
49
55
3628800
( ) ,
. for.
. .
, ({ })
. ,
,
.
C# , ..
.
, ,
.
,
( ).
C# ;
,
. , C#
x = y;
y = y + 1;
Console.WriteLine(x + " " + y);
.
x = y; y = y + 1; Console.WriteLine(x + " " + y);
,
. , .
Console.WriteLine(" " +
x + y + z +
" , ");
.
, , , ,
. C# ,
, .. ,
.
, .
, , ,
. ,
( ),
( ).
, .
50
I. C#
C#
C# 77 ,
. 2.1. ( )
C#.
, .
2.1. C#
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
int
interface
internal
is
lock
long
namespace
new
null
object
operator
out
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
volatile
void
while
C# , ,
, .
.
. ,
.
, line_count. C#
, .. myvar MyVar .
.
Test
x
2
MaxLoad
up
_top
my_var
sample23
, . , 12
. ,
,
, .
2. C#
51
C#
,
, @. , @fr
C#-. ,
- for, @ .
, @-.
// @-.
using System;
class IdTest {
static void Main() {
int @if; // if .
, @if
.
@if 0
@if 1
@if 2
@if 3
@if 4
@if 5
@if 6
@if 7
@if 8
@if 9
( )
@- . , @
( ),
.
C#
, ,
C#- WriteLine() Write(). ,
Console, System,
.NET Framework. , C#-
.NET Framework,
-, ,
(GUIs). , C# C# (
) .NET-. ,
C#-.
C#-,
. I .NET, .NET- II.
52
I. C#
3
,
C#: ,
. ,
. C#
, .
,
C# .
C# , C#
. , .
. ,
.
, , .
, , . ,
, . ,
, .
C#
C# :
. , .
C# 13 , . 3.1. ,
C# C#.
,
. ( :
.) , C# ,
(, C++).
.
C# .
, C# .
, int .
.
,
,
.
3.1. C#
bool
byte
char
decimal
double
, , /
8-
54
I. C#
3.1.
float
int
long
sbyte
short
uint
ulong
ushort
8-
C# : char, byte, sbyte, short,
ushort, int, uint, long ulong. char
( ).
.
. 3.2.
3.2.
byte
sbyte
short
ushort
int
uint
long
ulong
8
8
16
16
32
32
64
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# :
, .
.
, , ,
(sign flag).
, , , 1, .
.
, ,
, . ,
.
,
, ( )
. ,
32 767 short:
01111111 11111111
3. ,
55
1,
-1 ( ).
, ushort ( ),
65 535.
, int.
int ,
. ,
, int,
.
, uint (
). , ,
long, ulong. , , ,
.
,
long.
// .
using System;
class Inches {
public static void Main() {
long inches;
long miles;
miles = 93000000; // 93 000 000
//5280 , 12
inches = miles*5280* 12;
Console.WriteLine(" : " +
inches + " .");
:
: 5892480000000 .
,
int uint.
byte
sbyte. byte 0 255.
byte , ,
.
sbyte. byte for,
1 100.
// byte.
using System;
class Use_byte {
public static void Main() {
byte x;
int sum;
56
I. C#
sum = 0;
for(x = 1; x <= 100; x++)
sum = sum + x;
Console.WriteLine(" 1 100 "
+ sum);
:
1 100 5050
for 0 100 ,
byte,
, .
, ,
byte sbyte, , int uint, short
ushort.
.
: float double. float 32 ,
1,545 3,4+38.
double (.. ) 64 ,
5-324 1,7+308.
double.
double-
C# ( .NET Framework). , Sqrt(),
System.Math, double-,
double-. Sqrt()
, .
// .
using System;
class FindRadius {
public static void Main() {
double r;
double area;
area = 10.0;
r = Math.Sqrt(area / 3.1416);
Console.WriteLine(" " + r);
:
1,78412203012729
3. ,
57
,
Sqrt(): Math. , ,
, Sqrt() Math. (
WriteLine() Console.)
,
.
,
C#.
double. ,
( ) 0,1 1,0.
// Math.Sin(),
// Math.Cos() Math.Tan().
using System;
class Trigonometry {
public static void Main() {
double theta; // .
:
0,1 0,0998334166468282
0,1 0,995004165278026
0,1 0,100334672085451
0,2 0,198669330795061
0,2 0,980066577841242
0,2 0,202710035508673
0,3 0,29552020666134
0,3 0,955336489125606
0,3 0,309336249609623
,
Math.Sin(), Math.Cos() Math.Tan().
Math.Sqrt() double
double. .
decimal
, C# decimal,
, .
decimal 1E-28 7,9+28
58
I. C#
128 .
. decimal,
28 (
29).
.
, decimal
.
// decimal .
using System;
class UseDecimal {
public static void Main() {
decimal price;
decimal discount;
decimal discounted_price;
// .
price = 19.95m;
discount = 0.15m; // 15%.
discounted_price = price - (price * discount);
:
: $16,9575
, decimal-
m.
, decimal.
decimal (, 10)
m. (
.)
decimal.
,
.
/*
decimal
.
*/
using System;
class FutVal {
public static void Main() {
decimal amount;
decimal rate_of_return;
int years, i;
amount = 1000.0M;
rate_of_return = 0.07M;
years = 10;
3. ,
59
Console.WriteLine(" $"
+ amount);
:
: $1000
: 0,07
10
$1967,15135728956532249
( ) !
, , .
C# 8- ,
(, C++), 16-. C#
Unicode (), 16- ,
.
(, , , )
, (, ),
, .
, 16- .
, C# char 16- ,
065 535. 8- ASCII
Unicode 0127. , ASCII C#-.
,
. , X
ch, :
char ch;
ch = 'X';
char-, ch,
WriteLine()
Console.WriteLine(" ch: " + ch);
char C# ,
. ,
char
. , .
char ch;
ch = 10; // , .
10 ,
char.
. ,
.
60
I. C#
bool
bool /, C#
true false. ,
bool . C#
bool . , 1
true, 0 false.
bool :
// bool.
using System;
class BoolDemo {
public static void Main() {
bool b;
b = false;
Console.WriteLine("b " + b);
b = true;
Console.WriteLine("b " + b);
// bool if-.
if(b) Console.WriteLine(" .");
b = false;
if(b) Console.WriteLine(
" .");
// bool.
Console.WriteLine("10 > 9 " + (10 > 9));
}
:
b False
b True
.
10 > 9 True
, ? -, bool-
WriteLine() True False. -,
bool- if-, ..
if- .
if(b == true)...
-, (, <)
bool-. 10 > 9
True. 10 > 9, ,
, +
, >.
3. ,
61
WriteLine()
, C#. C#
,
. , -
,
. , ,
. ,
, C#.
.
:
Console.WriteLine(
" " + 2 + " $" + 3 + " .");
,
. ,
,
. :
Console.WriteLine(
" 10/3 : " + 10.0/3.0);
:
10/3 : 3,33333333333333
, ,
. ,
.
WriteLine(),
.
WriteLine("_",
arg0, arg1, ... , argN);
WriteLine()
, +. _
: .
, ,
.
:
{_, : }
_
( ).
, .
WriteLine()
, ( ) ,
_. ,
_ ,
, .
. , {0}
arg0, {1} arg1 ..
.
62
I. C#
:
1
1
1
2
4
8
3
9
27
4
16
64
5
25
125
6
36
216
7
49
343
8
64
512
9
81
729
.
, .
.
,
WriteLine(). #,
.
3. ,
63
, .
10 3.
.
Console.WriteLine(
" 10/3 : {0:#.##}", 10.0/3.0);
-:
10/3 : 3.33
#.##, WriteLine()
. ,
,
, .
.
Console.WriteLine("{0:###,###.##}", 123456.56);
:
123,456.56
,
. :
decimal balance;
balance = 12323.09m;
Console.WriteLine(" {0:C}, balance);
:
$12,323.09
, .
/*
C
.
*/
using System;
class UseDecimal {
public static void Main() {
decimal price;
decimal discount;
decimal discounted_price;
// .
price = 19.95m;
discount = 0.15m; // 15%.
, ,
:
: 16,96.
64
I. C#
C# ,
. , 100 . .
,
. .
C#- .
. ,
. , , % .
. , 10 100 .
, .
11.123. C#
( ).
C# , .
: ? ,
, 12, 123987 0.23? , C#
, .
-, ,
, , int. ,
, , int,
uint, long ulong. -, double.
, C#,
,
. long, l
L. , 12 int, 12L
long. ,
u U. , 100 int, 100U uint.
ul UL (,
987654UL ulong).
float, f F (,
10.19F).
decimal, m (, 9.
95).
int-, uint-, long-
ulong- ,
byte, sbyte, short ushort, , ,
.
, ,
16,
. 0 9 F,
10, 11, 12, 13, 14 15. ,
10 16. C#,
,
.
0x ( x). .
count = 0xFF; // 255
3. ,
65
incr = 0x1a; // 26
,
, (,
), .
, , C#
, . C#
(ESC), . 3.3.
, .
, ch :
ch = \t;
ch :
ch = \;
3.3.
ESC-
\
\b
\f
\n
\r
\t
\v
\0
\
\"
\\
()
( )
-
()
C# : .
, . ,
" "
. (
WriteLine()) .
,
. , , .
ESC-, \n, \t \".
// ESC- .
using System;
66
I. C#
class StrDemo {
public static void Main() {
Console.WriteLine(
" \n \n ");
Console.WriteLine("\t\t");
Console.WriteLine("\t\t");
// .
Console.WriteLine("\"?\", .");
}
}
:
"?", .
, \n
,
WriteLine() . ,
, ESC \n. ,
( ESC- \").
(verbatim) .
@, , .
. , ,
., .
("). ,
(""). ,
.
// .
using System;
class Verbatim {
public static void Main() {
Console.WriteLine(@"
,
.
");
Console.WriteLine(@" :
1 2 3
4
5 6 7
8
");
Console.WriteLine(
@" : "" C#.""");
}
}
:
3. ,
67
,
:
1
2
3
4
5
6
7
8
: " C#."
, ,
.
, .
.
,
.
. . (, 'X')
char. ,
(, X), - .
2,
:
_;
,
_ .
. .
, . ,
bool . ,
. ,
int char.
C# .
, ,
, ,
. C# .
. ,
, ,
, .
.
.
.
.
:
_ = ;
68
I. C#
, , ,
.
.
:
int count = 10; // count
// 10.
char ch = 'X'; // ch X.
float f = 1.2F // f
// 1.2.
(
)
. ,
int a, b = 8, c = 19, d;
// b c
// .
, C# ,
, . ,
, ,
, .
// .
using System;
class DynInit {
public static void Main() {
double s1 = 4.0, 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() (
) ,
hypot. ,
,
, , .
3. ,
69
, ,
Main(). C# .
, .
, (scope) . ,
, ,
.
.
C# ,
. ( , )
, ,
, .
, ,
. , .
, , ,
(.. ) , .
,
/ .
.
. ,
.
. , ,
, . :
, , .
,
:
// .
using System;
class ScopeDemo {
70
I. C#
, x
Main() .
if y.
, y . ,
,
// y = 100; //! y .
. ,
, y if-. x
if-,
(.. ) ,
.
,
. ,
, . ,
, ,
.
,
. ,
. , , ,
. ,
, .
, .
,
, .
, , :
// .
using System;
class VarInitDemo {
public static void Main() {
int x;
:
y : -1
y : 100
y : -1
y : 100
y : -1
y : 100
3. ,
71
, for y
1. 100,
.
:
, , ,
, ,
. , -
.
/*
, ,
.
*** . ***
*/
using System;
class NestVar {
C/C++, ,
, ,
. , C/C++ count
for .
. C#,
, ,
.
. , ,
float int.
int i;
float f;
i = 10;
f = i; //float- int-.
,
( )
. , ,
72
I. C#
int- i, float,
f. , C#
, .
, bool int . ,
-
. .
,
;
(.. ),
.
,
. , int ,
byte, int, byte
, .
,
, . ,
, long double
, .
//
// long double.
using System;
class LtoD {
public static void Main() {
long L;
double D;
L = 100123285L;
D = L;
long
double, ( double long)
, . ,
:
// *** . ***
using System;
class LtoD {
public static void Main() {
long L;
double D;
D = 100123285.0;
L = D; // !!!
3. ,
73
decimal float ( double),
char ( bool). , char bool.
,
.
.
.
:
(_)
_
. , , x/y int,
:
double x, y;
// ...
(int) (x / y);
, , x y double,
int. ,
x / y, . (
) int
x, .
,
double int .
,
. , long int
, long ,
int, long.
. ,
1,23
1. (0,23) .
,
,
.
// .
using System;
class CastDemo {
public static void Main() {
double x, y;
byte b;
int i;
char ch;
uint u;
74
I. C#
short s;
long l;
x = 10.0;
y = 3.0;
// double int.
i = (int) (x / y); // .
Console.WriteLine(
" x / y: " + 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("u -12: " + u +
" -- .");
Console.WriteLine();
// byte char.
b = 88; // ASCII- X.
ch = (char) b;
Console.WriteLine("ch 88: " + ch);
3. ,
75
:
x/y: 3
b 255: 255 -- .
b 257: 1 -- .
s 32000: 32000 -- .
s 64000: -1536 -- .
u 64000: 64000 -- .
u -12: 4294 967284 -- .
ch 88: X
.
(x / y) int , ..
.
, b
255, byte
255. b 257 ,
257
byte. ,
int byte .
s short 32 000 (
u uint) , short-
32 000. ,
64 000 short,
.
, uint
short .
u ( uint) 64 000 (
l long). ,
64 000 uint-.
u -12, , , uint
.
, long
uint .
, byte- char
, .. ,
.
,
. ,
. , short long,
.
,
.
. .
76
I. C#
decimal, TO , ..
decimal ( float double,
).
double, TO
double.
float, TO
float.
ulong, TO
ulong ( sbyte, short, int long,
).
long, TO
long.
uint, sbyte, short int,
long.
uint, TO
uint.
int.
. - .
, float double
decimal. ulong
. - ,
.
-, . ,
int,
. , char-, sbyte-, byte-, ushort-
short- int.
int- (integer
promotion). ,
int.
, ,
. ,
byte int,
- byte.
.
. ,
, byte-.
. byte-
int, ,
int. , byte-
byte- int-.
. :
// !
using System;
class PromDemo {
public static void Main() {
byte b;
3. ,
77
b = 10;
b = (byte) (b * b); // )!!
, b * b
b . , b * b
b int, .. b * b
int-, byte-
. , ,
, , ,
.
char. ,
- char int .
char ch1 = 'a', ch2 = 'b';
ch1 = (char) (ch1 + ch2);
ch1 ch2 int,
int- char-.
(, ). ,
int (.. sbyte-, byte-, short- ushort-),
int. To char. ,
uint- long.
,
.
. , , .
1 10.
.
,
Math.Sqrt() int.
// .
using System;
class CastExpr {
public 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(
78
I. C#
" : {0}",
Math.Sqrt(n) - (int) Math.Sqrt(n) );
}
}
Console.WriteLine();
:
1 1
: 1
: 0
2 1,4142135623731
: 1
: 0,414213562373095
3 1,73205080756888
: 1
: 0,732050807568877
4 2
: 2
: 0
5 2,23606797749979
: 2
: 0,23606797749979
6 2,44948974278318
: 2
: 0,449489742783178
7 2,64575131106459
: 2
: 0,645751311064591
8 2,82842712474619
: 2
: 0,82842712474619
9 3
: 3
: 0
10 3,16227766016938
: 3
: 0,16227766016838
, ,
Math.Sqrt(), int,
.
( ,
):
Math.Sqrt(n) - (int) Math.Sqrt(n)
double. int
Math.Sqrt().
3. ,
79
C# ,
. C# : , ,
.
?. C#
, , .
C# .
+
*
/
%
-++
C#- +, -, * /
( , ).
.
,
, .
, (/)
. , 10/3 3.
(%).
, :
. , 10 % 3 1. C# %
, . , 10,0 % 3,0
1. ( C/C++
.)
.
// %.
using System;
class ModDemo {
public static void Main() {
int iresult, irem;
double dresult, drem;
iresult =10/3;
irem = 10 % 3;
dresult = 10.0 / 3.0;
drem = 10.0 % 3.0;
4.
81
Console.WriteLine(
" 10/3: " +
iresult + " " + irem);
Console.WriteLine(
" 10.0 / 3.0: " +
dresult + " " + drem);
:
10 / 3: 3 1
10.0 / 3.0: 3,33333333333333 1
, % , 1,
, .
(++) (--)
, . ,
, .
, 1,
1 . ,
x = x + 1;
:
x++;
x = x - 1;
:
x--;
,
. ,
x = x + 1;
++x; // .
:
x++; // .
,
: .
,
. , C#
, ,
. , C#
, ,
. :
x = 10;
y = ++x;
82
I. C#
y 11.
, y
10:
x = 10;
y = x++;
x 11. ,
11 ( y ).
. ,
:
/*
++.
*/
using System;
class PrePostDemo {
public static void Main() {
int x, y;
int i;
x = 1;
Console.WriteLine(
", y = x + x++;");
for(i = 0; i < 10; i++) {
y = x + x++; // ++
Console.WriteLine(y + " ");
}
Console.WriteLine();
x = 1;
Console.WriteLine(
", y = x + ++x;");
for(i = 0; i < 10; i++) {
y = x + ++x; // ++
Console.WriteLine(y + " ");
}
Console.WriteLine();
:
, y = x + x++;
2
4
6
8
10
12
14
4.
83
16
18
20
, y = x + ++x;
3
5
7
9
11
13
15
17
19
21
,
y = x + x++;
x x, y.
x.
y = x + ++x;
-. ( )
x, , ,
y. ,
x++ ++x , ,
. .
x + ++x;
, .
,
. , x
x.
(/)
,
.
/ - , .
.
, .
==
!=
>
<
>=
<=
84
I. C#
&
|
^
&&
||
!
bool.
C# (,
== !=) . , <, >, <= >=,
, .
, .
bool ,
true false . , C# true > false
.
, bool,
bool. &, |, ^
! , ,
.
p
false
true
false
true
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
,
, .
,
.
//
// .
using System;
class RelLogOps {
public 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");
if(i == j) Console.WriteLine(" .");
4.
85
if(i
if(i
b1 =
b2 =
if(b1 &
if(!(b1
if(b1 |
if(b1 ^
:
i < j
i <= j
i != j
!(b1 & b2) --
b1 | b2 --
b1 ^ b2 --
. ,
.
C#. , C# ,
,
. ,
, , .
( , .)
:
p
p q
true
true
false
false
true
false
false
true
true
false
true
true
, ! |.
!p | q
:
// C#.
using System;
class Implication {
public static void Main() {
bool p = false, q = false;
int i, j;
for(i =0; i < 2; i++) {
for(j =0; j < 2; j++) {
if(i==0) p = true;
if(i==1) p = false;
if(j==0) q = true;
if(j==1) q = false;
86
I. C#
Console.WriteLine(
"p " + p + ", q " + q);
if(!p | q)
Console.WriteLine(" " +
p + " " + q + " " + true);
Console.WriteLine();
:
p True, q True
True True True
p True, q False
p False, q True
False True True
p False, q False
False False True
C# (short-circuit)
, .
, , ,
, .
, ,
. ,
. ,
.
&&,
|| ( & |,
).
,
,
.
,
. , d
n. . d / n
, , d n. ,
.
//
using System;
class SCops {
public static void Main() {
int n, d;
n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
4.
87
/*
.
( ). */
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " -- " + n);
, if
d . ,
. ,
d 2, .
( d ) ,
, .
,
, .
, :
C# ?.
, , ,
. ,
:
// .
using System;
class SideEffects {
public static void Main() {
int i;
i = 0;
88
/* i , ,
. */
if(false & (++i < 100))
Console.WriteLine(" .");
Console.WriteLine(
" if : " + i); // : 1
/* i ,
. */
if(false && (++i < 100))
Console.WriteLine(" .");
Console.WriteLine(
" if : " + i); // - 1 !!
I. C#
, if- i
if-.
if-
i , false.
.
/,
, , , .
.
, .
2.
.
(=). C# ,
.
.
= ;
. ,
. , , .
int x, y, z; x = y = z = 100;// x, y
// z 100.
x, y z 100
. ,
. ,
z = 100 100, y,
x.
( )
.
C# ,
.
. :
x = x + 10;
, :
x += 10;
+= x
x 10. .
x = x - 100;
:
x -= 100;
x ,
100.
4.
89
(.. , ).
:
op = ;
op ,
.
.
+=
-=
*=
/=
%=
&=
|=
^=
,
.
. , . -,
(
).
.
C# ,
C#.
.
bool, float double.
,
(), .
, ,
. . 4.1.
4.1.
&
|
^
>>
<<
~
1 ( )
, ,
, ,
&, |, ^ ~, . ,
, . ,
.
( ).
90
I. C#
p&q
p|q
p^q
~p
0
1
0
1
0
0
1
1
0
0
0
1
0
1
1
1
0
1
1
0
1
0
1
0
. , 0 0
. :
1101 0011
1010 1010
& ________
1000 0010
&
.
( ) . , 9
0000 1001. 8
(0000 1000 ).
//
// "" .
using System;
class MakeEven {
public static void Main() {
ushort num;
ushort i;
for(i = 1; i <= 10; i++) {
num = i;
Console.WriteLine("num: " + num);
num = (ushort) (num & 0xFFFE); // num & 1111 1110
Console.WriteLine("num : "
+ num + "\n");
}
}
}
:
num: 1
num : 0
num: 2
num : 2
num: 3
num : 2
num: 4
num : 4
num: 5
4.
91
num : 4
num: 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 & 0xFFFE
, .
, , ,
( ).
. ,
, .
//
// , .
using System;
class IsOdd {
public static void Main() {
ushort num;
num = 10;
if((num & 1) == 1)
Console.WriteLine(" .");
num = 11;
if((num & 1) == 1)
Console.WriteLine(num + " -- .");
}
}
:
11 -- .
if num
1. num (.. ),
num & 1 .
. if ,
.
,
&, ,
byte .
.
92
I. C#
// , .
using System;
class ShowBits {
public static void Main() {
int t;
byte val;
val = 123;
:
01111011
for
val. , ,
1, 0.
, ,
.
, 1, ,
. :
1101 0011
1010 1010
| ________
1111 1011
.
//
// "" .
using System;
class MakeOdd {
public static void Main() {
ushort num;
ushort i;
4.
93
:
num: 1
num : 1
num: 2
num : 3
num: 3
num : 3
num: 4
num : 5
num: 5
num : 5
num:
num : 7
num: 7
num : 7
num: 8
num : 9
num: 9
num : 9
num: 10
num : 11
, for, 1,
0000 0001. , 1 ,
.
,
, (
). , , ,
, .. .
(XOR)
, ,
.. . :
0111 1111
1011 1001
^ ________
1100 0110
XOR ,
. XOR
X Y, XOR
Y, X. ,
R1 = X ^ Y;
R2 = R1 ^ Y;
R2 X. ,
XOR, (Y),
(X).
94
I. C#
,
, .
,
. :
// XOR
// .
using System;
class Encode {
public 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!
: >1
: Hi!
, XOR,
, () .
( 1)
. , (
), 1001 0110, ~
0110 1001.
1 .
// .
using System;
class NotDemo {
public static void Main() {
4.
95
sbyte b = -34;
int t;
for(t = 128; t > 0; t = t/2) {
if((b & t) != 0) Console.Write("1 ");
if((b & t) == 0) Console.Write("0 "); }
Console.WriteLine();
// .
b = (sbyte) ~b;
:
11011110
00100001
C# .
C# :
<<
;
>>
.
:
<< _;
>> _.
, _ ,
.
, ,
, .
, , . ,
.
, . :
. ,
,
, .
, . ,
, .
,
. , ,
, .. 1,
0.
.
, .
val 1, 128, 1000 0000. ,
, , .
96
I. C#
// << >>.
using System;
class ShiftDemo {
public static void Main() {
int val = 1;
int t;
int i;
for(i = 0; i < 8; i++) {
for(t = 128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val << 1; // .
}
Console.WriteLine();
val = 128;
for(i = 0; i < 8; i++) {
for(t = 128; t > 0; t = t/2) {
if((val & t) != 0) Console.Write("1 ");
if((val & t) == 0) Console.Write("0 ");
}
Console.WriteLine();
val = val >> 1; // .
}
}
}
:
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
1
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0 0 0 0 0 0
0 0 0 0 0 0
1 0 0 0 0 0
0 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
2,
2. .
. , ,
( ) . :
//
// 2.
4.
97
using System;
class MultDiv {
public static void Main() {
int n;
n = 10;
Console.WriteLine(" n: " + n);
// 2.
n = n << 1;
Console.WriteLine(
" n n = n * 2: " + n);
// 4.
n = n << 2;
Console.WriteLine(
" n n = n * 4: " + n);
// 2.
n = n >> 1;
Console.WriteLine(
" n n = n / 2: " + n);
// 4.
n = n >> 2;
Console.WriteLine(
" n n = n / 4: " + n);
Console.WriteLine();
// n .
n = 10;
Console.WriteLine(" n: " + n);
// 2, 30 .
n = n << 30; // ; .
Console.WriteLine(
" n 30 : " + n);
:
n: 10
n n = n * 2: 20
n n = n * 4: 80
n n = n / 2: 40
n n = n / 4: 10
n: 10
n 30 : -2147483648
.
10 30 (.. 230)
,
, int.
,
98
I. C#
, int .
.
,
2. ( ,
, 3.)
, . ,
x
(XOR) x 127.
x = x ^ 127;
x ^= 127;
?
C# ?.
? if-thenelse. ? , .
:
1 ? 2 : 3;
1 bool. 2
3 .
.
?- .
1. , 2,
?-.
1 , ?-
3. , absval
val.
absval = val < 0 ? -val : val;
//
// val.
absval val,
. val ,
absval ,
.
?.
100 ,
.
// ?
using System;
class NoZeroDiv {
public static void Main() {
int result;
int i;
4.
99
.
/ -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 .
( i = 0) result .
,
?. ,
, . . ,
?, bool,
if.
, , ,
( ).
// ?-.
100
100
100
100
100
100
100
100
100
100
using System;
class NoZeroDiv2 {
public static void Main() {
int i;
if. i ,
if- false,
, , .
( ) .
100
I. C#
C# (
). , ,
:
=10/y*(127/x);
x = 10 / y * (127/x);
( , ) ,
.
. ,
, ! (
, , )
. , ,
?
x = y/3-34*temp+127;
X = (y/3) - (34*temp) + 127;
. 4.2 C#- (
). , .
4.2. C#-
4.
101
C#. :
(if, switch), ( for-, while-, do-while foreach-) (break, continue, goto, return throw).
throw, C#-
( 13),
.
if
if 2,
. :
if() ;
else ;
C#.
else .
. if- :
if() {
}
else
{
}
, ,
, if-;
else- ( ). .
, if-, bool.
, if-else-
, .
// ,
// .
using System;
class PosNeg {
public static void Main() {
int i;
for(i=-5; i <= 5; i++) {
Console.Write(" " + i + ": ");
if(i < 0) Console.WriteLine(" ");
else Console.WriteLine(" ");
}
}
}
5.
103
:
-5:
-4:
-3:
-2:
-1:
0:
1:
2:
3:
4:
5:
, i ,
if- ( : );
else- ( : ).
.
if-
if- ,
(. ) if-.
if- . ,
else- if-,
, else-.
:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d;
else a = c; // else-
// if(k > 100).
}
else a = d; // else- if(i == 10).
, else-
if(j < 20), (
if- , else-).
else- if(k > 100),
.
.
. ,
else-,
: .
// , ,
// .
using System;
class PosNegZero {
public static void Main() {
int i;
for(i=-5; i <= 5; i++) {
104
I. C#
:
-5:
-4:
-3:
-2:
-1:
0:
1:
2:
3:
4:
5:
if-else-if
,
if-, if-else-if.
:
if()
;
else if()
;
else if()
;
.
.
.
else
;
.
. -
, , ,
. , ,
else- ( , ,
). else- ,
, .
if-else-if- ,
{
).
// ,
// .
using System;
5.
105
class Ladder {
public static void Main() {
int num;
for(num = 2; num < 12; num++) {
if((num % 2) == 0)
Console.WriteLine(" " +
num + " 2.");
else if((num % 3) == 0)
Console.WriteLine(" " +
num + " 3.");
else if((num % 5) == 0)
Console.WriteLine(" " +
num + " 5.");
else if((num % 7) ==0)
Console.WriteLine(" " +
num + " 7.");
else
Console.WriteLine(num +
" 2, 3, 5 7.");
}
}
}
:
2 2.
3 3.
4 2.
5 5.
6 2.
7 7.
8 2.
9 3.
10 2.
11 2, 3, 5 7.
, else- ,
if-.
switch
switch. switch
.
.
if-, switch
. .
.
, .
switch :
switch{) {
case 1:
break;
case 2:
106
I. C#
break;
case 3:
break;
default:
break;
}
switch
(, char, byte, short int) string (
). , , .
switch- ; case ,
. case- switch-
.
default- ,
case- switch. default . ,
case- .
- , ,
case- , break.
switch- .
// switch.
using System;
class SwitchDemo {
public 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;
5.
.");
.");
.");
.");
.");
.");
107
:
.
.
.
.
.
.
.
.
.
.
, ,
case-, x.
. i , default.
switch- int. ,
, switch-
, char.
case- char- char-.
// char
// switch-.
i
i
i
i
i
i
i
i
i
i
using System;
class SwitchDemo2 {
public static void Main() {
char ch;
for(ch='A'; ch<= 'E'; ch++)
switch(ch) {
case 'A':
Console. WriteLine("ch ");
break;
case 'B':
Console.WriteLine("ch ");
break;
case 'C':
Console.WriteLine("ch ");
break;
case 'D':
Console.WriteLine("ch D");
break;
case 'E':
Console.WriteLine("ch ");
break;
}
}
}
:
ch A
ch B
108
I. C#
ch C
ch D
ch E
, default-
. , . ,
.
C# , ,
case-, , .
, ,
. case-
break. ( ,
goto, , break
.) break,
case-, switch
, switch.
default-
break.
C# , C++ Java. case-
, case-, ..
. C#
. -,
case-, ,
case- . -,
case-
,
.
case , , ,
, case
.
// "" case- "".
using System;
class EmptyCasesCanFall {
public static void Main() {
int i;
5.
109
:
1, 2 3
1, 2 3
1, 2 3
4
, i 1, 2 3,
WriteLine(), i 4, .
case- ,
case- .
case-
case-,
.
i
i
i
i
switch
switch case-
switch.
switch. , case-
switch , .
, :
switch(ch1) {
case 'A':
Console.WriteLine(
" - switch.");
switch(ch2) {
case 'A':
Console.WriteLine(
" - switch.");
break;
case '': // ...
} // switch.
break;
case '': // ...
for
2, for.
, ,
. . ,
for
:
for(; ; ) ;
for ,
:
for(; ; ) {
}
,
.
110
I. C#
, .
bool,
. ,
for . ,
,
. , for
. for ,
. ,
, for.
for ,
,
. , 100 -100
, 5.
// for
// .
using System;
class DecrFor {
public 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 . (count
< 5) .
.
for ,
. , for
2 20. ,
.
/*
. ,
. */
using System;
class FindPrimes {
public static void Main() {
int num;
int i;
int factor;
bool isprime;
for(num = 2; num < 20; num++) {
5.
111
isprime = true;
factor = 0;
// , num i .
for(i=2; i <= num/2; i++) {
if((num % i) == 0) {
// num i ,
// num .
isprime = false;
factor = i;
}
}
if(isprime)
Console.WriteLine(num + " .");
else
Console.WriteLine(" " +
num + " " + factor);
}
:
2 .
3 .
4 2
5 .
6 3
7 .
8 4
9 3
10 5
11 .
12 6
13 .
14 7
15 5
16 8
17 .
18 9
19 .
for
for C#,
.
for .
. :
// for.
using System;
class Comma {
112
I. C#
5.
113
: 50
: 2
for
, .
i.
2 ,
( num).
j.
, num,
, . ,
i j .
.
, for,
, bool. ,
done.
// bool.
using System;
class forDemo {
public 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);
:
j: 0 100
j: 1 99
j: 2 98
j: 3 97
j: 4 96
j: 5 95
j: 6 94
j: 7 93
j: 8 92
j: 9 91
j: 10 90
for , bool- done
true. true ,
i j .
i,
i,
i,
i,
i,
i,
i,
i,
i,
i,
i,
114
I. C#
C# (, ,
) .
. :
// for .
using System;
class Empty {
public 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 {
public static void Main() {
int i;
i = 0; // .
i for,
.
for.
5.
115
, , ,
, .
for,
(, ). ,
, C#-
.
for(;;) // .
{
// ...
}
.
(, ),
,
.
, . (: break.)
C# , for ( - ),
. , .
. ,
1 5.
// .
using System;
class Empty3 {
public static void Main() {
int i;
int sum = 0;
// 1 5.
for(i =1; i <= 5; sum += i++);
:
15
,
for, .
:
sum += i++
, .
, .
, sum
sum i,
116
I. C#
i. , :
sum = sum + i;
for
, for,
.
. , ,
1 5. i for.
// for.
using System;
class ForVar {
public static void Main() {
int sum = 0;
int fact = 1;
// 1 5.
for(int i = 1; i <= 5; i++) {
sum += i; // i .
fact *= i;
}
// i .
Console.WriteLine(" " + sum);
Console.WriteLine(" " + fact);
for :
. ,
for.
. , i
for.
- , for.
,
for.
while
while :
while();
,
. ,
bool. ,
.
, , .
5.
117
, while
.
// .
using System;
class WhileDemo {
public static void Main() {
int num;
int mag;
num = 435679;
mag = 0;
Console.WriteLine(": " + num);
while(num > 0) {
mag++;
num = num / 10;
};
Console.WriteLine(": " + mag);
:
: 435679 : 6
while . num.
, mag , num 10.
, num . num ,
, mag .
for, while, a
, .
( )
.
// 2.
using System;
class Power {
public 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);
118
I. C#
:
0 1
1 2
2 3
3 4
4 16
5 32
6 64
7 128
8 256
9 512
, while ,
. , ,
for, while .
2
2
2
2
2
2
2
2
2
2
do-while
C# do-while. for while,
, do-while
. , do-while .
:
do {
;
} while();
,
,
do-while, while.
do-while , ,
.
do-while
, .
// .
using System;
class DoWhileDemo {
public static void Main() {
int num;
int nextdigit;
num = 198;
Console.WriteLine(": " + num);
Console.Write(" : ");
do {
nextdigit = num % 10;
Console.Write(nextdigit);
5.
119
Console.WriteLine();
:
: 198 : 891
.
10.
.
num. ,
. , num
.
foreach
foreach .
. C# ,
. foreach 7, .
break
break ,
, , .
break ,
, . .
// break .
using System;
class BreakDemo {
public static void Main() {
// break .
for(int i=-10; i <= 10; i++) {
if(i > 0) break; // i > 0.
Console.Write(i + " ");
}
Console.WriteLine("!");
:
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 !
120
I. C#
, , for
i 10 10, break ,
i .
break C#-,
. , , dowhile-, :
// break
// do-while.
using System;
class BreakDemo2 {
public static void Main() {
int i;
i = -10;
do {
if(i > 0) break;
Console.Write(i + " ");
i++;
}
while(i <= 10);
Console.WriteLine("!");
.
.
// .
using System;
class FindSmallestFactor {
public static void Main() {
int factor = 1;
int num = 1000;
for(int i=2; i < num/2; i++) {
if((num%i) == 0) {
factor = i;
break; // , .
}
}
Console.WriteLine(
" " + factor);
}
}
:
2
break for,
.
.
break
.
5.
121
// break .
using System;
class BreakNested {
public 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
: 0123456789
: 1
: 0123456789
: 2
: 0123456789
.
, break, ,
, .
,
, break,
. . break,
switch, switch,
.
continue
,
. continue.
,
. continue
break. ,
continue 0 100.
// continue.
using System;
122
I. C#
class ContDemo {
public static void Main() {
// 0 100.
for(int i = 0; i <= 100; i++) {
if((i%2) != 0) continue;
//
// .
Console.WriteLine(i);
}
}
}
,
, WriteLine()
.
while do-while continue
, ,
. for
continue , .
.
continue ,
.
return
return .
. . 6.
goto
goto C#- .
, .
, ,
, -. goto -
, .
. , , (
) goto,
, .
.
goto , ,
,
. goto
,
.
goto .
C# , .
goto, . , goto
100 :
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
5.
123
// goto case 1; // !
// switch.
:
case 1
case 3
default
case 2
case 1
case 3
default
case 3
default
default
, goto
case default switch. , case break. goto
case-
case,
124
I. C#
(break) . ,
goto switch-.
// goto case 1; // !...
. goto
switch ,
,
goto
. :
// goto.
using System;
class Use_goto {
public 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 0
i, j, k; 0 0 1
i, j, k: 0 0 2
i, j, k: 0 0 3
, ! i, j, k: 0, 0, 3
, goto,
if break. goto
.
, , , ,
goto .
5.
125
6
,
. C#,
. , C#.
-
C#. , .
. , ,
C#,
.
C#- ,
. , ,
. ,
, .
, . , .
, , . C#
. .
, (), ,
. : .
, ,
.
. , , ,
.
, , , ,
.
, ,
.
, ,
. ,
-, ,
, , , , , .
,
.
.
class.
, ,
:
class _ {
// .
1;
2;
//...
N;
// .
_ 1() {
//
}
6. ,
127
_ 2() {
//
}
_ N() {
//
}
}
,
.
(, public), , .
2,
. , .
, , , ,
(private). ( )
.
public-, ,
, , .
8.
( ), ,
. , ,
, ( )
,
. ,
. ,
, .
, ,
Main(). , . ,
Main() . ,
.
,
(, , .). ( Building)
( ,
).
Building.
: floors, area occupants. ,
Building .
. ( .)
class Building {
public int floors; //
public int area; //
public int occupants; //
}
, Building,
. :
_;
128
I. C#
,
, _ .
, ,
, . Building
public, , ,
,
Building.
class .
Building.
Building. , class ;
. ,
Building.
Building, , ,
:
Building house = new Building();
//
// Building.
house Building,
.. . .
,
, .
, Building
floors, area occupants.
(.).
. :
.
, , .
, floors 2,
.
house.floors = 2;
, .
, Building.
// , Building.
using System;
class Building {
public int floors; //
public int area; //
public int occupants; //
}
// Building.
class BuildingDemo {
public static void Main() {
Building house = new Building();
//
// Building.
int areaPP; // , .
// house.
house.occupants = 4;
house.area = 2500;
house.floors = 2;
6. ,
129
// , .
areaPP = house.area / house.occupants;
Console.WriteLine(
" :\n " +
house.floors + " \n " +
house.occupants + " \n " +
house.area +
" , \n "
+ areaPP + " ");
: Building BuildingDemo.
BuildingDemo Main() Building
house, house,
.
, Building BuildingDemo .
, .
, BuildingDemo
Building, , .. public-.
public,
Building, BuildingDemo
.
UseBuilding.cs,
UseBuilding.exe. Building BuildingDemo
.
:
:
2
4
2500 ,
625
Building BuildingDemo
.
Building.cs BuildingDemo.cs, .
.
:
csc Building.cs BuildingDemo.cs
Visual Studio IDE,
.
,
:
, . ,
.
, ,
. , Building
floors, area occupants,
() .
.
// Building.
using System;
130
I. C#
class Building {
public int floors; //
public int area; //
public int occupants; //
}
// Building.
class BuildingDemo {
public static void Main() {
Building house = new Building();
Building office = new 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 + " ");
Console.WriteLine();
// ,
// .
areaPP = office.area / office.occupants;
Console.WriteLine(" :\n " +
office.floors + " \n " +
office.occupants + " \n " +
office.area +
" , \n " +
areaPP + " ");
:
:
2
4
2500 ,
625
:
3
25
4200 ,
168
6. ,
131
, ( house)
( office). .
6.1.
house
office
floors
area
2500
occupants
floors
area
4200
occupants
25
. 6.1.
Building. Building house = new Building();
. -,
house Building. ,
. -,
house .
new. ,
house Building.
new (.. )
. (
) , new.
, C# .
, ,
.
Building house; // .
house = new Building();
//
// Building.
house
Building. house , ,
. ( ) house
null, , .
Building,
house. house .
, ,
, .
132
I. C#
,
. . ,
int x; x = 10;
x 10, x 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;
,
Console.WriteLine(house1.area);
Console.WriteLine(house2.area);
2600.
, house1 house2,
, . ,
house2 , .
Building house1 = new Building();
Building house2 = house1;
Building house3 = new Building();
Building house2 = house3;
// house2
// house3
// .
house2 ,
house3. , house1, .
6. ,
133
,
. Building .
( ) , .
(), ,
, .
.
. C#-
. ,
. .
, Main() ,
. , C#.
.
, getval, getval().
.
:
_ (_) {
//
}
, ,
. ,
, , , , (private)
, . public, ,
, .
_ ,
. , ,
. ,
void. , , .
, ,
. _
( ), .
, , .
, _ .
Building
, , , ,
, . , ,
Main() ,
, .
,
. , ,
Building,
area occupants, Building.
, Building
134
I. C#
. , ,
, , .
,
. , 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 {
public static void Main() {
Building house = new Building();
Building office = new Building();
// house.
house.occupants = 4;
house.area = 2500;
house.floors = 2;
// office.
office.occupants = 25;
office.area = 4200;
office.floors = 3;
Console.WriteLine(" :\n " +
house.floors + " \n " +
house.occupants + " \n " +
house.area +
" , ");
house.areaPerPerson();
Console.WriteLine();
Console.WriteLine(" :\n " +
6. ,
135
office.areaPerPerson();
, :
:
2
4
2500 ,
625
:
3
25
4200 ,
168
,
areaPerPerson(). :
public void areaPerPerson() {
areaPerPerson(),
. public,
.
areaPerPerson() void, ..
. ,
.
. areaPerPerson() :
Console.WriteLine(" " + area / occupants +
" ");
, ,
area occupants.
Building area
occupants, areaPerPerson() ,
, ,
.
areaPerPerson() , ..
.
Main():
house.areaPerPerson();
areaPerPerson() house.
, , .
,
,
, .
house.areaPerPerson()
, , ,
house. office.areaPerPerson()
, , ,
136
I. C#
office. , ,
areaPerPerson(), ,
, , .
. area occupants
areaPerPerson() , ..
, . :
, ,
, . ,
. ,
, , . ,
. , area occupants
areaPerPerson() ,
, areaPerPerson().
.
,
( areaPerPerson()),
return.
return: void- (
), .
, .
void-
return:
return;
, . , , :
public void myMeth() {
int i;
for i 0 5,
, i 5,
myMeth().
return. ,
public void myMeth() {
//...
if(done) return;
//...
if(error) return;
}
,
.
. ,
, .
6. ,
137
, : void-
:
return.
void- ,
. ,
. 3,
Math.Sqrt() .
, , -.
( Math.Sqrt())
, , ,
, .
, , ,
C#-.
,
return:
return ;
, .
areaPerPerson(). ,
, 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 {
public static void Main() {
Building house = new Building();
Building office = new Building();
int areaPP; // ,
// .
// house.
house.occupants = 4;
house.area = 2500;
house.floors = 2;
138
I. C#
// office.
office.occupants = 25;
office.area = 4200;
office.floors = 3;
// house ,
// .
areaPP = house.areaPerPerson();
Console.WriteLine(" :\n " +
house.floors + " \n " +
house.occupants + " \n " +
house.area +
" , \n " +
areaPP + " ");
Console.WriteLine();
// office,
// .
areaPP = office.areaPerPerson();
Console.WriteLine(" :\n " +
office.floors + " \n " +
office.occupants + " \n " +
office.area +
" , \n " +
areaPP + " ");
}
.
areaPerPerson():
. , ,
areaPerPerson(). ,
areaPP = house.areaPerPerson();
, house,
areaPP.
, areaPerPerson()
, int. ,
. , ,
, , ,
,
. , , double,
double.
,
. , areaPP.
areaPerPerson()
WriteLine();
Console.WriteLine(" :\n " +
house.floors + " \n " +
6. ,
139
.
, , , . ,
, .
, .
, .
, , ,
.
. ChkNum
isPrime, true,
, false . ,
isPrime bool.
// .
using System;
class ChkNum {
// true, x - .
public bool isPrime(int x) {
for(int i=2; i < x/2 + 1; i++)
if((x %i) == 0) return false;
return true;
class ParmDemo {
public static void Main() {
ChkNum ob = new ChkNum();
for(int i=1; i < 10; i++)
if(ob.isPrime(i)) Console.WriteLine(i +
" .");
else Console.WriteLine(i + " .");
}
}
:
140
I. C#
1
2
3
4
5
6
7
8
9
.
.
.
.
.
.
.
.
.
isPrime ,
. . -,
, isPrime.
. isPrime
1. x
1. 2, ,
2 .. , ,
isPrime, , x.
.
, . , ,
ChkNum, lcd(),
(least common denominator)
.
// , .
using System;
class ChkNum {
// true, x - .
public bool isPrime(int x) {
for(int i=2; i < x/2 + 1; i++)
if((x %i) == 0) return false;
return true;
}
// .
public int lcd(int a, int b) {
int max;
if(isPrime(a) | isPrime(b)) return 1;
max = a < b ? a : b;
for(int i=2; i < max/2 + 1; i++)
if(((a%i) == 0) & ((b%i) == 0)) return i;
return 1;
class ParmDemo {
public static void Main() {
ChkNum ob = new ChkNum();
int a, b;
for(int i=1; i < 10; i++)
6. ,
141
a = 100;
b = 8;
Console.WriteLine(" " +
a + " " + b + " " +
ob.lcd(a, b));
a = 100;
b = 75;
Console.WriteLine(" " +
a + " " + b + " " +
ob.lcd(a, b));
, lcd()
. :
1 .
2 .
3 .
4 .
5 .
6 .
7 .
8 .
9 .
7 8 1
100 8 2
100 75 5
, . ,
:
int myMeth(int a, double b, float ) { // ...
Building
Building (
)
. , , ,
.
maxOccupant() .
/* ,
. */
142
I. C#
6. ,
143
house.maxOccupant(300));
Console.WriteLine(
" , \n" +
" " +
300 + " : " +
office.maxOccupant(300));
.
,
300 : 8
,
300 : 14
,
.
C#.
. :
public void m() {
char a, b;
// ...
if(a==b) {
Console.WriteLine("");
return;
}
else {
Console.WriteLine(" ");
return;
}
Console.WriteLine(" .");
WriteLine() m()
,
m(). .
,
.
Building-
:
house.occupants = 4;
house.area = 2500;
house.floors = 2;
. ,
,
, .
.
144
I. C#
. ,
, .
. :
_() {
//
}
, ,
, ,
. ,
public,
, , ,
, ,
C# ,
-, , , null-.
, .
:
// .
using System;
class MyClass {
public int x;
public MyClass() {
x = 10;
}
class ConsDemo {
public static void Main() {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
Console.WriteLine(t1.x + " " + t2.x);
}
}
MyClass :
public MyClass() {
x = 10;
}
public- ,
, MyClass.
x 10. MyClass()
new MyClass. ,
MyClass t1 = new MyClass();
t1 MyClass(),
t1.x 10. t2, ..
t2 t2.x
10. ,
:
10 10
6. ,
145
.
,
. , :
. ,
.
// .
using System;
class MyClass {
public int x;
public MyClass(int i) {
x = i;
}
class ParmConsDemo {
public static void Main() {
MyClass t1 = new MyClass(10);
MyClass t2 = new MyClass(88);
:
10 88
MyClass()
i, x.
,
MyClass t1 = new MyClass(10);
i 10,
x.
Building
Building, ,
(.. )
floors, area occupants. ,
Building.
// Building.
using System;
class Building {
public int floors; //
public int area; //
public int occupants; //
public Building(int f, int a, int o) {
146
I. C#
/*
,
. */
public int maxOccupant(int minArea) {
return area / minArea;
}
// Building().
class BuildingDemo {
public static void Main() {
Building house = new Building(2, 2500, 4);
Building office = new Building(3, 4200, 25);
Console.WriteLine(
" , \n" +
" " +
300 + " : " +
house.maxOccupant(300));
Console.WriteLine(
" , \n" +
" " +
300 + " : " +
office.maxOccupant(300));
.
, house office,
Building(). ,
, . ,
Building house = new Building(2, 2500, 4);
Building() 2, 2500 4 , new
Building. floors, area
occupants, house, 2, 2500 4,
.
new
, ,
new. :
__ = new _();
6. ,
147
__
. , _
.
, .
, new ,
C#. , new
.
, ,
new , ,
.
. ( ,
13.) , ,
,
.
new
, , , ,
: new ,
int float. C# .
. , new
, , ,
, ..
.
, int
char, .
,
.
.
new .
:
int i = new int();
int,
i . :
// new .
using System;
class newValue {
public static void Main() {
int i = new int(); // i .
Console.WriteLine(" i : " + i);
}
}
:
i : 0
, i
. : new i
, WriteLine()
.
148
I. C#
new
.
.
new .
""
, new
. ,
, .
, new -
.
,
.
. , C++
delete. C# -,
.
C#
, .
. ,
, , .
() .
. :
, ,
. ,
C#
. , , ,
.
C# ,
,
. ,
. ,
, .
:
~_() {
//
}
, _ . ,
,
(~). ( ,
.)
, .
, .
, , ,
.
6. ,
149
,
, ,
. ( C#- C++-,
, .) ,
, . ,
.
,
.
, ,
.
// .
using System;
class Destruct {
public int x;
public Destruct(int i) {
x = i;
}
// .
~Destruct() {
Console.WriteLine(" " + x);
}
// , // .
public void generator(int i) {
Destruct = new Destruct(i);
}
class DestructDemo {
public static void Main() {
int count;
Destruct ob = new Destruct(0);
/* .
- .
: ,
. */
.
x . x ID (
) . x .
generator(). Destruct,
. DestructDemo
Destruct ob. , ob,
150
I. C#
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;
}
class UseRect {
public static void Main() {
Rect r1 = new Rect(4, 5);
Rect r2 = new Rect(7, 9);
Console.WriteLine(
" r1: " + r1.area());
Console.WriteLine(
" r2: " + r2.area());
6. ,
151
,
, .. . ,
area()
return width * height;
, width height,
, .
:
return this.width * this.height;
this , area().
, this.width width
, this.height height .
, area() x, this
x.
this ,
Rect, this:
using System;
class Rect {
public int width;
public int height;
public Rect(int w, int h) {
this.width = w;
this.height = h;
}
public int area() {
return this.width * this.height;
}
}
class UseRect {
public static void Main() {
Rect r1 = new Rect(4, 5);
Rect r2 = new Rect(7, 9);
Console.WriteLine(
" r1: " + r1.area());
Console.WriteLine(
" r2: " + r2.area());
C#- this ,
, ,
. this . ,
C# ,
.
.
this. , (
)
Rect().
152
I. C#
6. ,
153
C# (
string).
foreach.
(array) ,
. C#
, .
.
,
,
.
,
. , , ,
, , ,
. ,
.
C# ,
, C#- ,
: . ,
, (
) ,
.
.
,
.
, .
.
[] _ = new [];
.
, .
. ,
. , ,
. ,
.
, ,
. , C#
new.
C++,
C# ,
7.
155
. int ( 10 ),
sample.
int[] sample = new int[10];
. sample
, new.
.
. C#
. sample 10 , 0
9. ,
. , sample
sample[0], sample[9]. ,
sample 0 9.
// .
using System;
class ArrayDemo {
public static void Main() {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
sample[0]
sample[1]
sample[2]
sample[3]
sample[4]
sample[5]
sample[6]
sample[7]
sample[8]
sample[9]
:
sample[0]: 0
samp1[1]: 1
sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9
sample :
,
. ,
,
nums, for .
156
I. C#
//
// .
using System;
class Average {
public static void Main() {
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;
:
: 53
nums , ..
.
: .
:
[] _ = [val1, val2, ..., valN];
, ,
val1valN. ,
. C#
,
().
new. Average.
//
// .
using System;
class Average {
public static void Main() {
int[] nums = { 99, 10, 100, 18, 78,
23, 63, 9, 87, 49 };
7.
157
int avg = 0;
for(int i=0; i < 10; i++)
avg = avg + nums[i];
, , ,
new. , nums
,
.
int[] nums = new int[] { 99, 10, 100, 18, 78,
23, 63, 9, 87, 49 };
new-
,
. :
int[] nums;
nums = new int[] { 99, 10, 100, 18, 78,
23, 63, 9, 87, 49 };
nums .
. ,
. , ,
nums.
int[] nums = new int[10] { 99, 10, 100, 18, 78,
23, 63, 9, 87, 49 };
nums 10.
" "
C# " ".
. ,
, .
// .
using System;
class ArrayErr {
public static void Main() {
int[] sample = new int[10];
int i;
// .
for(i = 0; i < 100; i = i+1)
sample[i] = i;
i 10,
IndexOutOfRangeException, .
158
I. C#
, "" .
, ,
.
.
.
, , .
10x20
table, :
int[,] table = new int[10, 20];
, .
[,]
, .
new
:
int[10, 20]
10x20,
.
,
, . , 10
table, 3 5,
:
table[3, 5] = 10;
, 1
12, .
// .
using System;
class TwoD {
public static void Main() {
int t, i;
int[,] table = new int[3, 4];
7.
159
table[0,0] 1,
table[0,1] 2, table[0,2] 3 ..
table[2,3] 12. ,
. 7.1.
0
10
11
12
table[1,2]
C C++,
C# . C C++
C# .
C# .
:
[, .. ,] = new [1, ..., N];
,
4x10x3:
int[, ,] multidim = new int[4, 10, 3];
100 multidim,
2,4,1, :
multidim[2, 4, 1] = 100;
, ,
3x3x3- .
// ,
// 3x3x3-.
using System;
class ThreeDMatrix {
public static void Main() {
int[,,] m = new int[3, 3, 3];
int sum = 0;
int n = 1;
for(int x=0; x < 3; x++)
for(int y=0; y < 3; y++)
for(int z=0; z < 3; z++)
m[x, y, z] = n++;
160
I. C#
:
: 42
,
. ,
:
[,] _ = {
{val, val, val, ..., val}
{val, val, val, ..., val}
.
.
.
{val, val, val, ..., val)
};
val .
. ,
.. ,
,
.
, sqrs 1 10
.
// .
using System;
class Squares {
public 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();
}
}
}
7.
161
:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
, C#
. ,
,
. C# ,
, . .
,
.
,
. , ,
:
[][] = new [][];
.
, . ,
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[l][0]
jagged[l][1]
jagged[l][2]
jagged[2][0]
jagged[2][1]
jagged[2][2]
jagged[0][3]
jagged[2][3]
jagged[2][4]
, , , .
. ,
10 jagged 2 1,
:
jagged[2][1] = 10;
, ,
.
.
162
I. C#
// .
using System;
class Jagged {
public static void Main() {
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
int i;
// .
for(i=0; i < 4; i++)
jagged[0][i] = i;
// .
for(i=0; i < 3; i++)
jagged[1][i] = i;
// .
for(i=0; i < 5; i++)
jagged[2][i] = i;
// .
for(i=0; i < 4; i++)
Console.Write(jagged[0][i] + " ");
Console.WriteLine();
// .
for(i=0; i < 3; i++)
Console.Write(jagged[1][i] + " ");
Console.WriteLine();
// .
for(i=0; i < 5; i++)
Console.Write(jagged[2][i] + " ");
Console.WriteLine();
:
0 1 2 3
0 1 2
0 1 2 3 4
,
. ,
(.. , ),
, .
7.
163
. ,
, . ,
:
int[][,] jagged = new int[3][,];
jagged[0] 4x2:
jagged[0] = new int[4][2];
i
jagged[0][1,0].
jagged[0][1,0] = i;
,
, , .
. ,
, :
// .
using System;
class AssignARef {
public static void Main() {
int i;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for(i=0; i
nums1[i]
for(i=0; i
nums2[i]
<
=
<
=
10; i++)
i;
10; i++)
-i;
164
I. C#
// nums 2.
nums2[3] = 99;
Console.Write(" nums1 \n" +
" nums2: ");
for(i=0; i < 10; i++)
Console.Write(nums1[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
,
nums1 nums2
.
Length
, C# ,
. , Length,
, .
.
// Length.
using System;
class LengthDemo {
public static void Main() {
int[] nums = new int[10];
Console.WriteLine(" nums " +
nums.Length);
// Length nums.
for(int i=0; i < nums.Length; i++)
nums[i] = i * i;
// Length nums.
Console.Write(" nums: ");
for(int i=0; i < nums.Length; i++)
Console.Write(nums[i] + " ");
Console.WriteLine();
:
nums 10
nums: 0 1 4 9 16 25 36 49 64 81
7.
165
, LengthDemo for
nums.Length .
, ,
. ,
Length .
, .
, .
:
// Length 3-- .
using System;
class LengthDemo3D {
public static void Main() {
int[,,] nums = new int[10, 5, 6];
Console.WriteLine(" " +
nums.Length);
}
}
:
300
, Length
, nums
300 (10 x 5 x 6).
().
Length
. ,
Length
.
// .
using System;
class RevCopy {
public 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
// .
if(nums2.Length >= nums1.Length) //
// , nums2
// .
166
I. C#
Console.WriteLine();
:
: 0 1 2 3 4 5 6 7 8 9
: 9 8 7 6 5 4 3 2 1 0
Length . -,
, - ,
. -, for,
. , ,
Length,
.
Length
Length
, ()
. , , ,
() .
// Length
// .
using System;
class Jagged {
public 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; j++) {
7.
167
Console.Write(" " + i +
" " + j + ": ");
Console.Write(network_nodes[i][j] + "% ");
Console.WriteLine();
}
Console.WriteLine();
:
: 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 0: 70%
3 1: 73%
3 2: 76%
3 3: 79%
3 4: 82%
, Length
network_nodes. , .
network_nodes.Length
, network_nodes (
4).
, , , :
network_nodes[0].Length
.
foreach
5 , C# foreach,
.
, .
foreach .
. C# ,
. foreach :
foreach( _ in ) ;
168
I. C#
_
, freach
.
( ).
, ( ) .
,
. ,
, .
foreach.
. , .
// foreach.
using System;
class ForeachDemo {
public static void Main() {
int sum = 0;
int[] nums = new int[10];
// nums .
for(int i = 0; i < 10; i++)
nums[i] = i;
// foreach
// .
foreach(int x in nums) {
Console.WriteLine(" : " + x);
sum += x;
}
Console.WriteLine(" : " + sum);
}
}
:
: 0
: 1
: 2
: 3
: 4
: 5
:
: 7
: 8
: 9
: 45
, foreach
.
foreach ,
,
break. ,
nums.
// break foreach.
using System;
7.
169
class ForeachDemo {
public static void Main() {
int sum = 0;
int[] nums = new int[10];
// nums .
for(int i = 0; i < 10; i++)
nums[i] = i;
// foreach
// .
foreach(int x in nums) {
Console.WriteLine(" : " + x);
sum += x;
if(x == 4) break; // , x 4.
}
:
: 0
: 1
: 2
: 3
: 4
5 : 10
, foreach
.
foreach .
: .
// foreach .
using System;
class ForeachDemo2 {
public static void Main() {
int sum =0;
int[,] nums = new int[3,5];
// nums .
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i,j] = (i+1)*(j+1);
170
// foreach
// .
foreach(int x in nums) {
Console.WriteLine(" : " + x);
sum += x;
}
Console.WriteLine(" : " + sum);
I. C#
:
: 1
: 2
: 3
: 4
: 5
: 2
: 4
: 6
: 8
: 10
: 3
: 6
: 9
: 12
: 15
: 90
freach (
), ,
. .
. . ,
foreach .
, .
// foreach.
using System;
class Search {
public static void Main() {
int[] nums = new int[10];
int val;
bool found = false;
// nums .
for(int i = 0; i < 10; i++)
nums[i] = i;
val = 5;
// foreach nums
// .
foreach(int x in nums) {
if(x == val) {
found = true; break;
}
}
if(found)
Console.WriteLine(" !");
foreach ,
, ..
, foreach .
7.
171
C# string.
.
. C# : .
, string . string
, .
string, 2,
.
string. ,
Console.WriteLine(" C# .");
" C# ." C#
string. ,
string. .
string
. , str
string, .
string str = "C#- - .";
str
C#- - ..
string- char. :
char[] charray = ('t', 'e', 's', 't');
string str = new string(charray);
string- ,
, . , string-
WriteLine(),
.
// .
using System;
class StringDemo {
public static void Main() {
char[] charray = {'A', ' ', 's', 't', 'r',
'i', 'n', 'g', '.' };
string str1 = new string(charray);
string str2 = " string-.";
172
Console.WriteLine(str1);
Console.WriteLine(str2);
I. C#
:
A string.
string-.
string ,
( . 7.1). string Length,
.
,
. :
string str = "test";
Console.WriteLine(str[0]);
t
( "test"). , .
,
. .
7.1.
static string Copy(
string str)
int CompareTo(string str)
string ToLower()
string ToUpper()
str
,
str, ,
str, ,
,
str.
-1,
,
str.
-1,
, , "==".
, "==" , ,
.
string . .
"!=".
(, ">" ">="), ,
.
,
.
// .
using System;
class StrOps {
public static void Main() {
string str1 =
" .NET- C# .";
string str2 = string.Copy(str1);
7.
173
== str2");
!= str2");
== str3");
!= str3");
result = str1.CompareTo(str3);
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("");
Console.WriteLine(
" : " + idx);
idx = str2.LastIndexOf("");
Console.WriteLine(
" : " + idx);
}
174
I. C#
:
str1: .NET- C# .
str1: 43
str1:
.net- C# .
str1:
.NET- C# .
str1 .
.NET- C# .
str1 == str2
str1 != str3
str1 , str3
: 0
: 13
"+" () .
,
string str1 = "";
string str2 = "";
string str3 = "";
string str4 = str1 + str2 + str3;
str4 "".
. string System.
String, .NET Framework. ,
, string,
System.String ( ).
System.String .
, .
.
// .
using System;
class StringArrays {
public static void Main() {
string[] str = { "", "", "", "." };
Console.WriteLine(" : ");
for(int i=0; i < str.Length; i++)
Console.Write(str[i] + " ");
Console.WriteLine("\n");
// .
str[1] = "";
str[3] = ", ?";
Console.WriteLine(" : ");
for(int i=0; i < str.Length; i++)
Console.Write(str[i] + " ");
7.
175
:
:
.
:
, ?
.
. , 19
.
// .
using System;
class ConvertDigitsToWords {
public static void Main() {
int num;
int nextdigit;
int numdigits;
int[] n = new int[20];
string[] digits = { "", "", "",
"", "", "",
"", "", "",
"" };
num = 1908;
Console.WriteLine(": " + num);
Console.Write(" : ");
nextdigit = 0; numdigits = 0;
/* .
. */
do {
nextdigit = num % 10;
n[numdigits] = nextdigit;
numdigits++;
num = num / 10;
}
while(num > 0);
numdigits--;
// .
for(; numdigits >= 0; numdigits--)
Console.Write(digits[n[numdigits]] + " ");
Console.WriteLine();
:
: 1908
:
176
I. C#
string- digits
.
, ,
, int- n.
, n
digits,
.
, , : string-
. , , ,
. , .
C# . ,
,
, .
,
.
, string
, . string-
.
,
, string: Substring().
, .
string-, ,
, .
:
orgstr: C# .
substr:
7.
177
, orgstr , substr
.
string- ,
,
. C# StringBuilder,
System.Text. ,
. string-,
StringBuilder.
switch-
switch- string-,
, , int.
. ,
, .
//
// switch.
using System;
class StringSwitch {
public static void Main() {
string[] strs = { "", "", "", "", "" };
foreach(string s in strs) {
switch(s) {
case "":
Console.Write(1);
break;
case "":
Console.Write(2);
break;
case "":
Console.Write(3);
break;
}
}
Console.WriteLine();
:
12321
178
I. C#
.
.
, ,
Main(), static.
, . , (
6). -, .
.
,
: .
, .
,
, .
.
,
.
,
, , , . ,
, .
, .
, ,
, .
C#
: public, private, protected internal.
public private.
protected 9.
internal
(assembly) 16.
public
, , .
private
, . ,
private- . 6,
(private)
. , private
.
. :
public string errMsg;
private double bal;
private bool isError(byte status) { // ...
180
I. C#
public private,
:
// .
using System;
class MyClass {
private int alpha; // private.
int beta; // private .
public int gamma; // public.
/* alpha beta.
private- . */
public void setAlpha(int a) {
alpha = a;
}
public int getAlpha() {
return alpha;
}
public void setBeta(int a) {
beta = a;
}
public int getBeta() {
return beta;
}
class AccessDemo {
public static void Main() {
MyClass ob = new MyClass();
/* private- alpha beta
. */
ob.setAlpha(-99);
ob.setBeta(19);
Console.WriteLine(" ob.alpha " +
ob.getAlpha());
Console.WriteLine(" ob.beta " +
ob.getBeta());
// private- alpha beta
// :
// ob.alpha = 10;
// ! alpha !
// ob.beta = 9;
// ! beta !
//
// gamma, .
ob.gamma = 99;
}
}
, MyClass alpha private-,
beta private- , a gamma public-.
8.
181
alpha beta ,
. , AccessDemo
. (public-)
, setAlpha() getAlpha().
//
ob.alpha = 10; // ! alpha -- !,
. alpha MyClass
, , MyClass (setAlpha() getAlpha()),
. beta.
, ,
, .
public private
public private
- .
, ,
.
1. , ,
.
2. ,
, ,
, .
3. ,
(.. ),
.
4. ,
, ,
,
.
5. , ,
.
6. ,
.
, ,
. ,
,
.
:
.
-
, . ( ,
: .
, ,
.)
182
I. C#
- ,
,
. ,
, , ,
.
:
. .
.
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 full() {
return tos==stck.Length;
}
8.
183
// true, .
public bool empty() {
return tos==0;
}
// .
public int capacity() {
return stck.Length;
}
// .
public int getNum() {
return tos;
}
stack .
:
char[] stck; // .
int tos; // .
stck ,
. , .
stack. tos .
stck tos ,
.
stck ,
. , tos
, ,
stack.
stck tos ,
. :
// Stack .
public Stack(int size) {
stck = new char[size]; // .
tos = 0;
}
.
tos . , tos
, .
push() .
:
// .
public void push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" - .");
return;
}
stck[tos] = ch;
tos++;
184
I. C#
, , ch.
, , ,
. ,
tos stck.
, stck ,
tos, tos . , tos
stck.
, pop().
:
// .
public char pop() {
if(tos==0) {
Console. WriteLine(" - .");
return(char) 0;
}
tos--;
return stck[tos];
tos. , ,
. tos ,
.
push() pop() ,
, ,
, Stack (full(),
empty(), capacity() getNum()).
. .
// true, .
public bool full() {
return tos==stck.Length;
}
// true, .
public bool empty() {
return tos==0;
}
// ,.
public int capacity() {
return stck.Length;
}
// .
public int getNum() {
return tos;
}
full() true, , false
. empty() true, ,
false . (.. ,
), capacity(). ,
, getNum().
, ,
8.
185
, tos,
Stack.
.
// Stack.
using System;
class StackDemo {
public static void Main() {
Stack stk1 = new Stack(10);
Stack stk2 = new Stack(10);
Stack stk3 = new Stack(10);
char ch; int i;
// stk1.
Console.WriteLine(
" Z stk1.");
for(i=0; !stk1.full(); i++)
stk1.push((char) ('A' + i));
if(stk1.full()) Console.WriteLine(" stk1 .");
// stk1.
Console.Write(" stk1: ");
while( !stk1.empty() ) {
ch = stk1.pop();
Console.Write(ch);
}
Console.WriteLine();
if(stk1.empty()) Console.WriteLine(" stk1 .\n");
// stk1.
Console.WriteLine(
" Z stk1.");
for(i=0; !stk1.full(); i++)
stk1.push((char) ('A' + i));
/* stk1
stk2.
stk2
. */
Console.WriteLine(
" stk1 \n" +
" stk2.");
while(!stk1.empty()) {
ch = stk1.pop();
stk2.push(ch);
}
Console.Write(" stk2: ");
while( !stk2.empty() ) {
ch = stk2.pop();
Console.Write(ch);
}
186
I. C#
Console.WriteLine("\n");
// 5 stk3.
Console.WriteLine(" 5 stk3.");
for(i=0; i < 5; i++)
stk3.push((char) ('A' + i));
Console.WriteLine(
" stk3: " + stk3.capacity());
Console.WriteLine(
" stk3: " +
stk3.getNum());
:
Z stk1.
stk1 .
stk1: JIHGFEDCBA
stk1 .
Z 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;
}
/* true, ob
, . */
public bool sameAs(MyClass ob) {
if((ob.alpha == alpha) & (ob.beta == beta))
return true;
else
return false;
}
8.
187
// ob.
public void copy(MyClass ob) {
alpha = ob.alpha;
beta = ob.beta;
}
public void show() {
Console.WriteLine("alpha: {0}, beta: {1}", alpha, beta);
}
}
class PassOb {
public static void Main() {
MyClass 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 b2 .");
else
Console.WriteLine(
"ob1 b2 .");
Console.WriteLine();
// b1 b2.
ob1.copy(ob2);
Console.Write("ob1 : ");
ob1.show();
if(ob1.sameAs(ob2))
Console.WriteLine(
"ob1 b2 .");
else
Console.WriteLine(
"b1 b2 .");
, :
ob1: alpha: 4, beta: 5
ob2: alpha: 6, beta: 7
b1 ob2 .
b1 : alpha: 6, beta: 7
b1 b2 .
sameAs() ()
. sameAs() alpha beta
alpha beta , ob.
188
I. C#
true ,
. ()
alpha beta , ob,
alpha beta . ,
MyClass.
, ( ) ,
.
. , .
. ,
.
(call-by-value).
. , ,
, , .
(call-by-reference).
, ,
. , , ,
, .
(, int double)
. , , ,
, .
:
// .
using System;
class Test {
/* ,
. */
public void noChange(int i, int j) {
i = i + j;
j = -j;
}
}
class CallByValue {
public static void Main() {
Test ob = new Test();
int a = 15, b = 20;
Console.WriteLine(" b : " + a + " " + b);
ob.noChange(a, b);
8.
189
:
b : 15 20
b : 15 20
, , noChange(),
b, .
.
, , ,
, , , , ,
. (,
, , .) (,
) , , ,
, . ,
.
,
. , , ,
, . ,
. ,
, . ,
, :
// .
using System;
class Test {
public int a, b;
public Test(int i, int j) {
a = i;
b = j;
}
/* . ob.a ob.b ,
, . */
public void change(Test ob) {
ob.a = ob.a + ob.b;
ob.b = -ob.b;
}
class CallByRef {
public static void Main() {
Test ob = new Test(15, 20);
Console.WriteLine("ob.a ob.b : " +
ob.a + " " + ob.b);
ob.change(ob);
Console.WriteLine("ob. ob.b : " +
ob.a + " " + ob.b);
:
ob.a ob.b : 15 20
ob.a ob.b : 35 -20
190
I. C#
, change() ,
.
,
, .
, .
ref - out-
, (,
int char) . , ,
, ,
, .
. ref out,
. ,
.
ref out,
, .
:
. .
, ,
. swap(),
.
,
int, C#-
. ref.
, return ,
.
. , ? ,
, .
: .
, .
out.
ref
ref C#
. ref .
. sqr(),
.
ref.
// ref
// .
using System;
class RefTest {
/* .
ref. */
public void sqr(ref int i) {
i = i * i;
8.
191
}
}
class RefDemo {
public static void Main() {
RefTest ob = new RefTest();
int a = 10;
,
.
,
sqr().
: 10
: 100
ref, ,
. , ,
swap(), ,
.
// .
using System;
class Swap {
// .
public void swap(ref int a, ref int b) {
int t;
t = a;
a = b;
b = t;
}
}
class SwapDemo {
public static void Main() {
Swap ob = new Swap();
int x = 10, y = 20;
Console.WriteLine("x y : " +
x + " " + y);
ob.swap(ref x, ref y);
192
Console.WriteLine("x y : " +
x + " " + y);
I. C#
:
x y : 10 20
x y : 20 10
. ,
ref, .
, , , ,
. , ref,
, .
out
, . , ,
, ,
,
. ,
.
ref, ref-
. , ref-
,
. , C# ,
out.
out ref :
. (
) , out-,
. , , out-
, ( )
. ,
out- .
out-. Decompose
parts() .
, .
// out.
using System;
class Decompose {
/*
. */
public int parts(double n, out double frac) {
int whole;
whole = (int) n;
frac = n - whole; //
// frac.
return whole; // .
class UseOut {
public static void Main() {
Decompose ob = new Decompose();
8.
193
int i; double f;
i = ob.parts(10.125, out f);
:
10
0,125
parts() . n
return. n
out- frac. , out-,
, , .
, C#
out-. out- ,
. out-.
isComDenom() . -, ,
. true,
, false . -,
, isComDenom() out-
.
// out-.
using System;
class Num {
/* , x v .
,
out-. */
public bool isComDenom(int x, int y,
out int least,
out int greatest) {
int i;
int max = x < y ? 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;
194
I. C#
class DemoOut {
public static void Main() {
Num ob = new Num();
int lcd, gcd;
if(ob.isComDenom(231, 105, out lcd, out gcd)) {
Console.WriteLine("Lcd 231 105 " +
lcd);
Console.WriteLine("Gcd 231 105 " +
gcd);
}
else
Console.WriteLine(
" 35 49 .");
ref out
ref out
. , .. ,
.
ref out, .
, -.
, ref-
, .
8.
195
// .
using System;
class RefSwap {
int a, b;
public RefSwap(int i, int j) {
a = i;
b = j;
}
public void show() {
Console.WriteLine("a: {0}, b: {1}", a, b);
}
// .
public void swap(ref RefSwap ob1, ref RefSwap ob2) {
RefSwap t;
t = ob1;
ob1 = ob2; ob2 = t;
}
class RefSwapDemo {
public static void Main() {
RefSwap x = new RefSwap(1, 2);
RefSwap y = new RefSwap(3, 4);
Console.Write("x : ");
x.show();
Console.Write("y : ");
y.show();
Console.WriteLine();
// , x y.
x.swap(ref x, ref y);
Console.Write("x : ");
x.show();
Console.Write("y : ");
y.show();
:
x : a: 1, b: 2
y : a: 3, b: 4
x : a: 3, b: 4
y : a: 1, b: 2
196
I. C#
swap() ,
. swap() x ,
1 2, y , 3
4. swap() x ,
3 4, y , 1
2. ref-, swap()
. ,
swap().
,
. ,
. , , ,
. , .
.
.
, .
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];
class ParamsDemo {
public static void Main() {
Min ob = new Min();
int min;
int a = 10, b = 20;
8.
197
// .
min = ob.minVal(a, b);
Console.WriteLine(" " + min);
// call with 3 values
min = ob.minVal(a, b, -1);
Console.WriteLine(" " + min);
// .
min = ob.minVal(18, 23, 3, 14, 25);
Console.WriteLine(" " + min);
// int-.
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.minVal(args);
Console.WriteLine(" " + min);
:
10
-1
3
8
minVal()
nums. . minVal()
.
params-
, , ,
. , minVal()
min = ob.minVal(1, 2.2);
, double(2.2)
int ( int nums minVal()) .
params
, params-
, ! ,
minVal() :
min = ob.minVal(); //
min = ob.minVal(3); //
minVal() nums
.
, minVal()
. (
.) ,
minVal() ,
. () .
.
, showArgs()
string params- .
//
// params-.
198
I. C#
using System;
class MyClass {
public void showArgs(string msg, params int[] nums) {
Console.Write(msg + ": ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
class ParamsDemo2 {
public static void Main() {
MyClass ob = new MyClass();
ob.showArgs(" ",
1, 2, 3, 4, 5);
ob.showArgs(" ",
17, 20);
:
: 1 2 3 4 5
: 17 20
params-, params-
.
, . ,
Rect enlarge(),
(
) ( ) .
// .
using System;
class Rect {
int width;
int height;
public Rect(int w, int h) {
width = w;
height = h;
}
public int area() {
return width * height;
}
8.
199
/* ,
. */
public Rect enlarge(int factor) {
return new Rect(width * factor, height * factor);
}
class RetObj {
public static void Main() {
Rect r1 = new Rect(4, 5);
Console.Write(" r1: ");
r1.show();
Console.WriteLine(" r1: " +
r1.area());
Console.WriteLine();
// ,
// r1 .
Rect r2 = r1.enlarge(2);
Console.Write(" r2: ");
r2.show();
:
r1: 4 5
r1: 20
r2: 8 10
r2: 80
, ,
, .
, , ..
. ,
, .
, ,
, (class factory).
, .
.
,
.
. :
// "" .
using System;
200
I. C#
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; // .
class MakeObjects {
public 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: 0 10
b: 1 9
b: 2 8
b: 3 7
b: 4 6
b: 5 5
b: 6 4
b: 7 3
b: 8 2
b: 9 1
. MyClass
, , C#
. , b
.
b , factory(). ,
b , factory()
.
Main() ob MyClass, for
. ,
.
MyClass anotherOb = ob.factory(i, j); //
8.
201
anotherOb,
, .
anotherOb ,
, , .
C# , .
( C# C++, , ,
, .) , findfactors()
, , .
// .
using System;
class Factor {
/* ,
num.
out- numfactors
. */
public int[] findfactors(int num, out int numfactors) {
int[] facts = new int[80]; // 80 .
int i, j;
// facts.
for(i=2, j=0; i < num/2 + 1; i++)
if( (num%i)==0 ) {
facts[j] = i;
j++;
}
numfactors = j; return facts;
}
}
class FindFactors {
public static void Main() {
Factor f = new Factor();
int numfactors;
int[] factors;
factors = f.findfactors(1000, out numfactors);
Console.WriteLine(" 1000: ");
for(int i=0; i < numfactors; i++)
Console.Write(factors[i] + " ");
Console.WriteLine();
:
1000:
2 4 5 8 10 20 25 40 50 100 125 200 250 500
202
I. C#
Factor findfactors() :
public int[] findfactors(int num, out int numfactors) {
, int.
. , , ()
, . ,
someMeth(),
double-.
public double[,] someMeth() { // ...
C#
. C#
, , .
(method overloading), ,
, (overloaded).
C#.
. .
:
, / .
.
. ( ,
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(" int-: " + a + " " + b);
return a + b;
}
// ovlDemo()
8.
203
// double-.
public double ovlDemo(double a, double b) {
Console.WriteLine(" double-: " +
a + " "+ b);
return a + b;
}
}
class OverloadDemo {
public static void Main() {
Overload ob = new 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();
:
: 2
int-: 4 6
ob.ovlDemo(4, 6): 10
double-: 1,1 2,32
ob.ovlDemo(1.1, 2.2): 3,42
, ovlDemo() .
, ,
, double-.
, ovlDemo() void, ..
, .
, , ,
.
ovlDemo() :
// ovlDemo(int) .
public void ovlDemo(int a) {
Console.WriteLine(" : " + a);
}
204
I. C#
// ! ovlDemo(int) ,
// ,
// .
public int ovlDemo(int a) {
Console.WriteLine(" : " + a);
return a * a;
}
, , ,
.
3, C#
.
. , , .
/*
. */
using System;
class Overload2 {
public void f(int x) {
Console.WriteLine(" f(int): " + x);
}
public void f(double x) {
Console.WriteLine(" f(double): " + x);
}
}
class TypeConv {
public static void Main() {
Overload2 ob = new Overload2();
int i = 10;
double d = 10.1;
byte b = 99;
short s = 10;
float f = 11.5F;
ob.f(i); // ob.f(int).
ob.f(d); // ob.f(double).
ob.f(b); // ob.f(int)
// .
ob.f(s); // ob.f(int)
// .
ob.f(f); // ob.f(double)
// .
:
f(int): 10
f(double): 10,1
f(int): 99
f(int): 10
f(double): 11,5
8.
205
f(): int-,
double-. f() int
double byte, short float. byte-
short- C# int (..
f(int)). float-
double f(double).
,
, .
f(), byte.
// f(byte).
using System;
class Overload2 {
public void f(byte x) {
Console.WriteLine(" f(byte): " + x);
}
public void f(int x) {
Console.WriteLine(" f(int): " + x);
}
class TypeConv {
public 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.f(i); // ob.f(int).
ob.f(d); // ob.f(double).
ob.f(b); // ob.f(byte) -
// .
ob.f(s); // ob.f(int)
// .
ob.f(f); // ob.f(double)
// .
:
f(int): 10
f(double): 10,1
206
I. C#
f(byte): 99
f(int): 10
f(double): 11,5
, f(),
byte, f() byte-
f(byte), byte-
int .
ref-, out-
. , .
public void f(int x) {
Console.WriteLine(" f(int): " + x);
}
public void f(ref int x) {
Console.WriteLine(" f(ref int): " + x);
}
,
ob.f(i);
f(int x),
ob.f(ref i);
f(ref int x).
C# ,
C# .
, , . ,
, .
. ,
, , . ,
,
, . , C
abs() () , labs()
, fabs()
. C ,
, ,
. , .
,
( ) . C# ,
. , C#
Abs(). C#-
System.Math, ,
. , ,
.
,
, . ,
Abs() , .
.
,
. .
, ,
.
8.
207
,
. ,
.
-
. , ,
, . ,
sqr ,
, ,
. ,
.
.
C# (signature),
. ,
. , ,
, C#
.
params-, . , 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;
208
I. C#
class OverloadConsDemo {
public 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:
Console.WriteLine("t2.x:
Console.WriteLine("t3.x:
Console.WriteLine("t4.x:
"
"
"
"
+
+
+
+
t1.x);
t2.x);
t3.x);
t4.x);
:
MyClass().
MyClass(int).
MyClass(double).
MyClass(int, int).
t1.x: 0
t2.x: 88
t3.x: 17
t4.x: 8
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++)
8.
209
stck[i] = ob.stck[i];
// tos .
tos = ob.tos;
// .
public void push(char ch) {
if(tos==stck.Length) {
Console.WriteLine(" -- .");
return;
}
stck[tos] = ch;
tos++;
}
// .
public char pop() {
if(tos==0) {
Console.WriteLine(" -- .");
return(char) 0;
}
tos--;
return stck[tos];
}
// true, .
public bool full() {
return tos==stck.Length;
}
// true, .
public bool empty() {
return tos==0;
}
// .
public int capacity() {
return stck.Length;
}
// .
public int getNum() {
return tos;
}
// Stack.
class StackDemo {
public static void Main() {
Stack stk1 = new Stack(10);
char ch;
int i;
// stk1.
Console.WriteLine(
210
I. C#
" Z stk1.");
for(i=0; !stk1.full(); i++)
stk1.push((char) ('A' + i));
// stck1.
Stack stk2 = new Stack(stk1);
// stk1.
Console.Write(" stk1: ");
while( !stk1.empty() ) {
ch = stk1.pop();
Console.Write(ch);
}
Console.WriteLine();
:
Z 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;
stck
, ,
, ob. ,
ob, ,
tos.
, .
8.
211
this
. C#
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;
y = j;
}
}
class OverloadConsDemo {
public 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)
XYCoord(obj)
t1.x, t1.y: 0, 0
t2.x, t2.y: 8, 9
t3.x, t3.y: 8, 9
212
I. C#
. XYCoord ,
x y, XYCoord(int, int).
XYCoord(int, int),
this. , t1
XYCoord(), this(0, 0),
XYCoord(0, 0), t2 .
this
, .
this
.
, ,
. ,
XYCoord :
public XYCoord(int x) : this(x, x) { }
y
x. ,
,
.
Main()
Main().
. ,
. .
Main()
( ).
Main(): public static int Main()
, void, Main()
int.
, Main(), ,
( ). ,
, .
.
Main()
.
,
. Main().
Main():
public static void Main(string[] args)
public static int Main(string[] args)
8.
213
void,
, .
string-,
Main().
,
.
// .
using System;
class CLDemo {
public static void Main(string[] args) {
Console.WriteLine(" " +
args.Length + " .");
Console.WriteLine(" : ");
, CLDemo
:
CLDemo
:
5 . :
, . .
, ,
. : ,
1. ..
, 1.
// .
using System;
class Cipher {
public static int Main(string[] args) {
// .
if(args.Length < 2) {
Console.WriteLine(
": " +
"1: <<>>/<<>> " +
"[2... N]");
return 1; // .
}
// ,
214
I. C#
// "" "".
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,
.
D:\Cipher
D:\Cipher
. -,
, . ,
.
, ,
.
. ,
, ,
, .
-, ,
. ,
1, .
, 0,
.
C# . , ,
, .
- .
8.
215
. .
.
N 1 N. ,
3 1x2x3, 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;
}
class Recursion {
public static void Main() {
Factorial f = new Factorial();
Console.WriteLine(
", " +
" .");
Console.WriteLine(" 3 "
f.factR(3));
Console.WriteLine(" 4 "
f.factR(4));
Console.WriteLine(" 5 "
f.factR(5));
Console.WriteLine();
Console.WriteLine(
", " +
" .");
Console.WriteLine(" 3 "
f.factI(3));
Console.WriteLine(" 4 "
f.factI(4));
Console.WriteLine(" 5 "
f.factI(5));
}
}
216
+
+
+
+
+
+
I. C#
:
, .
3 6
4 24
5 120
, .
3 6
4 24
5 120
factI() . ,
, 1 (
1) ,
.
factR() . ,
1, 1.
factR(n-1) * n. factR()
n-1. , 1,
. ,
2 factR()
, , 1. factR()
1, 2 ( n).
, factR()
WriteLine(), .
,
,
. .
.
,
.
. 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 {
public static void Main() {
string s = " ";
RevStr rsOb = new RevStr();
8.
217
:
:
:
displayRev() ,
str , displayRev()
-, str .
,
. ,
, ..
str.
.
,
, - ,
.
.
, , . C# .
, .
,
, . ,
Quicksort . ,
.
(, if-),
. , ,
, .
.
WriteLine(), ,
, .
static
,
.
. ,
, .. .
, static.
static,
. static ,
. static- Main(),
.
218
I. C#
static-
. . static , . ,
10 static- count,
Timer, :
Timer.count = 10;
,
, .
static-, ..
.
, static-,
. static- ,
static-.
static- .
, static-, ,
; null-, bool
false. , static- .
static- , static-
,
. ,
static- Sqrt(), System.Math,
static- static-.
// static.
using System;
class StaticDemo {
// .
public static int val = 100;
// .
public static int valDiv2() {
return val/2;
}
class SDemo {
public static void Main() {
Console.WriteLine(
" StaticDemo.val " +
StaticDemo.val);
StaticDemo.val = 8;
Console.WriteLine(
" StaticDemo.val " +
StaticDemo.val);
Console.WriteLine("StaticDemo.valDiv2(): " +
StaticDemo.valDiv2());
:
8.
219
StaticDemo.val 100
StaticDemo.val 8
StaticDemo.valDiv2() : 4
, static-
, .. ,
.
static- .
1. static- this,
2. static- static-.
. ,
,
static-.
3. static- static-.
,
.
, static- valDivDenom() :
class StaticError {
int denom =3; //
static int val = 1024; //
/* !
. */
static int valDivDenom() {
return val/denom; // !
}
denom ,
. val
, static-.
static . :
using System;
class AnotherStaticError { // .
void nonStaticMeth() {
Console.WriteLine(" nonStaticMeth().");
}
/* !
. */
static void staticMeth() {
nonStaticMeth(); // !
}
(.. )
.
, static-
,
. ,
. ,
:
220
I. C#
class MyClass {
// .
void nonStaticMeth() {
Console.WriteLine(" nonStaticMeth().");
}
/*
, . */
public static void staticMeth(MyClass ob) {
ob.nonStaticMeth(); // .
}
static- ,
, . .
static-
.
// static- .
using System;
class CountInst {
static int count = 0;
// .
public CountInst() {
count++;
}
// .
~CountInst() {
count--;
}
public static int getcount() {
return count;
}
class CountDemo {
public static void Main() {
CountInst ob;
:
: 1
: 2
: 3
: 4
: 5
8.
221
: 6
: 7
: 8
: 9
: 10
, CountInst, static- count
. , CountInst , 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; // .
class MakeObjects {
public static void Main() {
int i, j;
// "" .
for(i=0, j=10; i < 10; i++, j--) {
MyClass ob = MyClass.factory(i, j);
//
// .
ob.show();
}
222
I. C#
Console.WriteLine();
factory()
:
MyClass ob = MyClass.factory(i, j); // .
, MyClass
.
.
,
, . ,
.
.
// .
using System;
class Cons {
public static int alpha;
public int beta;
// .
static Cons() {
alpha = 99;
Console.WriteLine(" .");
}
// .
public Cons() {
beta = 100;
Console.WriteLine(" .");
}
class ConsDemo {
public static void Main() {
Cons ob = new Cons();
Console.WriteLine("Cons.alpha: " + Cons.alpha);
Console.WriteLine("ob.beta: " + ob.beta);
}
}
:
.
.
Cons.alpha: 99
ob.beta: 100
, ,
. static-
. , static-
, .
8.
223
C# .
. ,
.
, . ,
, , +
. , ,
+ . -
.
.
. ,
+, , (
) .
,
.
-
, C#. ,
, C#- .
, ,
. C#.
.
operator,
, , .
operator: ,
. ( ) :
// .
public static _ operator (
_ )
{
//
}
// .
public static _ operator (
_1 1, _2 2)
{
//
}
op - ( + /), .
_ ,
. ,
, .
.
,
1 2.
,
. ,
9.
225
. , C#-
, . ,
+ int string.
: ref
out.
, , ,
+ -.
ThreeD .
+ ThreeD-,
- ThreeD-
.
// .
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+".
public static ThreeD operator +(ThreeD op1,
ThreeD op2)
{
ThreeD result = new ThreeD();
/*
. */
result.x = op1.x + op2.x; //
result.y = op1.y + op2.y; // .
result.z = op1.z + op2.z;
return result;
}
// "-".
public static ThreeD operator -(ThreeD op1, ThreeD op2) {
ThreeD result = new ThreeD();
/* .
op1 - , op2 - . */
result.x = op1.x - op2.x; //
result.y = op1.y - op2.y; // .
result.z = op1.z - op2.z;
return result;
}
// X, Y, Z.
226
I. C#
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
Console.Write(" a: ");
a.show();
Console.WriteLine();
Console.Write(" b: ");
b.show();
Console.WriteLine();
c = a + b; // b.
Console.Write(" + b: ");
c.show();
Console.WriteLine();
c = a + b + c; // , b c.
Console.Write(" + b + c: ");
c.show();
Console.WriteLine();
c = c - a; // c.
Console.Write(" c - a: ");
c.show();
Console.WriteLine();
c = c - b; // b c.
Console.Write(" c - b: ");
c.show();
Console.WriteLine();
:
a: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
+ b + c: 22, 24, 26
c - a: 21, 22, 23
c - b: 11, 12, 13
.
+. + ThreeD
, operator+().
, .
9.
227
ThreeD,
.
+, , , 10 12.
10+12 22, 10, 12 .
,
, , .
, operator+() ThreeD.
C# ,
, ThreeD, +
, + b + c. , a+b,
ThreeD, .
( ThreeD),
.
. operator+()
,
. + ThreeD
+, .
operator-(). "-"
+ ,
. , , (.. -
, -).
, .
,
, .
, . ,
, , . ,
, , ThreeD.
// "-".
public static ThreeD operator -(ThreeD op) {
ThreeD result = new ThreeD();
result.x = -op.x;
result.y = -op.y;
result.z = -op.z;
}
return result;
, ,
.
operator-().
.
. ,
= -b
b, , b .
228
I. C#
.
(++) (--). ( )
,
, + -, ,
. , .
, operator++-() ThreeD.
// "++".
public static ThreeD operator ++(ThreeD op){
// "++" .
op.x++;
op.y++;
op.z++;
return op;
}
: ,
, . , ,
++, . ,
, ++ .
, ,
, -
++.
// .
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+".
public static ThreeD operator +(ThreeD op1, ThreeD op2){
ThreeD result = new ThreeD();
/*
. */
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
}
// "-".
public static ThreeD operator -(ThreeD op1, ThreeD op2){
ThreeD result = new ThreeD();
/* .
9.
229
op1 - , op2 - . */
result.x = op1.x - op2.x;
result.y = op1.y - op2.y;
result.z = op1.z - op2.z;
return result;
// "-".
public static ThreeD operator -(ThreeD op) {
ThreeD result = new ThreeD();
result.x = -op.x;
result.y = -op.y;
result.z = -op.z;
return result;
}
// "++".
public static ThreeD operator ++(ThreeD op) {
// "++" .
op.x++;
op.y++;
op.z++;
return op;
}
// X, Y, Z.
public void show(){
Console.WriteLine(x + ", " + y + ", " + z);
}
}
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
Console.Write(" a: ");
a.show();
Console.WriteLine();
Console.Write(" b: ");
b.show();
Console.WriteLine();
c = a + b; // b.
Console.Write(" + b: ");
c.show();
Console.WriteLine();
c = a + b + c; // a, b c.
Console.Write(" + b + c: ");
230
I. C#
c.show();
Console.WriteLine();
c = c - a; // c.
Console.Write(" c - a: ");
c.show();
Console.WriteLine();
c = c - b; // b c.
Console.Write(" c - b: ");
c.show();
Console.WriteLine();
c = -a; // - c.
Console.Write(" -a: ");
c.show();
Console.WriteLine();
a++; // .
Console.Write(" a++: ");
a.show();
:
a: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
+ b + c: 22, 24, 26
c - a: 21, 22, 23
c - b: 11, 12, 13
-a: -1, -2, -3
a++: 2, 3, 4
, ++ ,
. ,
++;
a++;
.
++ . ,
++ .
.
9.
231
C#-
.
() .
ThreeD. , +,
ThreeD- .
ThreeD.
, -
ThreeD-.
. + , , :
// "+"
// int-.
public static ThreeD operator +(ThreeD op1, int op2){
ThreeD result = new ThreeD();
, int. ,
int- ThreeD-.
, , ,
,
. .
ThreeD,
operator+().
/* :
+ + int-. */
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+"
// " + ".
public static ThreeD operator +(ThreeD op1, ThreeD op2){
ThreeD result = new ThreeD();
/*
. */
232
I. C#
}
// "+"
// " + int-".
public static ThreeD operator +(ThreeD op1, int op2) {
ThreeD result = new ThreeD();
result.x = op1.x + op2;
result.y = op1.y + op2;
result.z = op1.z + op2;
return result;
}
// X, Y, Z.
public void show() {
Console.WriteLine(x + ", " + y + ", " + z);
}
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
Console.Write(" a: ");
a.show();
Console.WriteLine();
Console.Write(" b: ");
b.show();
Console.WriteLine();
c = a + b; // +
Console.Write(" + b: ");
c.show();
Console.WriteLine();
c = b + 10; // + int-
Console.Write(" b + 10: ");
c.show();
:
a: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
b + 10: 20, 20, 20
9.
233
, +
, .
+ ,
.
+
ThreeD,
. . operator+(ThreeD, int)
, .
b1 = b2 + 10;
, , :
b1 = 10 + b2;
, ,
.
. ,
+ .
int, ThreeD.
operator+() + int, int- + . +
( ), ,
.
ThreeD, +
.
/* "+" :
+ ,
+ int-
int- + . */
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+"
// " + ".
public static ThreeD operator +(ThreeD op1, ThreeD op2){
ThreeD result = new ThreeD();
/*
. */
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
}
// "+"
// " + int-".
234
I. C#
c = 15 + b; // int- +
Console.Write(" 15 + b: ");
c.show();
9.
235
:
a: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
b + 10: 20, 20, 20
15 + b: 25, 25, 25
(, == <) ,
. ,
: true false.
.
, .
ThreeD, < >.
// "<" ">".
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "<".
public static bool operator <(ThreeD op1, ThreeD op2){
if((op1.x < op2.x) && (op1.y < op2.y) &&
(op1.z < op2.z))
return true;
else
return false;
}
// ">".
public static bool operator >(ThreeD op1, ThreeD op2){
if((op1.x > op2.x) && (op1.y > op2.y) &&
(op1.z > op2.z))
return true;
else
return false;
}
// X, Y, Z.
public void show()
{
236
I. C#
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD(1, 2, 3);
Console.Write(" a: ");
a.show();
Console.Write(" b: ");
b.show();
Console.Write(" c: ");
c.show();
Console.WriteLine();
if(a
if(a
if(a
if(a
>
<
>
<
c)
c)
b)
b)
Console.WriteLine("a
Console.WriteLine("a
Console.WriteLine("a
Console.WriteLine("a
>
<
>
<
c
c
b
b
");
");
");
");
:
a: 5, , 7
b: 10, 10, 10
c: 1, 2, 3
> c - < b -
:
. , <,
>, . :
==
!=
<
>
<=
>=
== !=,
Object.Equals() Object.GetHashCode(). ( )
11.
true false
true false
.
. true
false,
if, while, for do-while, ?-.
(, ).
9.
237
true false .
.
:
public static bool operator true(_ op)
{
// true false.
}
public static bool operator false(_ op) {
// true false.
}
, bool.
true false ThreeD. , ThreeD-
, .
, .
.
// true false ThreeD.
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// true.
public static bool operator true(ThreeD op) {
if((op.x !=0) || (op.y != 0) || (op.z != 0))
return true; // 0.
else
return false;
}
// false.
public static bool operator false(ThreeD op) {
if((op.x == 0) && (op.y == 0) && (op.z == 0))
return true; // .
else
return false;
}
// "--".
public static ThreeD operator --(ThreeD op) {
op.x--;
op.y--;
op.z--;
return op;
}
// X, Y, Z.
238
I. C#
:
a: 5, 6, 7
b: 10, 10, 10
c: 0, 0, 0
- .
b - .
c - .
, ThreeD.
10, 10, 10
9, 9, 9
8, 8, 8
7, 7, 7
6, 6, 6
5, 5, 5
4, 4, 4
3, 3, 3
2, 2, 2
1, 1, 1
9.
239
, ThreeD
if- while-. if-, ThreeD-
true.
. do-while-
b. ,
b (..
). b , ()
( true), .
, C# : &, |, !, && ||.
, &, |, !.
&& ||,
.
.
, ,
& | ,
bool. ! , ,
bool.
&, |, !
ThreeD. , , ThreeD-
, .
, .
// !, | &
// ThreeD.
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "|".
public static bool 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 true;
else
return false;
}
// "&".
public static bool operator &(ThreeD op1, ThreeD op2)
240
I. C#
if(
}
// "!".
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 + ", " + y + ", " + z);
}
}
class TrueFalseDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD(0, 0, 0);
Console.Write(" a: ");
a.show();
Console.Write(" b: ");
b.show();
Console.Write(" c: ");
c.show();
Console.WriteLine();
if(!a) Console.WriteLine("a - .");
if(!b) Console.WriteLine("b - .");
if(!c) Console.WriteLine(" - .");
Console.WriteLine();
if(a & b) Console.WriteLine("a & b - .");
else Console.WriteLine("a & b - .");
if(a & c) Console.WriteLine("a & - .");
else Console.WriteLine("a & - .");
if(a | b) Console.WriteLine("a | b - .");
else Console.WriteLine("a | b - .");
if(a | c) Console.WriteLine("a | - .");
else Console.WriteLine("a | - .");
}
}
:
a: 5, 6, 7
b: 10, 10, 10
9.
241
c: 0, 0, 0
c - .
& b - .
& - .
a | b - .
| - .
operator |(), operator &() operator !()
bool. ,
(.. ,
bool). ,
bool. ,
,
bool. , , ,
.
&& ||,
, . -,
& |. -, &- |-
, . -,
,
. -, true false.
.
, & |
ThreeD, && ||,
.
/* !, | &
ThreeD.
&& ||. */
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = 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.y != 0) || (op2.z != 0)) )
return new ThreeD(1, 1, 1);
else
return new ThreeD(0, 0, 0);
242
I. C#
}
// "&"
// .
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
return false;
}
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + y + ", " + z);
}
class TrueFalseDemo {
public static void Main() {
ThreeD a = new ThreeD(5, 6, 7);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD(0, 0, 0);
Console.Write(" a: ");
a.show();
Console.Write(" b: ");
b.show();
Console.Write(" c: ");
c.show();
Console.WriteLine();
9.
243
if(a
else
if(a
else
if(a
else
if(a
else
|| b) Console.WriteLine("a || b - .");
Console.WriteLine("a || b - .");
|| c) Console.WriteLine("a || c - .");
Console.WriteLine("a || c - .");
:
a: 5, 6, 7
b: 10, 10, 10
c: 0, 0, 0
- .
b - .
c - .
& |
& b - .
a & c - .
| b - .
| c - .
244
I. C#
"" && ||
&& b - .
&& - .
|| b - .
a || - .
& |.
.
// "|"
// .
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 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);
}
,
ThreeD, , .
, ThreeD-
(.. , ).
, ThreeD (.. , ). ,
if( & b) Console.WriteLine("a & b - .");
else Console.WriteLine("a & b - .");
& b ThreeD-,
. ThreeD true false,
true,
bool. true,
" & b - .".
,
ThreeD .
.
operator true ( ||) operator
false ( &&).
, &- |- .
&
|. , &&- ||-
&- |- ,
. , ,
:
9.
245
,
. .
( ). C#
operator,
.
. , .
C#-
,
.
: .
:
public static explicit operator _(
_ v)[return ;]
public static implicit operator _(
_ v)[return ;]
_ ,
; _ ,
; v .
_,
.
implicit,
, .. ,
_.
explicit,
. , ,
explicit-, implicit- .
ThreeD. ,
246
I. C#
ThreeD ,
int.
.
implicit- , :
public static implicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
,
.
// implicit- .
using System;
// .
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+".
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
}
// ThreeD int.
public static implicit operator int(ThreeD op1) {
return op1.x * op1.y * op1.z;
}
// X, Y, Z.
public void show()
{
Console.WriteLine(x + ", " + y + ", " + z);
}
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
int i;
Console.Write(" a: ");
a.show();
9.
247
Console.WriteLine();
Console.Write(" b: ");
b.show();
Console.WriteLine();
c = a + b; // b.
Console.Write(" + b: ");
c.show();
Console.WriteLine();
i = a; // int.
Console.WriteLine(
" i = a: " + i);
Console.WriteLine();
i = a * 2 - b; // int.
Console.WriteLine(
" * 2 - b: " + i);
:
a: 1, 2, 3
b: 10, 10, 10
+ b: 11, 12, 13
i = a: 6
* 2 - b: -988
, ThreeD
( i = ),
.
6, , .
int-,
. c = + b
operator int() .
,
. ,
- double- long-.
.
,
, ,
,
.
, .
. , ,
,
int:
// .
using System;
// .
248
I. C#
class ThreeD {
int x, y, z; // 3-- .
public ThreeD() {
x = y = z = 0;
}
public ThreeD(int i, int j, int k) {
x = i;
y = j;
z = k;
}
// "+".
public static ThreeD operator +(ThreeD op1, ThreeD op2)
{
ThreeD result = new ThreeD();
result.x = op1.x + op2.x;
result.y = op1.y + op2.y;
result.z = op1.z + op2.z;
return result;
}
// explicit-.
public static explicit operator int(ThreeD op1)
{
return op1.x * op1.y * op1.z;
}
// X, Y, Z,
public void show()
{
Console.WriteLine(x + ", " + y + ", " + z);
}
}
class ThreeDDemo {
public static void Main() {
ThreeD a = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
ThreeD c = new ThreeD();
int i;
Console.Write(" a: ");
a.show();
Console.WriteLine();
Console.Write(" b: ");
b.show();
Console.WriteLine();
c = a + b; // b.
Console.Write(" + b: ");
c.show();
Console.WriteLine();
i = (int) a; //
// int,
// .
Console.WriteLine(" i = a: " + i);
Console.WriteLine();
i = (int)a * 2 - (int)b; // .
9.
249
Console.WriteLine(
" * 2 - b: " + i);
explicit, int
. ,
i = (int) a;
, .
.
. ,
double int.
Object .
,
.
. (
. 11.)
. (
. 12.)
,
.
, . ,
. -,
, , . -,
.
,
.
,
,
C#-.
. ,
+, ThreeD, +,
.
, , +,
(/). ,
( ) ,
.
250
I. C#
.
. , ,
.
. ,
( , +=).
, .
&&
||
[]
()
new
is
sizeof
typeof
?
->
.
=
(())
, , , ,
.
, +=. ,
,
. , +=
operator+(). , ThreeD.
ThreeD = new ThreeD(1, 2, 3);
ThreeD b = new ThreeD(10, 10, 10);
b += a; // b.
operator+() ThreeD,
b 11,12,13.
.
([]), (operator()),
, .
ThreeD. ,
.
,
, , .
, . , ,
,
.
. ,
nybble. ,
1 nybble,
.
,
. nybble-
.
Nybble,
. int,
015.
:
Nybble- Nybble-;
9.
251
int- Nybble-;
Nybble- int-;
(>) (<);
;
int- Nybble-;
Nybble- int-.
, ,
C#.
Nybble, .
.
Nybble, NybbleDemo,
.
// 4- Nybble.
using System;
// 4- .
class Nybble {
int val; // - int.
public Nybble() {
val = 0;
}
public Nybble(int i) {
val = i;
val = val & 0xF; // 4 .
}
// "+"
// Nybble + Nybble.
public static Nybble operator +(Nybble op1, Nybble op2)
{
Nybble result = new Nybble();
result.val = op1.val + op2.val;
result.val = result.val & 0xF;
//
// 4 .
return result;
}
// "+"
// Nybble + int.
public static Nybble operator +(Nybble op1, int op2)
{
Nybble result = new Nybble();
result.val = op1.val + op2;
result.val = result.val & 0xF;
//
// 4 .
return result;
}
252
I. C#
// "+"
// int + Nybble.
public static Nybble operator +(int op1, Nybble op2)
{
Nybble result = new Nybble();
result.val = op1 + op2.val;
result.val = result.val & 0xF;
//
// 4 .
return result;
}
// "++".
public static Nybble operator ++(Nybble op)
{
op.val++;
op.val = op.val & 0xF;
//
// 4 .
return op;
}
// ">".
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 {
public static void Main() {
Nybble a = new Nybble(1);
Nybble b = new Nybble(10);
Nybble c = new Nybble();
int t;
Console.WriteLine("a: " + (int) a);
9.
253
:
a: 1
b: 10
b
c = + b: 11
+= 5: 6
* 2 + 3: 15
= 19: 3
for- Nybble-. 0123456789
, .
Nybble
254
I. C#
9.
255
10
,
: .
, C# .
,
, .
.
, C#: ,
.
, [].
, operator(),
(indexer).
.
,
. ,
.
, .
.
_ this[int ] {
// .
get {
// , .
}
// .
set {
// ,
// .
}
}
_ . , _
, .
.
( ) . ,
int,
, .
( ) get
set. ,
.
, .
, set
, .
get , c.
10.
257
set ( value),
, .
,
, .
. FailSoftArray ,
,
.
.
,
, .
FailSoftArray ,
([]).
//
// .
using System;
class FailSoftArray {
int[] a; // .
public int Length;
// Length - .
public bool errflag; //
// .
// .
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}
// - FailSoftArray.
public int this[int index] { // - get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
}
else {
errflag = true;
return 0;
}
}
// - set-.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else
errflag = true;
}
}
// true,
258
I. C#
// - .
private bool ok(int index) {
if(index >= 0 & index < Length)
return true;
return false;
}
}
// .
class FSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
int x;
// " " .
Console.WriteLine(" .");
for(int i=0; i < (fs.Length * 2); i++)
fs[i] = i*10;
for(int i=0; i < (fs.Length * 2); i++) {
x = fs[i];
if(x != -1) Console.Write(x + " ");
}
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]
10.
259
.
. :
public int this[int index] {
, int.
index.
.
get.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;
}
}
get .
, get ,
. ,
, .
FailSoftArray errflag .
, , .
set().
.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;
}
, ,
value, .
errflag true. ,
value ,
, . ( )
.
get-, set-.
, , get. , ,
set-.
.
FailSoftArray, double.
double- .
, ,
,
.
260
I. C#
// FailSoftArray.
using System;
class FailSoftArray {
int[] a; // .
public int Length; // Length () - .
public bool errflag; //
// .
// .
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}
// int- FailSoftArray.
public int this[int index] { // get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
}
else {
errflag = true;
return 0;
}
}
// set-.
set {
if(ok(index)) {
a[index] = value;
errflag = false;
}
else errflag = true;
}
}
/* FailSoftArray.
double-.
. */
public int this[double idx] { // get-.
get {
int index;
// int-.
if( (idx - (int) idx) < 0.5)
index = (int) idx;
else
index = (int) idx + 1;
if(ok(index)) {
errflag = false;
return a[index];
} else {
10.
261
errflag = true;
return 0;
// set-.
set {
int index;
// int-.
if( (idx - (int) idx) < 0.5)
index = (int) idx;
else
index = (int) idx + 1;
if(ok(index)) {
a[index] = value;
errflag = false;
}
else
errflag = true;
}
}
// true, .
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;
}
}
// .
class FSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// 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[1.1]);
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.
262
I. C#
, ,
, . ,
,
.
. ,
, ,
, . , ,
, .
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 {
public static void Main() {
PwrOfTwo pwr = new PwrOfTwo();
Console.Write(" 8 2: ");
for(int i=0; i < 8; i++)
Console.Write(pwr[i] + " ");
Console.WriteLine();
Console.Write(" : ");
Console.Write(pwr[-1] + " " + pwr[17]);
Console.WriteLine();
10.
263
:
8 2: 12 4 8 16 32 64 128
: -1 -1
, UsePwrOfTwo get, set-. ,
. , UsePwrOfTwo
, . ,
, :
pwr[0] = 11; //
,
set-.
. -,
,
ref- out-. -,
,
static.
. ,
.
.
// .
using System;
class FailSoftArray2D {
int[,] a; // .
int rows, cols; //
public int Length; // Length - .
public bool errflag; //
// .
// .
public FailSoftArray2D(int r, int ) {
rows = r;
cols = ;
a = 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 {
errflag = true;
return 0;
}
}
264
I. C#
// 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 {
public static void Main() {
FailSoftArray2D fs = new FailSoftArray2D(3, 5);
int x;
// " " .
Console.WriteLine(" .");
for(int i=0; i < 6; i++)
fs[i, i] = i*10;
for(int i=0; i < 6; i++) {
x = fs[i, i ];
if(x != -1) Console.Write(x + " ");
}
Console.WriteLine();
// .
Console.WriteLine(
"\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 + " ");
else
Console.WriteLine(
"fs[" + i + ", " + i + "] ");
}
}
}
10.
265
, :
. 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{
//
}
(, int), .
.
set value,
, .
, . ,
, .
.
, myprop,
prop.
.
// .
using System;
266
I. C#
class SimpProp {
int prop; // myprop.
public SimpProp() {
prop =0;
}
/*
prop.
. */
public int myprop {
get {
return prop;
}
set {
if(value >= 0)
prop = value;
}
}
}
// .
class PropertyDemo {
public static void Main() {
SimpProp ob = new SimpProp();
Console.WriteLine(" ob.myprop: " +
ob.myprop);
ob.myprop = 100; // .
Console.WriteLine(" ob.myprop: " +
ob.myprop);
// prop
// .
Console.WriteLine(
" -10 ob.myprop");
ob.myprop = -10;
Console.WriteLine(" ob.myprop: " + ob.myprop);
}
}
:
ob.myprop: 0
ob.myprop: 100
-10 ob.myprop
ob.myprop: 100
. SimpProp
prop myprop, prop.
, ,
.
. , prop ,
myprop.
myprop public- ,
, .
, prop
: get- prop, a set-
prop, . ,
10.
267
myprop , prop.
.
myprop ,
, .
, ( get) ( set-).
,
. ,
Length. FailSoftArray
Length. ,
Length ,
. (, -
.) ,
Length , ,
FailSoftArray.
// FailSoftArray Length.
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;
}
}
// FailSoftArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = false;
return a[index];
} else {
errflag = true;
return 0;
}
}
// set-.
set {
if(ok(index)) {
a[index] = value;
268
I. C#
errflag = false;
}
else errflag = true;
// true, .
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;
}
// .
class ImprovedFSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
int x;
// Length .
for(int i=0; i < fs.Length; i++)
fs[i] = i*10;
for(int i=0; i < fs.Length; i++) {
x = fs[i];
if(x != -1) Console.Write(x + " ");
}
Console.WriteLine();
// fs.Length = 10; // , !
Length ,
len. get-,
Length , . ,
:
// fs.Length = 10; // , !
, , Length .
FailSoftArray Length ,
. errflag
,
.
FailSoftArray, Error,
errflag.
// errflag .
using System;
class FailSoftArray {
int[] a; // .
int len; // .
10.
269
bool errflag; // .
// .
public FailSoftArray(int size) {
a = new int[size];
len = size;
}
// Length .
public int Length {
get {
return len;
}
}
// Error .
public bool Error {
get {
return errflag;
}
}
// - FailSoftArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = 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 FinalFSDemo {
public static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// Error.
270
I. C#
Error FailSoftArray
. -, errflag ,
Error.
errflag . -,
Error, .
errflag, Error.
Main(), ,
Error.
. -,
,
ref- out-. -, . (
,
, .) ,
get-,
.
, get- .
,
. RangeArray,
,
.
, C# .
,
,
-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 (
ra), -5 10 .
, .
10.
271
RangeArray RangeArrayDemo,
. RangeArray int-,
.
/*
. RangeArray
, .
RangeArray
.
. ,
-5 5, 1 10 50 56. */
using System;
class RangeArray {
// .
int[] a; // .
int lowerBound; // .
int upperBound; // .
// .
int len; // Length.
bool errflag; // Error.
// .
public RangeArray(int low, int high) {
high++;
if(high <= low) {
Console.WriteLine(" .");
high = 1; //
// .
low = 0;
}
a = new int[high - low];
len = high - low;
lowerBound = low;
upperBound = --high;
}
// Length, .
public int Length {
get {
return len;
}
}
// Error, .
public bool Error {
get {
return errflag;
}
}
// RangeArray.
public int this[int index] {
272
I. C#
// get-.
get {
if(ok(index)) {
errflag = false;
return a[index - lowerBound];
} else {
errflag = true;
return 0;
}
}
// set-.
set {
if(ok(index)) {
a[index - lowerBound] = value;
errflag = false;
}
else errflag = true;
}
}
// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return true;
return false;
}
}
//
// .
class RangeArrayDemo {
public 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: " + 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++)
10.
273
Console.WriteLine("\n");
:
ra: 11
ra: -5 -4 -3 -2 -1 0 1 2 3 4 5
ra2: 10
r2: 1 2 3 4 56 7 8 9 10
ra3: 9
ra3: -20 -19 -18 -17 -16 -15 -14 -13 -12
,
RangeArray . ,
RangeArray.
:
// .
int[] ; // .
int lowerBound; // .
int upperBound; // .
// .
int len; // Length.
bool errflag; // Error.
.
RangeArray.
lowerBound, upperBound.
, Length Error.
RangeArray :
// .
public RangeArray(int low, int high) {
high++;
if(high <= low) {
Console.WriteLine(" .");
high = 1;
//
// .
low = 0;
274
I. C#
RangeArray
low high.
high , ,
low high . ,
. ,
.
( , ),
. len ( Length)
. ,
lowerBound upperBound.
RangeArray Length Error.
.
// Length, .
public int Length {
get {
return len;
}
}
// Error, .
public bool Error {
get {
return errflag;
}
}
, FailSoftArray,
.
RangeArray . :
// RangeArray.
public int this[int index] {
// get-.
get {
if(ok(index)) {
errflag = false;
return a[index - lowerBound];
} else {
errflag = true;
return 0;
}
}
// set-.
set {
if(ok(index)) {
a[index - lowerBound] = value;
errflag = false;
} else
errflag = true;
10.
275
}
}
FailSoftArray,
. ,
.
index - lowerBound
, index,
, .. , ,
.
.
lowerBound: , .
ok().
// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return true;
return false;
}
, FailSoftArray
,
lowerBound upperBound.
RangeArray ,
.
( ),
. .
276
I. C#
11
,
. ,
, , .
,
, .
C# , , . ,
, . ,
. ,
, , , , ,
.
C# ,
. .
. TwoDShape,
(, ,
, ..).
// .
class TwoDShape {
public double width;
public double height;
TwoDShape (..
) , .
, TwoDShape
Triangle. , Triangle.
// .
using System;
// .
class TwoDShape {
public double width;
public double height;
// Triangle TwoDShape.
class Triangle : TwoDShape {
public string style; // .
278
I. C#
// .
public double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
class Shapes {
public 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());
.
t1:
4 4 8
t2: 8
12 48
Triangle TwoDShape,
. Triangle TwoDShape
, , style, area() showStyle(). style
, area() ,
showStyle() .
, Triangle,
TwoDShape.
class Triangle : TwoDShape {
11.
279
. ,
,
. C#
.
Triangle , TwoDShape,
width height area(). ,
Main() t1 t2 width height,
Triangle. TwoDShape
Triangle . 11.1.
width
TwoDShape
height
showDim()
style
Triangle
area
showStyle()
. 11.1. Triangle
TwoDShape Triangle,
. ,
(), .
, :
TwoDShape shape = new TwoDShape();
shape.width = 10;
shape.height = 20;
shape.showDim();
, TwoDShape
, TwoDShape.
, , :
class __ : __ {
//
}
.
C# ( C++)
. C++- C#.
,
. ,
( , ) .
, , ,
,
.
. ,
, TwoDShape ,
:
280
I. C#
// Rectangle,
// TwoDShape.
class Rectangle : TwoDShape {
// true,
// .
public bool isSquare() {
if(width == height) return true;
return false;
}
// .
public double area() {
return width * height;
}
8, ,
.
, . ,
, ,
, . ,
, width height private- TwoDShape,
Triangle ,
// .
// .
using System;
// .
class TwoDShape {
double width; // private-.
double height; // private-.
public void showDim() {
Console.WriteLine(" " +
width + " " + height);
}
}
// Triangle TwoDShape.
class Triangle : TwoDShape {
public string style; // .
// .
public double area() {
return width * height /2;
}
11.
// ,
//
// .
281
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
}
Triangle , width height
area() . width
height , .
.
.
, ,
.
,
. ,
C# .
protected-, .
,
. , C#-
. TwoDShape,
width height .
//
// .
using System;
// .
class TwoDShape {
double pri_width; // private-.
double pri_height; // private-.
// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
// - TwoDShape.
class Triangle : TwoDShape {
public string style; // .
// .
public double area() {
return width * height / 2;
282
I. C#
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
class Shapes2 {
public 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();
.
Java. Java
C#. Java C#. ,
, C#-. C++
/ .
,
. , , ,
, . ,
, .
, , C#
. , ,
.
protected.
protected- , .
, .
,
, . ,
protected, (
11.
283
) ,
.
.
// .
using System;
class {
protected int i, j;
// ,
// D.
public void set(int a, int b) {
i = a;
j = b;
}
class D : {
int k; // .
// D i j .
public void setk() {
k = i * j;
}
class ProtectedDemo {
public static void Main() {
D ob = new D();
D i j
(.. protected),
setk() . i j
, D , .
public private protected
.
,
,
,
.
284
I. C#
,
. :
? ,
? : ,
, ,
. ,
.
.
, C#,
.
, , .
,
: . ,
,
. , Triangle,
. style private-,
.
// Triangle.
using System;
// .
class TwoDShape {
double pri_width; // .
double pri_height; // .
// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public void showDim() {
Console.WriteLine(" " +
width + " " + height);
}
// - TwoDShape.
class Triangle : TwoDShape {
string style; // .
// .
public Triangle(string s, double w, double h) {
width = w; // .
height = h; // .
11.
285
style = s; // .
}
// .
public double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
class Shapes3 {
public static void Main() {
Triangle t1 = new Triangle("",
4.0, 4.0);
Triangle t2 = new Triangle("",
8.0, 12.0);
Console. WriteLine(" t1: ");
t1.showStyle();
t1.showDim();
Console.WriteLine(" " + t1.area());
Console.WriteLine();
Triangle
TwoDShape, style.
, ,
,
. C# base,
:
, .
base.
,
,
base. :
__(
_) : base(_) {
//
}
_ ,
.
286
I. C#
, base,
TwoDShape. ,
width height.
// TwoDShape.
using System;
// .
class TwoDShape {
double pri_width; // .
double pri_height; // .
// TwoDShape.
public TwoDShape(double w, double h) {
width = w;
height = h;
}
// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// .
public Triangle(string s,
double w,
double h) : base(w, h) {
style = s;
}
// .
public double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
11.
287
class Shapes4 {
public static void Main() {
Triangle t1 = new Triangle("", 4.0, 4.0);
Triangle t2 = new Triangle("", 8.0, 12.0);
Console.WriteLine(" t1: ");
t1.showStyle();
t1.showDim();
Console. WriteLine(" " + t1.area());
Console.WriteLine();
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 x) {
width = height = x;
}
288
I. C#
// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public void showDim() {
Console.WriteLine(" " +
width + " " + height);
}
}
// , TwoDShape.
class Triangle : TwoDShape {
string 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 {
public 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();
11.
289
t1. showDim();
Console.WriteLine(" " + t1.area());
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
4 8
t3:
4 4
8
base-.
base- .
, base ,
.
. ,
base().
base ,
.
,
.
. C#
,
.
. ,
290
I. C#
new. ,
new .
.
// .
using System;
class A {
public int i = 0;
}
// .
class : A {
new int i; // i i A.
public (int b) {
i = b; // i .
}
class NameHiding {
public static void Main() {
ob = new (2);
ob.show();
-, new
i B. , , ,
i, i
. new, .
:
i : 2
i,
i, . ,
show() B, i,
B, .
base
base,
this, , base
, .
:
base.
11.
291
,
. base ,
.
:
// base .
using System;
class A {
public int i = 0;
}
// .
class B : A {
new int i; // i i .
public B(int a, int b) {
base.i = a; // i .
i = b; // i B.
}
class UncoverName {
public static void Main() {
B ob = new B(1, 2);
ob.show();
:
i : 1
i : 2
i i
, base i .
base .
.
// .
using System;
class A {
public int i = 0;
// show() .
public void show() {
Console.WriteLine("i : " + i);
}
292
I. C#
}
// .
class B : A {
new int i; // i
// A.
public B(int a, int b) {
base.i = a; //
// i .
i = b; // i B.
}
// show(),
// .
// new.
new public void show() {
base.show(); // show() .
// i B.
Console.WriteLine("i : " + i);
}
class UncoverName {
public static void Main() {
B ob = new B(1, 2);
ob.show();
:
i : 1
i : 2
, base.show()
show(), .
, new
,
show(), show(), .
,
. ,
. ,
. ,
(, B C) B, , ,
.
. C B A.
, ,
. Triangle
ColorTriangle.
11.
293
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
/* .
TwoDShape. */
public Triangle() {
style = "null";
}
// .
public Triangle(string s, double w, double h) : base(w, h) {
style = s;
294
I. C#
// .
public Triangle(double x) : base(x) {
style = "";
}
// .
public double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
// .
class ColorTriangle : Triangle {
string color;
public ColorTriangle(
string c, string s,
double w, double h) : base(s, w, h) {
color = c;
}
// .
public void showColor() {
Console.WriteLine(" " + color);
}
}
class Shapes6 {
public static void Main() {
ColorTriangle t1 =
new ColorTriangle("", "",
8.0, 12.0);
ColorTriangle t2 =
new ColorTriangle("", "",
2.0, 2.0);
Console.WriteLine(" t1: ");
t1.showStyle();
t1.showDim();
t1.showColor();
Console.WriteLine(" " + t1.area());
Console.WriteLine();
11.
295
.
t1:
8 12
48
t2:
2 2
2
ColorTriangle
Triangle TwoDShape, ,
() .
: .
: base
. , ColorTriangle
base , Triangle. Triangle
base , TwoDShape.
,
, ,
.
:
? , B ,
B, ? .
, ..
.
, , base.
base , (..
) .
:
// .
using System;
// .
class A {
public A() {
Console.WriteLine(" A.");
}
}
// , A.
class B : A {
public B() {
Console.WriteLine(" B.");
}
296
I. C#
}
// , B.
class C : B {
public C() {
Console.WriteLine(" C.");
}
}
class OrderOfConstruction {
public static void Main() {
C c = new C();
}
}
, :
.
.
.
, .
. ,
, ,
. , ()
() ,
. -
.
, C# .
, ,
. ,
. , ,
:
// .
class X {
int a;
public X(int i) {
a = i;
}
}
class Y {
int a;
public Y(int i) {
a = i;
}
}
class IncompatibleRef {
public static void Main() {
X x = new X(10);
X x2;
11.
297
Y y = new Y(5);
x2 = x; // OK, .
x2 = y; // , .
}
X Y ,
Y X,
.
.
C#-
.
, . .
//
// .
using System;
class X {
public int a;
public X(int i) {
a = i;
}
class Y : X {
public int b;
class BaseRef {
public static void Main() {
X x = new X(10);
X x2;
Y y = new Y(5, 6);
x2 = x; // OK, .
Console.WriteLine("x2.a: " + x2.a);
x2 = y;
// ok, Y
// X.
Console.WriteLine("x2.a: " + x2.a);
//
}
// - "" X.
x2.a = 19; //
x2.b = 27; // , X b.
Y X, x2
Y.
298
I. C#
, ( ,
) , . ,
,
, .
x2 b Y ,
Y. ,
, .
.
,
. ,
.
, .
, ,
.
. , ,
. , , 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 x) {
width = height = x;
}
// .
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
}
// width height.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
11.
299
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// .
public Triangle() {
style = "null";
}
// Triangle.
public Triangle(string s,
double w,
double h) : base(w, h) {
style = s;
}
// .
public Triangle(double x) : base(x) {
style = "";
}
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}
// .
public double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
class Shapes7 {
public static void Main() {
Triangle t1 = new Triangle("", 8.0, 12.0);
// t1.
Triangle t2 = new Triangle(t1);
Console.WriteLine(" t1: ");
t1.showStyle();
t1.showDim();
300
I. C#
t2 t1 .
:
t1:
8 12
48
t2:
8 12
4 8
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
.
,
. : ,
.
, C#
11.
301
, , ,
. , ,
. ,
, ( ) ,
. ,
,
( )
.
,
virtual.
override. ,
(method
overriding). . ,
( static) (
abstract, ).
C#: .
, .
C# .
,
.
// .
using System;
class Base {
// .
public virtual void who() {
Console.WriteLine(" who() Base.");
}
}
class Derived1 : Base {
// who() .
public override void who() {
Console.WriteLine(" who() Derived1");
}
}
class Derived2 : Base {
// who()
// .
public override void who() {
Console.WriteLine(" who() Derived2");
}
}
class OverrideDemo {
public static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
Derived2 dOb2 = new Derived2();
302
I. C#
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(). ,
, ,
baseRef.
.
, ,
. :
/*
,
. */
using System;
class Base {
// .
public virtual void who() {
Console.WriteLine(" who() Base");
}
}
class Derived1 : Base {
// who() .
public override void who() {
Console.WriteLine(" who() Derived1");
}
}
class Derived2 : Base {
// who().
}
class NoOverrideDemo {
public static void Main() {
Base baseOb = new Base();
Derived1 dOb1 = new Derived1();
11.
303
:
who() Base
who() Derived1
who() Base
Derived2 who().
who() Derived2 who(),
Base.
, ,
.
.
/*
,
,
. */
using System;
class Base {
// .
public virtual void who() {
Console.WriteLine(" who() Base");
}
}
class Derived1 : Base {
// who() .
public override void who() {
Console.WriteLine(" who() Derived1");
}
}
class Derived2 : Derived1 {
// who().
}
class Derived3 : Derived2 {
// who().
}
class NoOverrideDemo2 {
304
I. C#
Base baseRef; // .
baseRef = dOb;
baseRef.who();
// who()
// Derived1.
:
who() Derived1
Derived3 Derived2,
Derived1, Base.
, who()
Derived3, Derived2, Derived1,
who() ( Derived1) ,
.
.
virtual, override.
C# .
- ,
,
,
.
C# ,
.
(, )
, ,
.
, ..
. , ,
.
, -
. ,
() ,
, .
,
TwoDShape. , TwoDShape,
area(). ,
area() TwoDShape,
,
, .
. TwoDShape
name, .
11.
305
// .
using System;
class TwoDShape {
double pri_width; // .
double pri_height; // .
string pri_name; // .
// .
public TwoDShape() {
width = height = 0.0;
name = "null";
}
// .
public TwoDShape(double w, double h, string n) {
width = w;
height = h;
name = n;
}
// , .
public TwoDShape(double x, string n) {
width = height = x;
name = n;
}
// .
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
// width, height name.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
}
public string name {
get { return pri_name; }
set { pri_name = value; }
}
public void showDim() {
Console.WriteLine(" " +
width + " " + height);
}
public virtual double area() {
Console.WriteLine(
306
I. C#
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// .
public Triangle() {
style = "null";
}
// .
public Triangle(string s, double w, double h) :
base(w, h, "") {
style = s;
}
// .
public Triangle(double x) : base(x, "") {
style = "";
}
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}
// area() Triangle.
public override double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
// , TwoDShape.
class Rectangle : TwoDShape {
// .
public Rectangle(double w, double h) :
base(w, h, ""){ }
// .
public Rectangle(double x) :
base(x, "") { }
// .
public Rectangle(Rectangle ob) : base(ob) { }
// true, - .
public bool isSquare() {
if(width == height) return true;
return false;
11.
307
}
// area() Rectangle.
public override double area() {
return width * height;
}
class DynShapes {
public static void Main() {
TwoDShape[] shapes = new TwoDShape[5];
shapes[0] = new Triangle("", 8.0, 12.0);
shapes[1] = new Rectangle(10);
shapes[2] = new Rectangle(10, 4);
shapes[3] = new Triangle(7.0);
shapes[4] = new TwoDShape(10, 20,
" ");
for(int i=0; i < shapes.Length; i++) {
Console.WriteLine(" " +
shapes[i].name);
Console.WriteLine(" " +
shapes[i].area());
Console.WriteLine();
}
}
}
:
48
100
40
24,5
area() .
0
. -, area()
TwoDShape virtual
Triangle Rectangle. TwoDShape area()
, ,
. area()
,
. ,
, area() .
.
, Main() shapes
308
I. C#
TwoDShape.
Triangle, Rectangle TwoDShape. ,
.
shapes, .
, , .
, ,
, , ..
, .
TwoDShape, area().
,
.
,
, ,
. ,
,
. ,
.
TwoDShape ( ),
area() ,
, , .
, , ,
() , -
. . ,
,
.
(, ),
. .
,
. Triangle. ,
area(). ,
. C#
.
abstract.
, , .
,
, . ,
,
virtual. ,
virtual abstract .
.
abstract (_);
, . abstract
, static-.
.
, ,
abstract,
class. ,
11.
309
, . ,
new
.
,
.
. , abstract
, .
,
TwoDShape.
, area()
TwoDShape , , , TwoDShape.
, , , TwoDShape,
area().
// .
using System;
abstract class TwoDShape {
double pri_width; // .
double pri_height; // .
string pri_name; // .
// .
public TwoDShape() {
width = height = 0.0;
name = "null";
}
// .
public TwoDShape(double w, double h, string n) {
width = w;
height = h;
name = n;
}
// , .
public TwoDShape(double x, string n) {
width = height = x;
name = n;
}
// .
public TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
name = ob.name;
}
// width, height name.
public double width {
get { return pri_width; }
set { pri_width = value; }
}
public double height {
get { return pri_height; }
set { pri_height = value; }
310
I. C#
}
// , TwoDShape.
class Triangle : TwoDShape {
string style; // .
// .
public Triangle() {
style = "null";
}
// .
public Triangle(string s, double w, double h) :
base(w, h, "triangle") {
style = s;
}
// .
public Triangle(double x) : base(x, "") {
style = "";
}
// .
public Triangle(Triangle ob) : base(ob) {
style = ob.style;
}
// area() Triangle.
public override double area() {
return width * height / 2;
}
// .
public void showStyle() {
Console.WriteLine(" " + style);
}
// , TwoDShape.
class Rectangle : TwoDShape {
// .
public Rectangle(double w, double h) :
base(w, h, ""){ }
// .
11.
311
public Rectangle(double x) :
base(x, "") { }
// .
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 {
public static void Main() {
TwoDShape[] shapes = new TwoDShape[4];
shapes[0]
shapes[1]
shapes[2]
shapes[3]
=
=
=
=
new
new
new
new
,
area(), .
, , area().
(.. ) . ,
TwoDShape, .
TwoDShape. Main()
shapes 4,
TwoDShape.
, TwoDShape -
showDim(), abstract.
( )
, . ,
abstract,
.
312
I. C#
sealed
,
. , ,
,
.
,
. C#
sealed.
,
sealed. ,
abstract sealed,
, ..
.
sealed-.
sealed class {
// ...
}
// .
class : { // ! .
// ...
}
B ,
sealed-.
object
C# object,
( ). ,
object. ,
object . , C#-
, object
. , C#- object System.Object,
.NET Framework.
object , . 11.1.
.
11.1. object
,
, , ob
, b1 ,
b2
11.
313
. 11.1
protected Finalize()
. C# Finalize()
-,
" " , ..
, ,
, b1 b2
. Equals(object) ,
, , , ..
, . true,
, false .
. ,
. , Equals(object),
( , ).
Equals(object,
object)
Equals(object).
GetHashCode() -, .
- ,
, ,
9, ==
Equals(object) GetHashCode(),
== Equals(object), , .
Equals(object),
GetHashCode(), .
ToString() , ,
. , ToString()
WriteLine(). ToString()
,
, . :
// ToString().
using System;
class MyClass {
static int count = 0;
int id;
public MyClass() {
id = count;
count++;
}
public override string ToString() {
return " MyClass #" + id;
314
I. C#
class Test {
public static void Main() {
MyClass ob1 = new MyClass();
MyClass ob2 = new MyClass();
MyClass ob3 = new MyClass();
Console.WriteLine(ob1);
Console.WriteLine(ob2);
Console.WriteLine(ob3);
:
MyClass #0
MyClass #1
MyClass #2
, C#-, ,
object. , object
, . object
,
(boxing).
, . ,
.
.
.
object. C#.
(unboxing)
.
, .. object
.
,
.
// "" "".
using System;
class BoxingDemo {
public static void Main() {
int x;
object obj;
x = 10;
obj = x; // "" x .
int y = (int)obj; // ""
// obj int-.
Console.WriteLine(y);
}
}
11.
315
10. ,
x obj,
object. ,
obj, int.
( ) .
int- sqr(),
object.
//
// .
using System;
class BoxingDemo {
public static void Main() {
int x;
x = 10;
Console.WriteLine(" x : " + x);
// x
// sqr().
x = BoxingDemo.sqr(x);
Console.WriteLine(" x : " + x);
:
x : 10
x : 100
x sqr()
.
C#-
. object.
object .
, . ,
object, . , ,
, .
// ""
// object !
using System;
class MethOnValue {
316
I. C#
10. , ToString()
, .
10 10!
object
, object C#-
, object .
, ,
object, .
// object
// .
using System;
class GenericDemo {
public static void Main() {
object[] ga = new object[10];
// int-.
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] = "";
:
ga[0]: 0
ga[1]: 1
ga[2]: 2
ga[3]: 1,5
ga[4]: 2
ga[5]: 2,5
ga[6]:
ga[7]: True
ga[8]: X
ga[9]:
,
object . ,
11.
317
object .
, object- .
, , object.
.
, object,
, , object
C#- . ,
int- int-, string-
string- .. object .
318
I. C#
12
,
C#: .
, .
. , ,
, .
C#: .
, , ,
. .
, C#.
- ,
, .
. ,
. ,
, -. ,
, .
, . C#
interface.
.
, ..
. , , , .
, .
.
( )
, .
. ,
, .
, , ,
, .
,
, C# ,
.
interface.
:
interface {
_ _1(_);
_ _2(_);
// ...
_ _N(_);
}
.
. , ,
. ,
. , , ,
. (public), .
320
I. C#
, ,
public interface ISeries {
int getNext(); // .
void reset(); // .
void setStart(int x);
//
// .
}
ISeries. I ,
, .
ISeries ,
.
,
. 15,
, .
. , .
, .
, , .
, ,
. ,
, :
class _ : _ {
//
}
,
_.
, , ..
.
.
.
.
.
, , .
, ,
. ,
,
.
ISeries,
. ByTwos, ,
.
// ISeries.
class ByTwos : ISeries {
int start;
int val;
public ByTwos() {
start = 0;
val = 0;
}
public int getNext() {
12. ,
321
, ByTwos ,
ISeries. ,
.
, ByTwos, :
// ,
// ByTwos.
using System;
class SeriesDemo {
public 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
(IDE) Visual Studio,
C#-. .
322
I. C#
:.
2
4
6
8
10
.
2
4
6
8
10
100.
102
104
106
108
110
, ,
. , ByTwos
getPrevious(), .
// ISeries
// getPrevious().
class ByTwos : ISeries {
int start;
int val;
int prev;
public ByTwos() {
start = 0;
val = 0;
prev = -2;
}
public int 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;
}
12. ,
323
, getPrevious()
, ISeries.
,
, .
.
, .
, , 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 + 1); j++) {
if((i%j)==0) {
isprime = false;
break;
}
}
if(isprime) {
val = i;
break;
}
}
return val;
}
public void reset() {
val = start;
}
, , Primes ByTwos
, ISeries.
, ,
.
324
I. C#
, , ,
. , -
. ,
.
, .
(. 11).
.
-,
ByTwos, Primes.
// .
using System;
// .
public interface ISeries {
int getNext(); // .
void reset(); // .
void setStart(int x);
//
// .
}
// ISeries
// .
class ByTwos : ISeries {
int start;
int val;
public ByTwos() {
start = 0;
val = 0;
}
public int getNext() {
val +=2;
return val;
}
public void reset() {
val = start;
}
// ISeries
// .
class Primes : ISeries {
int start;
int val;
12. ,
325
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 + 1); 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 {
public 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());
}
}
}
:
2
3
4
5
326
I. C#
6
7
8
11
10
13
Main() ob ISeries.
, ,
ISeries. twoOb
primeOb, ByTwos Primes, ,
, ISeries.
, "
, interface. ,
, ,
.
, .
.
//
{
get;
set;
}
, ,
get- set-, .
ISeries ByTwos,
.
// .
using System;
public interface ISeries {
// .
int next {
get; // .
set; // .
}
}
// ISeries.
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
}
// .
public int next {
get {
12. ,
327
val +=2;
return val;
}
set {
val = value;
}
}
}
// .
class SeriesDemo3 {
public 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);
:
2
4
6
8
10
21
23
25
27
29
31
.
:
//
_ this[int ]{
get;
set;
}
, ,
get- set-, .
ISeries, ,
.
328
I. C#
// .
using System;
public interface ISeries {
// .
int next {
get; // .
set; // .
}
// .
int this[int index] {
get; // .
}
}
// ISeries.
class ByTwos : ISeries {
int val;
public ByTwos() {
val = 0;
}
//
// .
public int next {
get {
val += 2;
return val;
}
set {
val = value;
}
}
// .
public int this[int index] {
get {
val = 0;
for(int i=0; i<index; i++)
val += 2;
return val;
}
}
// .
class SeriesDemo4 {
public static void Main() {
ByTwos ob = new ByTwos();
// .
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);
12. ,
329
Console.WriteLine("\naae 21");
ob.next = 21;
for(int i=0; i < 5; i++)
Console.WriteLine(" " +
ob.next);
Console.WriteLine("\n .");
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
.
0
2
4
6
8
.
, .
, ,
,
. :
// .
using System;
public interface A {
void meth1();
void meth2();
}
// meth1() meth2(),
// meth3().
330
I. C#
public interface : A {
void meth3();
}
//
// .
class MyClass : {
public void meth1() {
Console.WriteLine(" meth1().");
}
public void meth2() {
Console.WriteLine(" meth2().");
}
class IFExtend {
public static void Main() {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
meth1(),
MyClass,
. , , ,
, , ,
.
, ,
. .
,
new.
. ,
, . ,
12. ,
331
interface IMyIF {
int myMeth(int x);
}
IMyIF :
class MyClass : IMyIF{
int IMyIF.myMeth(int x) {
return x / 3;
}
}
, myMeth() IMyIF
, .
. , ,
, ,
. -, ,
.
. .
IEven,
isEven() isOdd(), ,
. MyClass IEven, isOdd()
.
// .
using System;
interface IEven {
bool isOdd(int x);
bool isEven(int x);
}
class MyClass : IEven {
// .
bool IEven.isOdd(int x) {
if((x%2) != 0) return true;
else return false;
}
// .
public bool isEven(int x) {
IEven o = this; // .
return !o.isOdd(x);
}
class Demo {
public static void Main() {
MyClass ob = new MyClass();
bool result;
result = ob.isEven(4);
if(result) Console.WriteLine("4 - .");
332
I. C#
isOdd() ,
MyClass. .
MyClass isOdd() .
isEven().
, ,
meth(). ,
.
// ,
// .
using System;
interface IMyIF_A {
int meth(int x);
}
interface IMyIF_B {
int meth(int x);
}
// MyClass .
class MyClass : IMyIF_A, IMyIF_B {
// meth().
int IMyIF_A.meth(int x) {
return x + x;
}
int IMyIF_B.meth(int x) {
return x * x;
}
// meth() .
public int methA(int x){
IMyIF_A a_ob;
a_ob = this;
return a_ob.meth(x);
//
// IMyIF_A.
}
public int methB(int x){
IMyIF_B b_ob;
b_ob = this;
return b_ob.meth(x);
}
//
// IMyIF_B
12. ,
333
class FQIFNames {
public static void Main() {
MyClass ob = new MyClass();
Console.Write(" IMyIF_A.meth(): ");
Console.WriteLine(ob.methA(3));
IMyIF_A.meth(): 6
IMyIF_B.meth(): 9
, meth()
IMyIF_A IMyIF_B. , MyClass
, ,
( ).
,
meth(), IMyIF_A, IMyIF_A,
meth(), IMyIF_B,
IMyIF_B. ,
.
C# ,
, , ,
. .
, , .
, (
) .
.NET Framework
.NET Framework ,
C#-. , System.IComparable
CompareTo(), .
,
(, ). , ,
System.Collections.ICollection ,
. System.Collections.IEnumerator
. II.
334
I. C#
:
C#,
.
ICipher, .
,
, , .
ICipher :
// .
public interface ICipher {
string encode(string str);
string decode(string str);
}
ICipher : encode() decode(),
, .
. , , ,
. ,
, .
.
, (
). ,
.
,
.
ICipher :
SimpleCipher BitCipher. SimpleCipher
. ,
, .. BitCipher
-:
, 16-
, .
/* ICipher,
1 . ,
.. */
class SimpleCipher : ICipher {
// ,
// .
public string encode(string str) {
string ciphertext = "";
for(int i=0; i < str.Length; i++)
ciphertext = ciphertext + (char) (str[i] + 1);
return ciphertext;
}
// ,
// .
public string decode(string str) {
string plaintext = "";
12. ,
335
/* ICipher
. */
class BitCipher : ICipher {
ushort key;
//
// BitCipher.
public BitCipher(ushort k) {
key = k;
}
// ,
// .
public string encode(string str) {
string ciphertext = "";
// ,
// .
public string decode(string str) {
string plaintext = "";
, SimpleCipher BitCipher
ICipher, .
SimpleCipher
BitCipher.
// ICipher.
using System;
class ICipherDemo {
public static void Main() {
ICipher ciphRef;
BitCipher bit = new BitCipher(27);
SimpleCipher sc = new SimpleCipher();
string plain;
string coded;
336
I. C#
// ciphRef
// SimpleCipher ( ).
ciphRef = sc;
Console.WriteLine(" .");
plain = "testing";
coded = ciphRef.encode(plain);
Console.WriteLine(" : " + coded);
plain = ciphRef.decode(coded);
Console.WriteLine(" : " + plain);
// ciphRef refer
// BitCipher ( ).
ciphRef = bit;
Console.WriteLine(
"\n .");
plain = "testing";
coded = ciphRef.encode(plain);
:
.
: uftujoh
: testing
.
: o~horu|
: testing
,
, , ,
, . ,
, UnlistedPhone
.
.
// ICipher.
using System;
// .
class UnlistedPhone {
string pri_name; // Name.
string pri_number; // Number.
ICipher crypt; // .
public UnlistedPhone(string name, string number,
ICipher c)
{
12. ,
337
crypt = c; // .
pri_name = crypt.encode(name);
pri_number = crypt.encode(number);
// UnlistedPhone.
class UnlistedDemo {
public static void Main() {
UnlistedPhone phone1 =
new UnlistedPhone("Tom", "555-3456", new BitCipher(27));
UnlistedPhone phone2 =
new UnlistedPhone("", "555-8891", new BitCipher(9));
Console.WriteLine(" " +
phone1.Name + " : " + phone1.Number);
Console.WriteLine(" " +
phone2.Name + " : " + phone2.Number);
:
: 555-3456
: 555-8891
, UnlistedPhone. ,
.
.
ICipher. UnlistedPhone
. , ,
, .
crypt.
, , ,
338
I. C#
ICipher. BitCipher. ,
UnlistedPhone encode() decode()
BitCipher crypt.
Name Number.
set-
encode() , crypt.
get-
decode(). Name, Number
.
.
ICipher, ,
UnlistedPhone. ,
UnlistedPhone SimpleCipher-, BitCipher-.
,
UnlistedPhone.
// SimpleCipher.
using System;
class UnlistedDemo {
public static void Main() {
// Bitcipher
// SimpleCipher.
UnlistedPhone phone1=
new UnlistedPhone("Tom", "555-3456",
new SimpleCipher());
UnlistedPhone phone2 =
new UnlistedPhone("Mary", "555-88 91",
new SimpleCipher());
Console.WriteLine(
" " +
phone1.Name + " : " +
phone1.Number);
Console.WriteLine(
" " +
phone2.Name + " : " +
phone2.Number);
, ICipher
SimpleCipher Bitcipher, UnlistedPhone
.
. UnlistedPhone
, , .
ICipher,
,
ICipher.
, UnlistedPhone.
UnlistedPhone crypt
12. ,
339
(, BitCipher),
UnlistedPhone
.
, . ,
. ,
C# .
, . .
,
, .
.
C# . ,
, .
struct
. :
struct : {
//
}
.
.
. (,
C#-, 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;
}
340
I. C#
}
// Book.
class StructDemo {
public static void Main() {
Book book1 = new Book(
"Herb Schildt",
"C# A Beginner's Guide",
2001);
//
// .
Book book2 = new Book(); //
// .
Book book3; //
// .
Console.WriteLine(book1.title + ", " +
book1.author +
", (c) " + book1.copyright);
Console.WriteLine();
if(book2.title == null)
Console.WriteLine(" book2.title null.");
// book2 .
book2.title = "Brave New World";
book2.author = "Aldous Huxley";
book2.copyright = 1932;
Console.Write(" book2 :\n ");
Console.WriteLine(book2.title + ", " +
book2.author +
", (c) " + book2.copyright);
Console.WriteLine();
// Console.WriteLine(bk3.title);
// :
//
// .
:
C# A Beginner's Guide, Herb Schildt, (c) 2001
book2.title null.
book2 :
Brave New World, Aldous Huxley, (c) 1932
Red Storm Rising
,
new, ,
. new
, (
), ,
. new ,
12. ,
341
bk3, ,
.
.
struct- lass-. ,
, ,
, .
struct- , ,
. , , :
// .
using System;
// .
struct MyStruct {
public int x;
}
// .
class StructAssignment {
public static void Main() {
MyStruct a;
MyStruct b;
a.x = 10;
b.x = 20;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;
.
a.x 10, b.x 20
a.x 20, b.x 30
,
= b;
b - . ,
b, ,
b. b , . class- .
// .
using System;
// .
class MyClass {
public int x;
}
// .
342
I. C#
class ClassAssignment {
public 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;
:
a.x 10, b.x 20
a.x 30, b.x 30
, b
, .. , b.
, C# struct, ,
, class.
. ,
, . , struct
. ,
. , ,
,
. ,
.
. . ,
,
, struct
.
, ,
. .
.
.
, .
.
// .
using System;
// .
struct PacketHeader {
public uint packNum; // .
public ushort packLen; // .
}
12. ,
343
// PacketHeader
// .
class Transaction {
static uint transacNum = 0;
PacketHeader ph;
//
// PacketHeader.
string accountNum;
double amount;
public Transaction(string acc, double val) {
// .
ph.packNum = transacNum++;
ph.packLen = 512; // arbitrary length
accountNum = acc;
amount = val;
}
// .
public void sendTransaction() {
Console.WriteLine(" #: " + ph.packNum +
", : " + ph.packLen +
",\n #: " + accountNum +
", : {0:C}\n", amount);
}
// .
class PacketDemo {
public static void Main() {
Transaction t = new Transaction("31243", -100.12);
Transaction t2 = new Transaction("AB4655", 345.25);
Transaction t3 = new Transaction("8475-09", 9800.00);
t.sendTransaction();
t2.sendTransaction();
t3.sendTransaction();
.
#: 0, : 512,
#: 31243, : ($100.12)
#: 1, : 512,
#: 4655, : $345.25
#: 2, : 512,
#: 8475-09, : $9,800.00
PacketHeader ,
, .
PacketHeader
, . ,
PacketHeader
.
344
I. C#
, C++
struct. C#- C++- .
C++ struct , struct class
( :
, ). C# struct
, a class .
(enumeration) .
enum . :
enum {_};
.
_ ,
.
.
apple, .
enum apple { Jonathan, GoldenDel, RedDel, Winsap,
Cortland, McIntosh };
,
, ( )
. ,
, Jonathan 0, GoldenDel 1
..
,
. enum
,
.
.
. ,
Console.WriteLine(apple.RedDel + " " +
(int)apple.RedDel);
.
RedDel 2
,
.
int. (
C#,
, .)
,
apple.
// .
using System;
class EnumDemo {
12. ,
345
// .
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 - -
, for- apple.
,
, .
, color
( ). :
. ,
.
.
. ,
switch- (
).
346
I. C#
.
. , , ,
. ,
10 RedDel.
enum apple { Jonathan, GoldenDel, RedDel = 10, Winsap,
Cortland, McIntosh };
:
Jonathan
0
GoldenDel
l
RedDel
10
Winsap
11
Cortland
12
McIntosh
13
int,
, char.
, int,
. , apple
byte.
enura apple : byte { Jonathan, GoldenDel, RedDel, Winsap,
Cortland, McIntosh };
apple.Winsap, , byte-.
, ,
, C#-.
. ,
. , ,
.
conveyor(), : ,
, . conveyor() (1
, 2 ..), ,
, . :
// .
using System;
class ConveyorControl {
// , .
public enum action { , , , };
public void conveyor(action com) {
switch(com) {
case action.:
Console.WriteLine(" .");
12. ,
347
break;
case action.:
Console.WriteLine(" .");
break;
case action.:
Console.WriteLine(" .");
break;
case action.:
Console.WriteLine(" .");
break;
class ConveyorDemo {
public static void Main() {
ConveyorControl c = new ConveyorControl();
c.conveyor(ConveyorControl.action.);
c.conveyor(ConveyorControl.action.);
c.conveyor(ConveyorControl.action.);
c.conveyor(ConveyorControl.action.);
}
:
.
.
.
.
conveyor() action,
, action. , ,
conveyor() 22.
c.conveyor(22); // !
,
int action .
conveyor() . , ,
,
. ,
, , ,
conveyor() .
.
switch-.
, ,
switch.
348
I. C#
13
( ) ,
C#-
, . C#
, C++ Java.
C++- Java-.
C# .
, .
,
,
. , ,
. ,
, ,
.
. ,
.
C#
,
.
,
.
C#-
C# .
System.Exception
C# .
Exception,
System. ,
Exception.
Exception
SystemException
ApplicationException. ,
C#: , C#- ,
(Common Language Runtime CLR), ,
. SystemException,
ApplicationException
Exception.
.
C# ,
SystemException. ,
DivideByZeroException. ,
,
ApplicationException.
C#-
: try, catch, throw finally. ,
350
I. C#
.
.
, .
, .
, ,
try-. ,
.
catch-
. C#-
. ,
throw. , try-,
finally.
try- catch-
try catch.
; try catch catch try.
try/catch- :
try {
// , .
}
catch(ExcepType1 exOb) {
// ExcepType1.
}
catch(ExcepType2 exOb) {
// ExcepType2.
}...
.
catch,
. try/catch-, try-
, catch-. ,
. , catch-,
(
). exOb
.
exOb .
( ), exOb
. exOb .
. , try-
, catch- .
,
catch. , catch- ( try-)
, .
, ,
. ,
. C#-
IndexOutOfRangeException,
, C#.
, .
13.
351
// .
using System;
class ExcDemo1 {
public static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine(
" .");
// ,
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[ {0}] : {1}", i, nums[i]);
}
Console.WriteLine(" .");
catch(IndexOutOfRangeException) {
// Console.WriteLine(" !");
}
Console.WriteLine(" catch-.");
:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
!
catch-.
, nums int-
. for 0 9,
,
IndexOutOfRangeException.
,
. -, try. -, ( -
for- nums ) try , catch-.
, catch-, ,
try- . , catch
, .
Console.WriteLine(" catch-."};
. catch-
. ,
, ,
.
352
I. C#
, catch .
, ,
.
,
, . ,
catch- , ,
.
, try- ,
catch- , ,
catch-. ,
for-
for(int i=0; i < 10; i++) {
:
for(int i=0; i < nums.Length; i++) {
for nums.
, catch- .
, try-,
. ,
, try. , ,
try-, 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(" .");
class ExcDemo2 {
public static void Main() {
try {
ExcTest.genException();
}
catch(IndexOutOfRangeException) {
13.
353
// .
Console.WriteLine(" !");
Console.WriteLine(" catch-.");
,
:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
!
catch-.
genException() try, ,
( ), catch
Main(). genException() ,
Main().
C#-,
, : .
.
, C#-
. ,
. , ,
, .
//
// C#- .
using System;
class NotHandled {
public static void Main() {
int[] nums = new int[4];
Console.WriteLine(" .");
// ,
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console. WriteLine("nums[{0} ] : {1}", i, nums[i]);
}
,
:
354
I. C#
catch-
DivideByZeroException ( C#-).
, ,
IndexOutOfRangeException,
catch-. .
// !
using System;
class ExcTypeMismatch {
public static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine(" .");
// ,
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");
/* catch-
DivideByZeroException,
. */
catch(DivideByZeroException) {
// .
Console.WriteLine(" !");
}
Console.WriteLine(" catch-.");
:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
13.
355
,
. ,
, ,
. ,
DivideByZeroException.
, . ,
,
.
.
// -// !
using System;
class ExcDemo3 {
public 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(" !");
:
4/2 2
!
16/4 4
32/4 8
!
128 / 8 16
.
. ,
356
I. C#
try-,
.
.
catch-
try- , catch-.
. catch-
. ,
, .
// catch-.
using System;
class ExcDemo4 {
public 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
!
128 / 8 16
.
.
, catch-
.
catch- ,
. ,
. catch- .
13.
357
, .
catch- .
, ,
.
,
IndexOutOfRangeException DivideByZeroException.
// catch-
// " ".
using System;
class ExcDemo5 {
public static void Main() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
:
4/2 2
.
16/4 4
32/4 8
.
128 / 8 16
.
.
catch-, ,
:
catch-.
try-
try- . ,
try- catch-,
try-, try-. ,
IndexOutOfRangeException try, .
358
I. C#
// try-.
using System;
class NestTrys {
public static void Main() {
// numer denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
try {
// try-.
for(int i=0; i < numer.Length; i++) {
try {
// try-.
Console.WriteLine(numer[i] + " / " +
denom[i] + " " + numer[i]/denom[i]);
}
catch(DivideByZeroException) {
// .
Console.WriteLine(" !");
}
}
}
catch(IndexOutOfRangeException) {
// .
Console.WriteLine(" .");
Console.WriteLine(
" .");
}
}
}
:
4/2 2
!
16/4 4
32/4 8
!
128 / 8 16
.
.
, try- (
), .
try-
.
.
try-
.
.
,
. try-
, try- .
try-
, .
13.
359
,
C#. ,
throw. :
throw exceptOb;
exceptOb ,
Exception.
, throw
DivideByZeroException .
// .
using System;
class ThrowDemo {
public static void Main() {
try {
Console.WriteLine(" .");
throw new DivideByZeroException();
}
catch(DivideByZeroException) {
// .
Console.WriteLine(" .");
}
Console.WriteLine(" try/catch-.");
}
}
:
.
.
try/catch-.
,
DivideByZeroException, : new throw.
, throw ,
. DivideByZeroException
,
.
,
. ,
,
.
, catch-, ,
() catch-.
. ,
, ,
. ,
360
I. C#
throw, . ,
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 };
class RethrowDemo {
public static void Main() {
try {
Rethrow.genException();
}
catch(IndexOutOfRangeException) {
//
// .
Console.WriteLine(" " +
" .");
}
}
}
( ), ..
genException(),
. IndexOutOfRangeException
Main().
13.
361
finally
,
try/catch-. ,
, , ,
.
, .
, C# :
finally.
, try/catch, try/catch- finally.
try/catch-, finally,
.
try {
// , .
}
catch(ExcepType1 exOb) {
// ExcepType1,
}
catch(ExcepType2 exOb) {
// ExcepType2.
}
.
.
.
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;
//
// .
362
I. C#
break;
case 2:
return; // try-.
}
}
catch(DivideByZeroException) {
// .
Console.WriteLine(" !");
return; // catch-.
}
catch(IndexOutOfRangeException) {
// .
Console.WriteLine(" .");
}
finally {
Console.WriteLine(" try-.");
}
}
}
class FinallyDemo {
public static void Main() {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
Console.WriteLine();
}
}
}
:
0
!
try-.
1
.
try-.
2
try-.
,
try-, finally .
,
. , catch-
. .
Exception,
, .
Exception
catch-.
Exception . : Message,
StackTrace TargetSite. .
13.
363
Message , , StackTrace
, .
TargetSite , , .
Exception .
ToString(), . ToString()
, , ,
WriteLine(). Exception
.
// Exception.
using System;
class ExcTest {
public static void genException() {
int[] nums = new int[4];
Console.WriteLine(" .");
// ,
// .
for(int i=0; i < 10; i++) {
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
Console.WriteLine(" .");
}
}
class UseExcept {
public static void Main() {
try {
ExcTest.genException();
}
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(" catch-.");
:
.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
364
I. C#
:
System.IndexOutOfRangeException: Index was outside
the bounds of the array.
at ExcTest.genException()
at UseExcept.Main()
StackTrace:
at ExcTest.genException()
at UseExcept.Main()
Message: Index was outside the bounds of the array.
TargetSite: Void genException()
catch-.
Exception .
:
Exception()
Exception(string str)
.
Message, .
.
System
. SystemException,
(Common Language Runtime)
. ,
C#, . 13.1.
13.1. ,
System
ArrayTypeMismatchException
DivideByZeroException
IndexOutOfRangeException
InvalidCastException
OutOfMemoryException
OverflowException
NullReferenceException
StackOverflowException
new -
, ..
,
, . 13.1,
, NullReferenceException.
, ,
, .
.
null-, null.
, , , .
,
NullReferenceException.
13.
365
// NullReferenceException.
using System;
class X {
int x;
public X(int a) {
x = a;
}
// NullReferenceException.
class NREDemo {
public static void Main() {
X p = new X(10);
X q = null; // q
// null.
int val;
try {
val = p.add(q); //
// .
}
catch(NullReferenceException) {
Console.WriteLine("NullReferenceException!");
Console.WriteLine(" ...\n");
// .
q = new X(9);
val = p.add(q);
}
Console.WriteLine(" val {0}", val);
:
NullReferenceException!
...
val 19
X, x add(),
x, ,
x, , .
Main() x. , p, , , q,
( null). p.meth(),
q . q
, q.x
NullReferenceException.
StackOverflowException,
.
. ,
,
366
I. C#
, ,
.
. , ,
, .
C#-
, C#-
. C# ,
.
. .
Exception. ,
,
ApplicationException, ,
, .
,
.
, ,
, Exception . ,
.
, .
10 RangeArray.
, RangeArray int-,
. , ,
-5 27,
RangeArray. 10 , ,
, RangeArray. ,
,
RangeArray. ,
. , RangeArray
.
RangeArray.
//
//
// RangeArray.
using System;
// RangeArray.
class RangeArrayException : ApplicationException {
// .
public RangeArrayException() : base() { }
public RangeArrayException(string str) : base(str) { }
// ToString()
// RangeArrayException.
public override string ToString() {
return Message;
}
13.
367
// RangeArray.
class RangeArray {
// .
int[] a; // .
int lowerBound; // .
int upperBound; // .
int len; // Length.
// .
public RangeArray(int low, int high) {
high++;
if(high <= low) {
throw new RangeArrayException(
" .");
}
a = new int[high - low];
len = high - low;
lowerBound = low;
upperBound = --high;
}
// Length, .
public int Length {
get { return len;
}
}
// RangeArray.
public int this[int index] {
// .
get {
if(ok(index)) {
return a[index - lowerBound];
} else {
throw new RangeArrayException(
" .");
}
}
// .
set {
if(ok(index)) {
a[index - lowerBound] = value;
}
else throw new RangeArrayException(
" .");
}
}
// true,
// .
private bool ok(int index) {
if(index >= lowerBound & index <= upperBound)
return true;
return false;
}
}
368
I. C#
//
// .
class RangeArrayDemo {
public 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] + " ");
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] + " ");
13.
369
}
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.
ApplicationException. , ,
, ApplicationException.
,
RangeArray-. ,
RangeArray try, .
RangeArray
C#-
.
, .
, ToString()
. ,
, , C#.
, ,
catch-, catch catch-
. ,
Exception, Exception
. , , catch .
, .
, ,
catch- .
catch-
. ,
catch- catch , . C#
catch- .
ExceptA
ExceptB. ExceptA ApplicationException,
ExceptB ExceptA. .
370
I. C#
//
//
// .
using System;
// .
class ExceptA : ApplicationException {
public ExceptA() : base() { }
public ExceptA(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
//
// ExceptA.
class ExceptB : ExceptA {
public ExceptB() : base() { }
public ExceptB(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
class OrderMatters {
public static void Main() {
for(int x = 0; x < 3; x++) {
try {
if(x==0) throw new ExceptA(
" ExceptA.");
else if(x==1) throw new ExceptB(
" ExceptB.");
else throw new Exception();
}
catch(ExceptB exc) { // .
Console.WriteLine(exc);
}
catch(ExceptA exc) { // .
Console.WriteLine(exc);
}
catch(Exception exc) {
Console.WriteLine(exc);
}
}
}
}
:
ExceptA.
ExceptB.
System.Exception: Exception of type System.Exception was thrown.
at OrderMatters.Main()
catch-.
. ExceptB ExceptA, catch ExceptB ,
13.
371
checked
unchecked
C# ,
, . ,
,
, .
, . , ,
:
byte a, b, result;
a = 127;
b = 127;
result = (byte)(a * b);
a b
byte. ,
result.
C#
checked unchecked. ,
,
checked. ,
unchecked. ,
- .
checked .
checked-. .
checked(expr)
checked {
// , .
}
expr , .
OverflowException.
unchecked . ,
.
, .
unchecked(expr)
372
I. C#
unchecked {
// , .
}
expr , .
.
, checked,
unchecked.
// checked unchecked.
using System;
class CheckedDemo {
public static void Main() {
byte a, b;
byte result;
a = 127;
b = 127;
try {
result = unchecked((byte) (a * b) );
Console.WriteLine("Unchecked-: " + result);
result = checked((byte)(a * b));
//
// .
Console.WriteLine("Checked-: " +
result);
//
// .
}
catch(OverflowException exc) {
// .
Console.WriteLine(exc);
}
:
Unchecked-: 1
System.OverflowException: Arithmetic operation resulted in an
overflow.
at CheckedDemo.Main()
, .
.
checked unchecked .
, .
// checked unchecked
// .
using System;
class CheckedBlocks {
public static void Main() {
byte a, b;
byte result;
13.
373
a = 127;
b = 127;
try {
unchecked {
a = 127;
b = 127;
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked-: " + result);
a = 125;
b = 5;
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked-: " + result);
}
checked {
a = 2;
b = 7;
result = checked((byte)(a * b)); // .
Console.WriteLine("Checked-: " + result);
a = 127;
b = 127;
result = checked((byte)(a * b)); //
//
// .
Console.WriteLine("Checked-: " +
result);
//
// .
}
catch(OverflowException exc) {
// .
Console.WriteLine(exc);
}
:
Unchecked-: 1
Unchecked-: 113
Checked-: 14
System.OverflowException: Arithmetic operation resulted in an
overflow. at CheckedBlocks.Main()
, unchecked-
. checked-
.
checked
unchecked , checked/unchecked-
. ,
.
374
I. C#
14
-
C#- -
Console.WriteLine(), .
C#- - ,
, , .
C#- -. C#
- , .NET Framework,
- .NET-.
, . , C#- -
, .
C#- -
C#- - .
(stream) , , .
C#- -.
, ,
. , -
. , ,
, .
C#- - .
, -
. .
, C# char 16- , a byte 8-.
ASCII, char byte
: char-.
Unicode-, .
, (
) -. C# ,
, byte-char- charbyte- .
,
Console.In, Console.Out Console.Error, ,
System. Console.Out
. . ,
Console.WriteLine() Console.Out.
Console.In ,
. Console.Error
, .
-.
. ,
.
376
I. C#
C# , .
,
,
. ,
, , .
System.IO.
,
:
using System.IO;
System.IO,
Console System.
Stream
C#- System.IO.Stream.
Stream
. , .. .
Stream .
, Stream, . 14.1.
14.1. Stream
void Close()
void Flush()
int ReadByte()
.
-1
numBytes buf,
buf[offset],
int Read(
byte[] buf,
int offset,
int numBytes)
long Seek (long offset,
SeekOrigin origin)
void WriteByte (byte b)
void Write(byte[] buf,
int offset,
int numBytes)
numBytes
buf, buf[offset]
- ,
. 14.1, IOException.
, , ,
, NotSupportedException.
, Stream ,
. ,
,
. ,
Seek(). ,
Stream. . 14.2.
Length Position,
, .
14. -
377
14.2. , Stream
bool CanRead
true, .
true,
.
true, .
.
.
,
bool CanSeek
bool CanWrite
long Length
long Position
Stream .
BufferedStream
.
, -
,
FileStream
MemoryStream
.
.
,
C#-.
TextReader TextWriter. TextReader
, TextWriter .
, ,
. , -,
.
. 14.3 ,
TextReader.
IOException. ( .)
ReadLine(),
, string-.
, .
14.3. , TextReader
void Close()
int Peek()
, .
-1,
.
-1
int Read()
378
I. C#
. 14.3
numChars buf,
buf[offset],
numChars buf,
buf[offset],
string-.
null-
, ,
string-
string ReadToEnd()
void
void
void
void
int
double
bool
string
uint
Write(int val)
Write(double val)
Write(bool val)
WriteLine(string val)
StreamReader
StreamWriter
SstringReader
StringWriter
14. -
379
, C#
, .
, BinaryReader BinaryWriter,
-.
, C#- -,
, , ,
-.
-
-
Console.In, Console.Out Console.Error. -
, 2, .
, .
, , C#-
, , ,
,
. , C#- -,
- , .
,
.
Console.In TextReader,
, TextReader.
, Console,
Console.In. Console
: Read() ReadLine().
Read() .
static int Read()
Read() , . ,
- , .
int,
char. Read() 1,
IOException.
( ), ,
,
<Enter>.
,
Read().
// .
using System;
class KbIn {
public static void Main() {
char ch;
380
I. C#
Console.Write(
" , -- <ENTER>: ");
ch = (char) Console.Read();
//
// char-.
Console.WriteLine(" : " + ch);
:
, <ENTER>:
:
, Read() ,
. <Enter>
, .
, , .
,
( ).
, ReadLine().
static string ReadLine()
ReadLine() ,
<Enter>, string.
IOException.
,
Console.In ReadLine().
// ReadLine().
using System;
class ReadString {
public static void Main() {
string str;
Console.WriteLine(" .");
str = Console.ReadLine();
Console.WriteLine(" : " + str);
.
.
.
: .
Console
Console.In,
TextReader. ,
, TextReader.
//
// Console.In.
using System;
class ReadChars2 {
public static void Main() {
string str;
14. -
381
Console.WriteLine(" .");
str = Console.In.ReadLine();
Console.WriteLine(" : " + str);
, ReadLine()
Console.In. , ,
TextReader,
Console.In, , .
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 {
public static void Main() {
int a = 10, b = 0;
int result;
Console.Out.WriteLine(
" .");
try {
result = a / b; // .
}
catch(DivideByZeroException exc) {
Console.Error.WriteLine(exc.Message);
}
:
.
Attempted to divide by zero.
, ,
Console.Error. Console.Out, Console.Error
, ?
: . ,
Console.Error ,
. , , ,
(log file), . ,
, ,
382
I. C#
, .
, -.
FileStream -
C# ,
. ,
.
. , C# ,
. ,
. C#
. , ,
. .
- .
,
FileStream. FileStream Stream
. , ,
FileStream, System.IO. ,
:
using System.IO;
, ,
FileStream. FileStream .
:
FileStream(string filename, FileMode mode)
filename , ,
. mode ,
, . mode
, FileMode ( . 14.4).
.
14.4. FileMode
FileMode.Append
FileMode.Create
.
.
, ,
,
FileMode.CreateNew
FileMode.Open
FileMode.OpenOrCreate
FileMode.Truncate
14. -
383
, .
,
FileNotFoundException. - -,
IOException.
: ArgumentNullException ( null-),
ArgumentException ( mode), SecurityException (
) DirectoryNotFoundException (
).
test.dat .
FileStream fin;
try {
fin = new FileStream("test.dat", FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
}
catch {
Console.WriteLine(" .");
return;
}
catch- ,
. , , ,
. ,
, .
FileNotFoundException IOException, (
) , ,
.
, FileStream
.
, :
FileStream(string filename, FileMode mode,
FileAccess how)
, filename , a mode
. , how,
. ,
FileAccess, :
FileAccess.Read
FileAccess.Write FileAccess.ReadWrite
, test.dat
:
FileStream fin = new FileStream("test.dat", FileMode.Open,
FileAccess.Read);
.
Close(). :
void Close()
,
, . Close()
IOException.
384
I. C#
FileStream
FileStream , :
ReadByte() Read(). ,
ReadByte(), :
int ReadByte()
,
.
-1. NotSupportedException
( ) ObjectDisposedException ( ).
, Read(),
:
int Read(byte[] buf, int offset, int numBytes)
Read() numBytes buf,
buf[offset]. .
- IOException.
NotSupportedException,
.
ReadByte()
.
. try/catch-, ,
:
.
.
/* .
,
, .
, TEST.CS,
:
ShowFile TEST.CS */
using System;
using System.IO;
class ShowFile {
public static void Main(string[] args) {
int i;
FileStream fin;
try {
fin = new FileStream(args[0], FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
}
catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message +
"\n: ShowFile ");
return;
}
14. -
385
// , EOF.
do {
try {
i = fin.ReadByte();
}
catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1) Console.Write((char) i);
} while(i != -1);
fin.Close();
, WriteByte().
:
void WriteByte(byte val)
, val.
IOException.
,
NotSupportedException.
Write() .
:
void Write(byte[] buf, int offset, int numBytes)
Write() numBytes buf,
buf[offset].
IOException.
, NotSupportedException.
.
, ,
,
,
, .
. ,
, 128 .
, , ,
, .
,
, Flush():
void Flush()
IOException.
,
Close(). , , ,
.
Flush().
.
386
I. C#
// .
using System;
using System.IO;
class WriteToFile {
public static void Main(string[] args) {
FileStream fout;
// .
try {
fout = new FileStream("test.txt", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(
exc.Message +
"\n .");
return;
}
// .
try {
for(char c = 'A'; c <= 'Z'; c++)
fout.WriteByte((byte) c);
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" . ");
}
fout.Close();
test.txt.
, .
, try/catch.
test.txt :
ABCDEFGHIJKLMNOPQRSTUVWXYZ
FileStream
- FileStream
, ,
. , ,
.
.
/*
.
.
, FIRST.DAT
SECOND.DAT,
:
CopyFile FIRST.DAT SECOND.DAT */
14. -
387
using System;
using System.IO;
class CopyFile {
public static void Main(string[] args) {
int i;
FileStream fin;
FileStream fout;
try {
// .
try {
fin = new FileStream(args[0], FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"\n .");
return;
}
// .
try {
fout = new FileStream(args[1], FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(
exc.Message +
"\n .");
return;
}
}
catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message +
"\n: CopyFile ");
return;
}
// .
try {
do {
i = fin.ReadByte();
if(i != -1) fout.WriteByte((byte)i);
} while(i != -1);
}
388
catch(IOException exc) {
Console.WriteLine(exc.Message +
" . ");
}
fin.Close();
fout.Close();
I. C#
,
C# .
Unicode- ( ). ,
Unicode-, .
, ,
FileStream StreamReader StreamWriter.
.
,
. StreamReader StreamWriter
.
StreamWriter TextWriter, a StreamReader
TextReader. , StreamWriter
StreamReader ,
.
StreamWriter
,
Stream (, FileStream) StreamWriter.
StreamWriter .
:
StreamWriter(Stream stream)
stream .
ArgumentException, stream ,
ArgumentNullException, () null-.
StreamWriter
.
-, ,
, test.txt. ,
. FileStream,
StreamWriter .
/* "-",
StreamWriter. */
using System;
using System.IO;
class KtoD {
public static void Main() {
string str;
FileStream fout;
try {
fout = new FileStream("test.txt", FileMode.Create);
}
catch(IOException exc) {
14. -
389
Console.WriteLine(exc.Message +
" . ");
return;
}
StreamWriter fstr_out = new StreamWriter(fout);
Console.WriteLine(
" ('' ).");
do {
Console.Write(": ");
str = Console.ReadLine();
if(str != "") {
str = str + "\r\n"; //
// .
try {
fstr_out.Write(str);
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
return;
}
}
} while(str != "");
fstr_out.Close();
StreamWriter.
:
StreamWriter(string filename)
StreamWriter(string filename, bool appendFlag)
filename ,
. appendFlag
bool: appendFlag true,
. .
, , , IOException (
).
-,
StreamWriter.
// StreamWriter.
using System;
using System.IO;
class KtoD {
public static void Main() {
string str;
StreamWriter fstr_out;
// ,
// StreamWriter.
try {
fstr_out = new StreamWriter("test.txt");
390
I. C#
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
return;
}
Console.WriteLine(
" ('' ).");
do {
Console.Write(": ");
str = Console.ReadLine();
if(str != "") {
str = str + "\r\n"; //
// .
try {
fstr_out.Write(str);
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" . ");
return;
}
}
} while(str != "");
fstr_out.Close();
StreamReader
,
- StreamReader. StreamReader
. :
StreamReader(Stream stream)
stream .
ArgumentNullException, stream null-,
ArgumentException, stream .
StreamReader .
-,
test.txt .
, ,
.
/* "-",
FileReader. */
using System;
using System.IO;
class DtoS {
public static void Main() {
FileStream fin;
14. -
391
string s;
try {
fin = new FileStream("test.txt", FileMode.Open);
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
" .");
return;
}
StreamReader fstr_in = new StreamReader(fin);
// .
while((s = fstr_in.ReadLine()) != null) {
Console.WriteLine(s);
}
fstr_in.Close();
, . ,
ReadLine(), null, , .
StreamWriter, ,
StreamReader. :
StreamReader(string filename)
filename ,
. .
FileNotFoundException. filename
null, ArgumentNullException,
, ArgumentException.
, , Console.In,
. , - .
/
. , ,
.
,
.
. -,
< >,
Console.In / Console.Out, .
, , :
using System;
class Test {
392
I. C#
Test > log
. log.
.
, ,
. .
< > C#,
. ,
- ( Windows),
, .
,
. SetIn(), SetOut()
SetError(), Console:
static void SetIn(TextReader input)
static void SetOut(TextWriter output)
static void SetError(TextWriter output)
, , SetIn(),
.
, TextReader.
, FileStream-,
StreamWriter-.
:
// Console.Out.
using System;
using System.IO;
class Redirect {
public static void Main() {
StreamWriter log_out;
try {
log_out = new StreamWriter("logfile.txt");
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
return;
}
//
// .
Console.SetOut(log_out);
Console.WriteLine(" .");
for(int i=0; i<10; i++)
Console.WriteLine(i);
Console.WriteLine(" .");
log_out.Close();
14. -
393
,
logfile.txt :
.
0
1
2
3
4
5
6
7
8
9
.
,
-.
, . ,
, int-, double- short-.
C#- BinaryReader
BinaryWriter. ,
, ,
.
BinaryWriter
BinaryWriter ,
.
:
BinaryWriter(Stream outputStream)
outputStream ,
. ,
, FileStream. outputStream null, ArgumentNullException,
outputStream , ArgumentException.
BinaryWriter ,
C#- ( . 14.5). :
string ,
. BinaryWriter
Close() Flush(), .
14.5. , BinaryWriter
394
byte- ( )
byte- ( )
I. C#
. 14.5
byte-
short (
)
ushort - (
)
int
uint- ( )
long (
)
ulong- (
)
float-
double-
string-
,
Write(float val)
Write(double val)
Write(char val)
Write(char[] buf)
Write(string val)
BinaryReader
BinaryReader ,
.
:
BinaryReader(Stream, inputStream)
inputStream , .
, ,
FileStream, inputStream null-,
ArgumentNullException, inputStream
, ArgumentException.
BinaryReader C#. . 14.6. ,
ReadString() ,
, .
EndOfStreamException,
IOException. BinaryReader
Read():
int Read()
.
-1
num buf,
buf[offset],
int Read(
byte[] buf,
int offset,
int num)
int Read(
char[] buf,
int offset,
int num)
num buf,
buf[offset],
IOException.
14. -
395
BinaryReader Close().
14.6. , BinaryReader
bool ReadBoolean()
byte ReadByte()
sbyte ReadSByte()
byte[] ReadBytes(
int num)
char ReadChar()
char[] ReadChars(
int num)
double ReadDouble()
float ReadSingle()
short ReadInt16()
int ReadInt32()
long ReadInt64()
ushort ReadUInt16()
uint ReadUInt32()
ulong ReadUInt64()
string ReadString()
bool-
byte-
sbyte-
num
char-
num
double-
float-
short-
int-
long-
ushort-
uint-
ulong-
string-,
, .
,
BinaryWriter
BinaryReader BinaryWriter. ,
.
//
// .
using System;
using System.IO;
class RWData {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
int i = 10;
double d = 1023.56;
bool b = true;
try {
dataOut = new
BinaryWriter(new FileStream("testdata",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\n .");
396
I. C#
return;
}
try {
Console.WriteLine(" "
dataOut.Write(i);
Console.WriteLine(" "
dataOut.Write(d);
Console.WriteLine(" "
dataOut.Write(b);
Console.WriteLine(" "
dataOut.Write(12.2 * 7.4);
}
+ i);
+ d);
+ b);
+ 12.2 * 7.4);
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\n .");
}
dataOut.Close();
Console.WriteLine();
// .
try {
dataIn = new
BinaryReader(new FileStream("testdata",
FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"\n .");
return;
}
try {
i = dataIn.ReadInt32();
Console.WriteLine("
d = dataIn.ReadDouble();
Console.WriteLine("
b = dataIn.ReadBoolean();
Console.WriteLine("
d = dataIn.ReadDouble();
Console.WriteLine("
}
" + i);
" + d);
" + b);
" + d);
catch(IOException exc) {
Console.WriteLine(exc.Message +
" .");
}
dataIn.Close();
14. -
397
:
10
1023,56
True
90,28
10
1023,56
True
90,28
testdata,
, , ,
.
, C#-
-.
.
, .
,
. , .
/* BinaryReader BinaryWriter
. */
using System;
using System.IO;
class Inventory {
public static void Main() {
BinaryWriter dataOut;
BinaryReader dataIn;
string item; // .
int onhand; // , .
double cost; // .
try {
dataOut = new
BinaryWriter(new FileStream("inventory.dat",
FileMode.Create));
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\n .");
return;
}
//
// .
try {
dataOut.Write("");
dataOut.Write(10);
dataOut.Write(3.95);
dataOut.Write("");
dataOut.Write(18);
dataOut.Write(1.50);
398
I. C#
dataOut.Write("");
dataOut.Write(5);
dataOut.Write(4.95);
dataOut.Write("");
dataOut.Write(8);
dataOut.Write(8.95);
}
catch(IOException exc) {
Console.WriteLine(exc.Message +
"\n .");
}
dataOut.Close();
Console.WriteLine();
//
// .
try {
dataIn = new
BinaryReader(new FileStream("inventory.dat",
FileMode.Open));
}
catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message +
"\n .");
return;
}
// , .
Console.Write(" : ");
string what = Console.ReadLine();
Console.WriteLine();
try {
for(;;) {
// .
item = dataIn.ReadString();
onhand = dataIn.ReadInt32();
cost = dataIn.ReadDouble();
/*
, . */
if(item.CompareTo(what) == 0) {
Console.WriteLine(item + ": " + onhand +
" . " +
": {0:C} .",
cost);
Console.WriteLine(
" <{0}>: {1:}.",
item, cost * onhand);
break;
}
}
}
catch(EndOfStreamException) {
Console.WriteLine(" .");
14. -
399
catch(IOException exc) {
Console.WriteLine(exc.Message + " .");
}
dataIn.Close();
:
:
; 18 . : $1.50 .
<>: $27.00.
,
, .
, , ,
, ,
. ,
.
,
.
EndOfStreamException,
, ,
. ,
.
, .. ,
, . C#
, .
Seek(), FileStream.
( ) .
Seek() :
long Seek(long newPos, SeekOrigin origin)
newPos , ,
, origin. origin
, SeekOrigin.
SeekOrigin.Begin
SeekOrigin.Current
SeekOrigin.End
Seek()
.
- , IOException.
,
NotSupportedException.
400
I. C#
, -
.
, .
// .
using System;
using System.IO;
class RandomAccessDemo {
public static void Main() {
FileStream f;
char ch;
try {
f = new FileStream("random.dat", FileMode.Create);
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return;
}
// .
for(int i=0; i < 26; i++) {
try {
f.WriteByte( (byte) ('A'+i) );
}
catch(IOException exc) {
Console.WriteLine(exc.Message);
return;
}
try {
// .
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 + " ");
}
}
14. -
401
catch(IOException exc) {
Console.WriteLine(exc.Message);
}
Console.WriteLine(); f.Close();
:
:
A C E G I K M O Q S U W Y
MemoryStream
-
.
. MemoryStream.
MemoryStream Stream, . :
MemoryStream(byte[] buf)
buf ,
- / . ,
, .
Seek().
buf,
.
,
MemoryStream:
// MemoryStream.
using System;
using System.IO;
class MemStrDemo {
public static void Main() {
byte[] storage = new byte[255];
// .
MemoryStream memstrm = new MemoryStream(storage);
// memstrm StreamWriter
// StreamReader.
StreamWriter memwtr = new StreamWriter(memstrm);
StreamReader memrdr = new StreamReader(memstrm);
//
// memwtr.
for(int i=0; i < 10; i++)
402
I. C#
// memstrm,
// .
memstrm.Seek(0, SeekOrigin.Begin); //
// .
string str = memrdr.ReadLine();
while(str != null) {
str = memrdr.ReadLine();
if(str.CompareTo(".") == 0) break;
Console.WriteLine(str);
}
storage:
byte[0]: 0
byte[1]: 1
byte[2]: 2
byte[3]: 3
byte[4]: 4
byte[5]: 5
byte[6]: 6
byte[7]: 7
byte[8]: 8
byte[9]: 9
memrdr:
byte[1]: 1
byte[2]: 2
byte[3]: 3
byte[4]: 4
byte[5]: 5
byte[6]: 6
byte[7]: 7
byte[8]: 8
byte[9]: 9
14. -
403
storage.
memstrm
MemoryStream. memstrm StreamReader
memrdr StreamWriter memwtr. memwtr
, .
, memwtr
flush(). , ,
memwtr, .
, .. foreach.
Seek() ,
memrdr.
, , .
,
, .
GUI-, Windows.
. , ,
.
StringReader
StringWriter
-,
,
(byte-) , (string-).
StringReader StringWriter. StringReader
TextReader, StringWriter TextWriter.
, , .
, ReadLine() StringReader
WriteLine() StringWriter.
StringReader :
StringReader(string str)
str ,
.
StringWriter .
:
StringWriter()
,
. StringWriter.
, ToString().
StringReader StringWriter.
// StringReader
// StringWriter.
using System;
using System.IO;
class StrRdrDemo {
public static void Main() {
// StringWriter.
404
I. C#
// StringReader-.
string str = strrdr.ReadLine();
while(str != null) {
str = strrdr.ReadLine();
Console.WriteLine(str);
}
:
i : 1
i : 2
i : 3
i : 4
i : 5
i : 6
i : 7
i : 8
i : 9
StringWriter strwtr
WriteLine().
StringReader , strwtr,
ToString(). ,
ReadLine().
-, ,
. , C#-
WriteLine() (
, int double) .
, WriteLine()
. C# ,
.. ,
. ,
, , 100,
,
int-. ,
, Parse().
14. -
405
, .
C#- (, int double)
(.. ) , .NET Framework.
Microsoft , C#- .NET- .
. 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.
,
C#- .
,
.
. ,
.
Decimal
Double
Single
Int64
Int32
Int16
UInt64
UInt32
UInt16
Byte
SByte
static
static
static
static
static
static
static
static
static
static
static
Parse() FormatException,
str , . str
null-, ArgumentNullException, a
406
I. C#
str ,
, OverflowException.
,
,
. ,
, .
,
ReadLine() Int32.Parse()
. , Double. Parse()
double-.
// ,
// .
using System;
using System.IO;
class AvgNums {
public 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);
n = 0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
n = 0;
}
Console.WriteLine(" " + n + " .");
for(int i=0; i < n; i++) {
Console.Write(": ");
str = Console.ReadLine();
try {
t = Double.Parse(str);
}
catch(FormatException exc) {
Console.WriteLine(exc.Message);
t = 0.0;
}
catch(OverflowException exc) {
Console.WriteLine(exc.Message);
t = 0;
}
sum += t;
}
avg = sum / n;
Console.WriteLine(" " + avg);
}
}
14. -
407
: 5
5 .
: 1.1
: 2.2
: 3.3
: 4.4
: 5.5
3.3
. ,
. ,
Int32.Parse() , ,
.
408
I. C#
15
C#-: .
,
, .
, .
, C#.
(delegate). ,
. , , ,
. ,
. , ,
.
,
, ,
. ,
. , .
, ,
, .
. ,
.
C/C++, , C#
C/C++
,
, ,
. , , ,
, .
.
delegate.
:
delegate _ (_);
_ ,
, . .
, , ,
_.
, (.. )
.
, ,
, ,
, :
// .
using System;
// .
delegate string strMod(string str);
class DelegateTest {
410
I. C#
Console.WriteLine(" .");
for(i=0; i < a.Length; i++)
if(a[i] != ' ') temp += a[i];
return temp;
// .
static string reverse(string a) {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i=a.Length-1; i >= 0; i--, j++)
temp += a[i];
return temp;
}
public 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();
:
.
: --.
.
: .
.
: .
15.
411
, strMod,
string string-. DelegateTest
, ,
. .
, replaceSpaces()
Replace() string.
Main() strMod strOp,
replaceSpaces().
:
strMod strOp = new strMod(replaceSpaces);
, replaceSpaces()
. ( ).
: ,
. ,
.
.
replaceSpaces()
strOp, :
str = strOp(" .");
strOp replaceSpaces(),
replaceSpaces(). strOp
removeSpaces(), strOp .
removeSpaces().
, strop reverse(),
strOp . , ,
reverse().
, strOp
, strOp . ,
,
.
,
.
. , ,
StringOps:
//
// .
using System;
// .
delegate string strMod(string str);
class StringOps {
// .
public string replaceSpaces(string a) {
Console.WriteLine(" .");
return a.Replace(' ', '-');
}
// .
public string removeSpaces(string a) {
string temp = "";
int i;
412
I. C#
Console.WriteLine(" .");
for(i=0; i < a.Length; i++)
if(a[i] != ' ') temp += a[i];
return temp;
// .
public string reverse(string a) {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i=a.Length-1; i >= 0; i--, j++)
temp += a[i];
return temp;
}
class DelegateTest {
public static void Main() {
StringOps so = new StringOps();
//
// StringOps.
// .
strMod strOp = new strMod(so.replaceSpaces);
string str;
// .
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
strOp = new strMod(so.removeSpaces);
str = strOp(" .");
Console.WriteLine(" : " + str);
Console.WriteLine();
, StringOps.
(multicasting). ,
( ) ,
. .
,
+=. -=.
(
+, - =, "+=" "-=".)
15.
413
:
void.
.
, string ,
, void,
ref-.
// .
using System;
// .
delegate void strMod(ref string str);
class StringOps {
// .
static void replaceSpaces(ref string a) {
Console.WriteLine(" .");
a = a.Replace(' ', '-');
}
// .
static void removeSpaces(ref string a) {
string temp = "";
int i;
Console.WriteLine(" .");
for(i=0; i < a.Length; i++)
if(a[i] != ' ') temp += a[i];
a = temp;
}
// .
static void reverse(ref string a) {
string temp = "";
int i, j;
Console.WriteLine(" .");
for(j=0, i=a.Length-1; i >= 0; i--, j++)
temp += a[i];
a = temp;
}
public static void Main() {
// .
strMod strOp;
strMod replaceSp = new strMod(replaceSpaces);
strMod removeSp = new strMod(removeSpaces);
strMod reverseStr = new strMod(reverse);
string str = " .";
// ,
strOp = replaceSp;
strOp += reverseStr;
// .
strOp(ref str);
414
I. C#
//
// .
// .
strOp(ref str);
:
.
.
: .--
.
.
: .
Main() . , strOp,
null-. .
, removeSpaces()
reverse(). :
strOp = replaceSp;
strOp += reverseStr;
strOp replaceSp. ,
+=, reverseStr.
strOp ,
.
strOp -= replaceSp;
replaceSp,
strOp += removeSp;
removeSp.
strOp .
, .
, , ,
, .
, .
System.Delegate
,
System.Delegate. ,
System.Delegate.
.
15.
415
, ""
, ?. ,
. -,
, . , ,
. ,
, . ,
( Windows Paint).
,
. ,
.
.
C#: (event).
- .
. ,
, .
, . :
.
,
event. :
event _ ;
_ ,
,
.
.
// .
using System;
// .
delegate void MyEventHandler();
// .
class MyEvent {
public event MyEventHandler SomeEvent;
// .
public void OnSomeEvent() {
if(SomeEvent != null) SomeEvent();
}
class EventDemo {
// .
static void handler() {
416
I. C#
Console.WriteLine(" .");
// handler() .
evt.SomeEvent += new MyEventHandler(handler);
// .
evt.OnSomeEvent();
:
.
, ,
. .
:
delegate void MyEventHandler();
. ,
. ,
.
, void.
MyEvent. ,
, SomeEvent:
public event MyEventHandler SomeEvent;
. .
, MyEvent OnSomeEvent(),
, . ( ,
, .) ,
SomeEvent.
if(SomeEvent != null)
SomeEvent();
, ,
SomeEvent null-. ,
, , ,
OnSomeEvent() .
null-,
, null-.
EventDemo handler().
, ,
.
, Main() MyEvent, handler()
.
MyEvent evt = new MyEvent();
// handler() .
evt.SomeEvent += new MyEventHandler(handler);
,
+=. ,
+= -=. handler() ,
15.
417
. ,
,
.
// . 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.");
}
}
class Y {
public void Yhandler() {
Console.WriteLine(", Y.");
}
}
class EventDemo {
static void handler() {
Console.WriteLine(
", EventDemo.");
}
public static
MyEvent evt
X xOb = new
Y yOb = new
418
void Main() {
= new MyEvent();
X();
Y();
I. C#
// .
evt.SomeEvent += new MyEventHandler(handler);
evt.SomeEvent += new MyEventHandler(xOb.Xhandler);
evt.SomeEvent += new MyEventHandler(yOb.Yhandler);
// . evt.OnSomeEvent();
Console.WriteLine();
// .
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
:
, EventDemo.
, X.
, Y.
, EventDemo.
, Y.
X Y,
MyEventHandler. ,
. , X y
. ,
, ,
.
.
,
,
,
. ,
( ).
,
. , ,
, .
, , , .
.
X,
. ,
X .
X.
/*
. */
using System;
15.
419
// .
delegate void MyEventHandler();
// .
class MyEvent {
public event MyEventHandler SomeEvent;
// .
public void OnSomeEvent() {
if(SomeEvent != null) SomeEvent();
}
}
class X {
int id;
public X(int x) { id = x; }
// ,
// .
public void Xhandler() {
Console.WriteLine(" " + id);
}
class EventDemo {
public static void Main() {
MyEvent evt = new MyEvent();
X o1 = new X(1);
X o2 = new X(2);
X o3 = new X(3);
:
1
2
3
,
.
, ,
, .
/*
. */
using System;
// .
420
I. C#
// .
public void OnSomeEvent() {
if(SomeEvent != null) SomeEvent();
}
class X {
/* ,
. */
class EventDemo {
public static void Main() {
MyEvent evt = new MyEvent();
evt.SomeEvent += new MyEventHandler(X.Xhandler);
// .
evt.OnSomeEvent();
:
.
, X.
handler() X,
SomeEvent OnSomeEvent().
, . ,
, ,
, ,
. ,
.
, , .
, , ,
.
,
event-, .
.
:
event _ _ {
add {
15.
421
// .
}
remove {
// .
}
}
: add remove.
add , +=
, remove ,
-= .
add remove ,
, . ,
, value.
add remove .
, , .
.
. ,
.
// .
using System;
// .
delegate void MyEventHandler();
//
// .
class MyEvent {
MyEventHandler[] evnt = new MyEventHandler[3];
public event MyEventHandler SomeEvent {
// .
add {
int i;
for(i=0; i < 3; i++)
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;
}
422
I. C#
if(i == 3)
Console.WriteLine(" .");
// .
public void OnSomeEvent() {
for(int i=0; i < 3; i++)
if(evnt[i] != null) evnt[i]();
}
}
// ,
// MyEventHandler.
class W {
public void Whandler() {
Console.WriteLine(" W.");
}
}
class X {
public void Xhandler() {
Console.WriteLine(" X.");
}
}
class Y {
public void Yhandler() {
Console.WriteLine(" Y.");
}
}
class Z {
public void Zhandler() {
Console.WriteLine(" Z.");
}
}
class EventDemo {
public 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 += new MyEventHandler(wOb.Whandler);
evt.SomeEvent += new MyEventHandler(xOb.Xhandler);
evt.SomeEvent += new MyEventHandler(yOb.Yhandler);
// .
evt.SomeEvent += new MyEventHandler(zOb.Zhandler);
Console.WriteLine();
// .
15.
423
evt.OnSomeEvent();
Console.WriteLine();
// .
Console.WriteLine(" xOb.Xhandler.");
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
Console.WriteLine();
// .
Console.WriteLine(
" xOb.Xhandler.");
evt.SomeEvent -= new MyEventHandler(xOb.Xhandler);
evt.OnSomeEvent();
Console.WriteLine();
// Zhandler.
Console.WriteLine(" zOb.Zhandler.");
evt. SomeEvent += new MyEventHandler(zOb. Zhandler);
evt.OnSomeEvent();
:
.
.
W.
X.
Y.
xOb.Xhandler.
W.
Y.
xOb.Xhandler.
.
W.
Y.
zOb.Zhandler.
W.
Z.
Y.
.
MyEventHandler. MyEvent,
,
evnt.
MyEventHandler[] evnt = new MyEventHandler[3];
,
. evnt null-
.
event-,
.
424
I. C#
add-,
( value)
evnt. ,
. evnt
, .
remove-, evnt
, value. ,
null,
.
OnSomeEvent().
evnt, .
,
.
,
.
event-, ,
. ,
, ,
.
.
. .
. ,
15.
425
add remove, .
sealed.
, .. .
.NET Framework
C# .
.NET Framework
, Microsoft .
,
. , .
EventArgs ,
. , .NET-
:
void handler(object source, EventArgs arg) {
// ...
}
source .
EventArgs ,
.
EventArgs ,
; ,
, .
, EventArgs
Empty, , .
, .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;
// SomeEvent-.
public void OnSomeEvent() {
MyEventArgs arg = new MyEventArgs();
if(SomeEvent != null) {
426
I. C#
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 EventDemo {
public static void Main() {
X ob1 = new X();
Y ob2 = new Y();
MyEvent evt = new MyEvent();
// handler() .
evt.SomeEvent += new MyEventHandler(ob1.handler);
evt.SomeEvent += new MyEventHandler(ob2.handler);
// . evt.OnSomeEvent();
evt.OnSomeEvent();
:
0 X.
MyEvent.
0 Y.
MyEvent.
1 X.
MyEvent.
1 Y.
MyEvent.
MyEventArgs EventArgs.
MyEventArgs eventnum.
15.
427
EventHandler
EventArgs .
.NET Framework
, EventHandler.
, .
EventHandler.
// EventHandler.
using System;
// .
class MyEvent {
public event EventHandler SomeEvent; //
// EventHandler.
//
// SomeEvent-.
public void OnSomeEvent() {
if(SomeEvent != null)
SomeEvent(this, EventArgs.Empty);
}
class EventDemo {
static void handler(object source, EventArgs arg) {
Console.WriteLine(" .");
Console.WriteLine(" " +
source + ".");
// .
evt.OnSomeEvent();
EventArgs
- EventArgs.Empty.
:
.
MyEvent.
428
I. C#
:
,
Windows. ,
, .
C#,
. ,
, .
.
Windows-,
, ,
. .
KeyPress,
OnKeyPress().
// ,
// .
using System;
// EventArgs,
// .
class KeyEventArgs : EventArgs {
public char ch;
}
// .
delegate void KeyHandler(object source, KeyEventArgs arg);
// ,
// .
class KeyEvent {
public event KeyHandler KeyPress;
//
// - .
public void OnKeyPress(char key) {
KeyEventArgs k = new KeyEventArgs();
if(KeyPress != null) {
k.ch = key;
KeyPress(this, k);
}
}
}
// , .
class ProcessKey {
public void keyhandler(object source, KeyEventArgs arg) {
Console.WriteLine(
" : " + arg.ch);
}
}
15.
429
// ,
// .
class CountKeys {
public int count = 0;
public void keyhandler(object source, KeyEventArgs arg) {
count++;
}
}
// KeyEvent.
class KeyEventDemo {
public static void Main() {
KeyEvent kevt = new KeyEvent();
ProcessKey pk = new ProcessKey();
CountKeys ck = new CountKeys();
char ch;
kevt.KeyPress += new KeyHandler(pk.keyhandler);
kevt.KeyPress += new KeyHandler(ck.keyhandler);
Console.WriteLine(" . " +
" .");
do {
ch = (char) Console.Read();
kevt.OnKeyPress(ch);
} while(ch != '.');
Console.WriteLine(" " +
ck.count + " .");
:
. .
.
:
:
:
:
: .
5 .
KeyEventArgs,
.
KeyHandler ,
. KeyEvent.
: ProcessKey
CountKeys. ProcessKey keyhandler(),
. CountKeys
. Main()
KeyEvent. ProcessKey CountKeys, a
keyhandler() ,
kevt.KeyPress. ,
kevt.OnKeyPress(),
.
430
I. C#
16
,
C#-,
. ,
.
2,
C#: C# -
. , C#
. , ,
, .
. .
,
. , , ,
, . .NET
Framework ( C#-) System.
:
using System;
14, -
, System, System.IO.
, System, C#.
,
, , ,
, ,
.
,
. , Finder,
, Finder
, . ,
, ,
, .
namespace.
:
namespace {
//
}
. ,
, . ,
.
, , , ,
.
432
I. C#
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;
}
}
CountDown ,
Counter.
,
Counter.
// .
using System;
// .
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) { val = n; }
public void reset(int n) {
val = n;
}
class NSDemo {
public static void Main() {
Counter.CountDown cd1 = new Counter.CountDown(10);
int i;
do {
16. ,
433
i = cd1.count();
Console.Write(i + "
} while(i > 0);
Console.WriteLine();
Counter.CountDown cd2
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();
");
= new Counter.CountDown(20);
");
");
:
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
. -,
CountDown Counter,
CountDown, ,
Counter.
Counter.CountDown cd1 = new Counter.CountDown(10);
Counter , (
) ( -) . ,
cd1.count() ,
:
i = cd1.count();
, ,
, ,
. , CountDown,
Counter2.
// ,
// .
using System;
// .
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
434
I. C#
}
public void reset(int n) {
val = n;
}
public int count() {
if(val > 0) return val--;
else return 0;
}
}
}
// .
namespace Counter2 {
/* CountDown
Counter2
, Counter. */
class CountDown {
public void count() {
Console.WriteLine(" count() " +
" Counter2.");
}
}
class NSDemo {
public static void Main() {
// CountDown
// Counter.
Counter.CountDown 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();
:
10 9 8 7 6 5 4 3 2 1 0
count() Counter2.
, CountDown
Counter CountDown,
Counter2, .
, ,
, ,
.
16. ,
435
using
2,
,
, .
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;
}
class NSDemo {
public static void Main() {
// CountDown
// .
CountDown cd1 = new CountDown(10);
436
I. C#
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();
:
.
,
. , System
Counter.
using
using :
using = ;
,
. ,
, Count
Counter.CountDown.
// .
using System;
// Counter.CountDown.
using Count = Counter.CountDown;
// .
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
}
public void reset(int n) {
16. ,
437
val = n;
}
public int count() {
if(val > 0) return val--;
else return 0;
}
class NSDemo {
public static void Main() {
// Count
// Counter.CountDown.
Count cd1 = new Count(10);
int i;
do {
i = cd1.count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
Count cd2 = new Count(20);
do {
i = cd2.count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
cd2.reset(4);
do {
i = cd2.count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
Count
Counter.CountDown,
CountDown . ,
Count cd1 = new Count(10);
CountDown.
.
. ,
Counter. CountDown, CountUp.
Counter .
// .
using System;
438
I. C#
// "" Counter.
using Counter;
//
// Counter.
namespace Counter {
// .
class CountDown {
int val;
public CountDown(int n) {
val = n;
}
public void reset(int n) {
val = n;
}
public int count() {
if(val > 0) return val--;
else return 0;
}
}
}
//
// Counter.
namespace Counter {
// .
class CountUp {
int val;
int target;
public int Target {
get{
return target;
}
}
public CountUp(int n) {
target = n;
val = 0;
}
public void reset(int n) {
target = n;
val = 0;
}
class NSDemo {
public static void Main() {
16. ,
439
:
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8
.
using Counter;
. CountDown
CountUp , .
, Counter ,
.
.
:
// .
using System;
namespace NS1 {
class ClassA {
public ClassA() {
Console.WriteLine(" ClassA.");
}
namespace NS2 { // .
class ClassB {
public ClassB() {
Console. WriteLine(" ClassB.");
}
class NestedNSDemo {
public static void Main() {
NS1.ClassA a = new NS1.ClassA();
// NS2.ClassB b = new NS2.ClassB(); // !!!
440
I. C#
// NS2 .
NS1.NS2.ClassB b = new NS1.NS2.ClassB();
}
//
// .
:
ClassA.
ClassB.
NS2 NS1.
, ClassB ,
: NS1, NS2. NS2 .
, ,
,
. ,
namespace OuterNS {
namespace InnerNS {
// ...
}
}
:
namespace OuterNS.InnerNS {
// ....
}
,
, .
, .
( , ) (
),
.
.
,
,
.
C# ,
.
, , .
C++, C#
, C++.
,
,
, (preprocessor).
,
.
16. ,
441
C# :
#define
#endregion
#region
#elif
#error
#undef
#else
#if
#warning
#endif
#line
#, ,
.
, C# ,
, .
,
. .
#define
#define ,
. #if #elif
,
. #define :
#define
, .
#define
, . ,
EXPERIMENTAL, :
#define EXPERIMENTAL
C/C++ #define
, ,
, .
#define C# . C# #define
.
#if #endif
#if #endif
,
, .
, . .
, #define,
.
#if :
#if _
_
#endif
, #if(_),
,
,
#endif(_), .
. #endif #if-.
442
I. C#
.
: !, ==, !=, && ||.
.
#if, #endif #define.
// #if, #endif
// #define.
#define EXPERIMENTAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#endif
Console.WriteLine(
" .");
:
.
.
#define
EXPERIMENTAL. #if
EXPERIMENTAL , ( )
WriteLine()-. experimental
, WriteLine()- ,
#if .
WriteLine()- ,
#if-. , #if
. :
// .
#define EXPERIMENTAL
#define TRIAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#endif
#if EXPERIMENTAL && TRIAL
Console.Error.WriteLine(
" .");
#endif
16. ,
443
Console.WriteLine(
" .");
:
.
.
.
, EXPERIMENTAL TRIAL.
WriteLine()- ,
.
#else #elif
#else else- C#, ..
, #if .
.
// #else.
#define EXPERIMENTAL
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#else
Console.WriteLine(" -.");
#endif
#if EXPERIMENTAL && TRIAL
Console.Error.WriteLine(
" .");
#else
Console.Error.WriteLine(
" .");
#endif
Console.WriteLine(
" .");
:
.
.
.
TRIAL , #else-
.
, #else
#if-, #else-, #if
#endif.
444
I. C#
#elif if-else-if-
. #elif .
, (_)
, #elif- ,
#elif-. #elif-
:
#if _
_
#elif _
_
#elif _
_
#elif _
_
#elif _
.
.
.
#endif
:
// #elif.
#define RELEASE
using System;
class Test {
public static void Main() {
#if EXPERIMENTAL
Console.WriteLine(
" .");
#elif RELEASE
Console.WriteLine(" -.");
#else
Console.WriteLine(
" .");
#endif
#if TRIAL && !RELEASE
Console.WriteLine(" .");
#endif
Console.WriteLine(
" .");
}
}
:
-.
.
#undef
#undef ,
. #undef :
#undef
16. ,
445
:
#define SMALL
#if SMALL
// ...
#undef SMALL
// SMALL .
#undef SMALL
.
#undef ,
.
#error
#error .
.
#error :
#error __
#error __
. ,
#error !
,
!.
#warning
#warning #error, ,
. .
#warning :
#warning _
#line
#line ,
#line.
.
#line :
#line "_"
,
, _ -
, . #line
.
,
default: #line default
446
I. C#
#region #endregion
#region #endregion ,
(IDE) Visual Studio. :
#region _
// _
#endregion
, _ .
internal
C#-
(assembly), .
.NET-.
Microsoft, .NET
Framework.
, .
.
.
(manifest). .
, , ,
.
, , .
,
.
, Microsoft Intermediate Language (MSIL).
, , .
, C#
, ( )
. , ,
C#-, ,
. , C# .
.
( .NET-, C#.)
C# :
internal. - .
internal
public, private protected,
, C# internal.
, ,
, . , ,
internal, , - .
internal .
16. ,
447
internal ,
. internal
.
internal
protected. protected internal,
. ,
protected internal,
. .
internal.
// internal.
using System;
class InternalTest {
internal int x;
}
class InternalDemo {
public static void Main() {
InternalTest ob = new InternalTest();
ob.x = 10; // : x .
InternalTest x
internal. , ,
InternalDemo, .
448
I. C#
17
C#:
, .
,
. ,
. ,
, .
, ,
. C#-.
, , .
.
,
.
(runtime type identification RTTI)
,
. , ,
. RTTI
, ,
,
.
( ).
C# ,
: is, as typeof.
.
is
is ,
. :
is
.
( ) ,
. .
, , ,
.
is.
// is.
using System;
class A {}
class B : A {}
class UseIs {
public static void Main() {
A a = new A();
B b = new B();
450
I. C#
b
b
--
.
, .
B.
.
,
. :
if(b is )
Console.WriteLine(" b , " +
" .");
if- , b
, . , b
. .
if(a is B)
Console.WriteLine(" , " +
" B.");
if- , ,
B. , a B .
as
, , .
as, :
as
,
, .
.
.
as is.
, , , is
:
// is
// .
using System;
class A {}
class : A {}
17. ,
451
class CheckCast {
public static void Main() {
A a = new A();
b = new ();
// , .
if(a is )
//
// .
b = () a;
else
//
// .
b = null;
if(b==null)
Console.WriteLine(
" b = () .");
else
Console.WriteLine(
" b = () .");
:
b = () .
, B,
,
if. ,
. ,
. as .
, .
// as.
using System;
class A {}
class B : A {}
class CheckCast {
public static void Main() {
A a = new A();
B b = new B();
b = a as B; // ,
// .
if(b==null)
Console.WriteLine(" " +
"b - (B) .");
else
Console.WriteLine(
" b - (B) .");
}
}
:
b = () .
452
I. C#
as ,
, , , .
typeof
as is, (
-) .
. C#
typeof.
System.Type . ,
.
typeof :
typeof()
, .
, typeof,
, .
Type-, ,
, , .
, ,
. ,
, ,
: FullName, IsClass IsAbstract. FullName
. IsClass true,
. IsAbstract true,
.
// typeof.
using System;
using System.IO;
class UseTypeof {
public static void Main() {
Type t = typeof(StreamReader);
Console.WriteLine(t.FullName);
if(t.IsClass) Console.WriteLine(" .");
if(t.IsAbstract) Console.WriteLine(
" ");
else Console.WriteLine(" .");
:
System.IO.StreamReader
.
.
StreamReader.
, ,
.
17. ,
453
, (reflection) C#,
.
: , , ,
.
, () ,
. ,
,
, .
, ,
.NET Reflection API,
System.Reflection. , ,
, :
using System.Reflection;
: System.T
System.Type ,
. ,
.
System.Reflection.MemberInf.
MemberInfo ,
:
DeclanngType
MemberTypes MemberType
string Name
Type ReflectedType
, MemberType MemberTypes.
MemberTypes , ,
. :
MemberTypes.Constructor
MemberTypes.Method
MemberTypes.Field
MemberTypes.Event
MemberTypes.Property
, , MemberType.
, MemberType MemberTypes.Method,
, .
MemberInfo : GetCustomAttributes()
IsDefined(). .
, MemberInfo,
. ,
.
454
I. C#
ConstructorInfo[] GetConstructors()
EventInfo[] GetEvents()
FieldInfo[] GetFields()
MemberInfo[] GetMembers()
MethodInfo[] GetMethods()
PropertyInfo[] GetProperties()
,
.
Assembly Assembly
TypeAttributes Attributes
Type BaseType
string FullName
bool IsAbstract
bool IsArray
bool IsClass
bool IsEnum
string Namespace
,
,
,
,
,
. , ,
, ,
. , ,
.
Reflection API ,
. ( Reflection API
!) Reflection API , , ,
, .
:
, ,
.
Type- ,
. GetMethods().
:
MethodInfo[] GetMethods()
17. ,
455
GetMethods() MethodInfo,
, . MethodInf
System.Reflection.
MethodInfo MethodBase, ,
, MemberInfo. ,
, . ,
, Name.
MethodInfo: ReturnType GetParameters().
ReturnType, , ,
.
GetParameters() , .
:
ParameterInfo[] GetParameters()
ParameterInfo.
ParameterInfo ,
. : Name,
, ,
ParameterType, .
.
,
, MyClass.
, ,
.
// .
using System;
using System.Reflection;
class MyClass {
int x;
int y;
public MyClass(int i, int j) {
x = i;
y = j;
}
public int sum() {
return x+y;
}
public bool isBetween(int i) {
if(x < i && i < y) return true;
else return false;
}
public void set(int a, int b) {
x = a;
y = b;
}
public void set(double a, double b) {
x = (int) a;
y = (int) b;
456
I. C#
class ReflectDemo {
public 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 GetHashCode()
Boolean Equals(Object obj)
String ToString()
Int32 sum()
Boolean isBetween(Int32 i)
Void set(Int32 a, Int32 b)
17. ,
457
}
GetParameters() pi.
for pi .
,
, .. MyClass.
GetMethods()
GetMethods() ,
. :
MethodInfo[] GetMethods(BindingFlags flags)
, .
BindingFlags .
:
458
I. C#
DeclaredOnly
, .
e-public-
public-
static-
Instance
Nonpublic
Public
static
.
Public Nonpublic Instance
Static. GetMethods() .
BindingFlags-,
GetMethods(), ,
. ,
, . , ,
GetMethods() :
// ,
// MyClass.
MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Public);
:
, MyClass
:
Int32 sum()
Boolean isBetween(Int32 i)
Void set(Int32 a, Int32 b)
Void set(Double a, Double b)
Void show()
, ,
MyClass.
, , .
Invoke(), MethodInfo.
:
object Invoke(object ob, object[] args)
ob , .
static- ob null. ,
, args.
, args null-.
args , .
, , args
, , , .
17. ,
459
Invoke()
MethodInfo, GetMethods().
:
// .
using System;
using System.Reflection;
class MyClass {
int x; int y;
public MyClass(int i, int j) {
x = i;
y = j;
}
public int sum() {
return x + y;
}
public bool isBetween(int i) {
if((x < i) && (i < y)) return true;
else return false;
}
public void set(int a, int b) {
Console.Write(" set(int, int). ");
x = a;
y = b;
show();
}
// set.
public void set(double a, double b) {
Console.Write(" set(double, double). ");
x = (int) a;
y = (int) b;
show();
}
class InvokeMethDemo {
public static void Main() {
Type t = typeof(MyClass);
MyClass reflectOb = new MyClass(10, 20);
int val;
Console.WriteLine(" , " +
t.Name);
Console.WriteLine();
MethodInfo[] mi = t.GetMethods();
460
I. C#
// .
foreach(MethodInfo m in mi) {
// .
ParameterInfo[] pi = m.GetParameters();
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);
}
else if(m.Name.CompareTo("sum")==0) {
val = (int) m.Invoke(reflectOb, null);
Console.WriteLine(
" sum " + val);
}
else if(m.Name.CompareTo("isBetween")==0) {
object[] args = new object[1];
args[0] = 14;
if((bool) m.Invoke(reflectOb, args))
Console.WriteLine("14 x y.");
}
else if(m.Name.CompareTo("show")==0) {
m.Invoke(reflectOb, null);
}
}
:
, MyClass
sum 30
14 x y.
set(int, int). x: 9, y: 18
set(double, double). x: 1, y: 23
x: 1, y: 23
, .
. freach .
, 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);
}
17. ,
461
,
( MyClass),
MyClass . ,
.
, .
. ,
.
, .
, GetConstructors()
. :
ConstructorInfo[] GetConstructors()
ConstructorInfo,
.
ConstructorInf MethodBase,
MemberInfo. ConstructorInfo
. GetParameters(),
, .
GetParameters(), MethodInf.
, ,
Invoke(), ConstructorInfo.
Invoke() :
object Invoke(object[] args)
, ,
args. , args
null-. args
. Invoke() .
MyClass:
// .
using System;
using System.Reflection;
462
I. C#
class MyClass {
int x;
int y;
public MyClass(int i) {
Console.WriteLine(
" MyClass(int). ");
x = y = i;
}
public MyClass(int i, int j) {
Console.WriteLine(
" MyClass(int, int). ");
x = i;
y = 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;
y = b;
show();
}
// set().
public void set(double a, double b) {
Console.Write(" set(double, double). ");
x = (int) a;
y = (int) b;
show();
}
class InvokeConsDemo {
public static void Main() {
Type t = typeof(MyClass);
int val;
// .
ConstructorInfo[] ci = t.GetConstructors();
Console.WriteLine(" : ");
17. ,
463
foreach(ConstructorInfo c in ci) {
// .
Console.Write(" " + t.Name + "{");
// .
ParameterInfo[] pi = c.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();
// .
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.WriteLine(
"\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] = 13;
m.Invoke(reflectOb, args);
}
464
I. C#
:
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)
.
MyClass(int, int).
x: 10, y: 20
reflectOb.
sum() 30
14 x y.
set(int, int). x: 9, y: 18
set(double, double). x: 1, y: 23
x: 1, y: 23
,
MyClass.
:
ConstructorInfo[] ci = t.GetConstructors();
, .
,
, :
for(x=0; x < ci.Length; x++) {
ParameterInfo[] pi = ci(x).GetParameters();
if(pi.Length == 2) break;
}
( ), ,
:
17. ,
465
// .
object[] consargs = new object[2];
consargs[0) = 10;
consargs[1] = 20;
object reflectOb = ci[x].Invoke(consargs);
Invoke() reflectOb
MyClass.
, ,
int-, ,
MyClass. .
MyClass, : MyClass.
MyClass,
, MyClass,
typeof ,
( ).
,
,
.
16, ,
., . Reflection API
,
. ,
,
.
. , , ,
. ,
,
, , .
,
.
Assembly. Assembly public. Assembly , .
, LoadFrom(). :
static Assembly LoadFrom(string _)
_ .
Assembly,
GetTypes(). :
[] GetTypes()
, .
, . .
MyClasses.cs :
// .
// MyClasses.cs.
466
I. C#
using
class
int
int
System;
MyClass {
x;
y;
public MyClass(int i) {
Console.WriteLine(
" MyClass(int). ");
x = y = i;
show();
}
public MyClass(int i, int j) {
Console.WriteLine(
" MyClassdnt, int). ");
x = i;
y = 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;
y = b;
show();
}
// set.
public void set(double a, double b) {
Console.Write(" set(double, double). ");
x = (int) a;
y = (int) b;
show();
}
class AnotherClass {
string remark;
public AnotherClass(string str) {
remark = str;
}
17. ,
467
class Demo {
public static void Main() {
Console.WriteLine(" .");
}
}
MyClass,
. , AnotherClass Demo.
, , ,
. , MyClasses.exe.
, .
,
MyClasses..
/* ,
, . */
using System;
using System.Reflection;
class ReflectAssemblyDemo {
public static void Main() {
int val;
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
// , MyClasses.exe.
Type[] 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 c in ci) {
// .
Console.Write(" " + t.Name + "(");
// .
ParameterInfo[] pi = c.GetParameters();
for(int i=0; i < pi.Length; i++) {
Console.Write(pi[i].ParameterType.Name +
468
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.WriteLine(
"\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) {
17. ,
469
}
else if(m.Name.CompareTo("isBetween")==0) {
object[] args = new object[1];
args[0] = 14;
}
else if(m.Name.CompareTo("show")==0) {
m.Invoke(reflectOb, null);
}
:
: MyClass
: AnotherClass
: Demo
: MyClass
:
MyClass(Int32 i)
MyClass(Int32 i, Int32 j)
.
MyClass(int, int).
x: 10, y: 20
reflectOb.
sum() 30
14 x y.
set(int, int). x: 9, y: 18
set(double, double). x: 1, y: 23
x: 1, y: 23
, ,
MyClasses.exe. ,
MyClass, .
MyClasses..
, MyClasses.exe,
,
Main():
// MyClasses.exe.
Assembly asm = Assembly.LoadFrom("MyClasses.");
// , MyClasses.exe.
[] alltypes = asm.GetTypes();
foreach(Type temp in alltypes)
Console.WriteLine(": " + temp.Name);
470
I. C#
,
.
, exe-,
(dynamic link library DLL), dll. ,
MyClasses.cs :
csc /t:library MyClasses.cs
MyClasses.dll. DLL-
Main(). exe- ,
Main(), . Demo Main().
DLL- . MyClass
DLL-, LoadFrom() :
Assembly asm = Assembly.LoadFrom("MyClasses.dll");
,
.
MyClass ,
MyClass. ,
(set() sum()).
, .
, ,
. , ,
, , .
, ,
, MyClasses.exe,
MyClass,
.
// MyClass
// .
using System;
using System.Reflection;
class ReflectAssemblyDemo {
public static void Main() {
int val;
Assembly asm = Assembly.LoadFrom("MyClasses.exe");
Type[] alltypes = asm.GetTypes();
Type t = alltypes[0];
//
// .
17. ,
471
472
I. C#
(pi[1].ParameterType == typeof(int))) {
object[] args = new object[2];
args[0] = 9;
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).
x: 10, y: 10
reflectOb.
sum
20
isBetween
14 x y.
set
set(int, int). x: 9, y: 18
set
set(double, double). x: 1, y: 23
show
x: 1, y: 23
. -, ( )
, MyClass.
BindingFlags-
GetMethods(). . , ,
, .
switch-. case-
() () .
.
17. ,
473
C#
. ,
, .. , , ,
.
, , . ,
. .
, 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;
}
.
RemarkAttribute.
AttributeUsage, , RemarkAttribute
. AttributeUsage
, ;
.
RemarkAttribute,
Attribute. RemarkAttribute pri_remark,
remark,
. , .
474
I. C#
RemarkAttribute ,
pri_remark. , ,
RemarkAttribute,
.
, .
, ,
. ,
RemarkAttribute :
[RemarkAttribute(" .")]
class UseAttrib {
//...
}
RemarkAttribute,
..
UseAttrib.
Attribute. ,
:
[Remark(" .")]
class UseAttrib {
// ...
}
Remark.
,
, .
,
. .
GetCustomAttributes(), MemberInfo
. , ,
:
object[] GetCustomAttributes(bool searchBases)
searchBases true,
.
, .
GetCustomAttribute(),
Attribute. :
static Attribute GetCustomAttribute(MemberInfo mi,
Type attribtype)
mi MemberInfo, ,
. attribtype.
, ,
. , RemarkAttribute,
:
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
17. ,
475
, . ,
, , , ,
. ,
remark:
Console.WriteLine(ra.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;
}
[RemarkAttribute(" .")]
class UseAttrib {
// ...
}
class AttribDemo {
public static void Main() {
Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": ");
object[] attribs = t.GetCustomAttributes(false);
foreach(object o in attribs) {
Console.WriteLine(o);
}
Console.Write("Remark: ");
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.remark);
:
UseAttrib: RemarkAttribute
Remark: .
476
I. C#
RemarkAttribute
. , ..
, comment,
RemarkAttribute(),
.
,
. C# .
, .
, ,
.
.
, .
, , :
[attrib(__,
__1 = value,
__2 = value, ...)]
( )
. .
.
.
.
, ,
. RemarkAttribute,
supplement, .
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // remark.
public string supplement; // .
public RemarkAttribute(string comment) {
pri_remark = comment;
supplement = " ";
}
, supplement
.
. , ,
supplement :
[RemarkAttribute(" .",
supplement = " .")]
class UseAttrib {
// ...
}
17. ,
477
,
RemarkAttribute. . , ,
supplement, .
. ,
.
. , ,
.
.
, supplement:
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // remark.
public string supplement; // .
public RemarkAttribute(string comment) {
pri_remark = comment;
supplement = " ";
}
[RemarkAttribute(" .",
supplement = " .")]
class UseAttrib {
// ...
}
class NamedParamDemo {
public static void Main() {
Type t = typeof(UseAttrib);
Console.Write(" " + t.Name + ": ");
object[] attribs = t.GetCustomAttributes(false);
foreach(object o in attribs) {
Console.WriteLine(o);
}
// RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write("Remark: ");
Console.WriteLine(ra.remark);
478
I. C#
Console.Write("Supplement: ");
Console.WriteLine(ra.supplement);
:
UseAttrib: RemarkAttribute
Remark: .
Supplement: .
,
. ,
RemarkAttribute int- priority.
//
// .
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class RemarkAttribute : Attribute {
string pri_remark; // remark.
int pri_priority; // priority.
public string supplement; // .
[RemarkAttribute(
" .",
supplement = " .",
priority = 10)]
class UseAttrib {
// ...
}
class NamedParamDemo {
17. ,
479
:
UseAttrib: RemarkAttribute
Remark: .
Supplement: .
Priority: 10
(
UseAttrib):
[RemarkAttribute(
" .",
supplement = " .",
priority = 10)]
supplement priority
. ,
.
C# : AttributeUsage, Conditional
Obsolete. .
AttributeUsage
, AttributeUsage ,
. AttributeUsage
System.AttributeUsageAttribute. AttributeUsage
:
AttributeUsage(AttributeTargets item)
480
I. C#
item ,
. AttributeTargets ,
:
All
Assembly
Class
Constructor
Delegate
Enum
Event
Field
Interface
Method
Module
Parameter
Property
ReturnValue
Struct
.
, , ,
AttributeTargets:
AttributeTargets.Field | AttributeTargets.Property
AttributeUsage .
AllowMultiple, bool,
, .
Inherited, bool.
, .
. AllowMultiple Inherited
false.
Conditional
Conditional, , C#-.
.
, #define.
. ,
#if.
Conditional System.Diagnostics.Conditional
-Attribute. Conditional,
System.Diagnostics.
, .
// Conditional.
#define TRIAL
using System;
using System.Diagnostics;
class Test {
[Conditional("TRIAL")]
void trial() {
Console.WriteLine(
" , .");
}
[Conditional("RELEASE")]
void release() {
Console.WriteLine(" .");
}
public static void Main() {
Test t = new Test();
17. ,
481
t.trial();
// ,
// TRIAL .
t.release();
// ,
// RELEASE .
:
, .
, ,
. ,
TRIAL, trial() release().
Conditional,
:
[Conditional "symbol"]
symbol , ,
. .
, .
.
Main() trial(), release().
TRIAL.
trial(). release() .
RELEASE, release().
TRIAL, trial() .
. void. , .
override.
Obsolete
Obsolete
System.ObsoleteAttribute. -
. :
[Obsolete("message")]
message ,
. .
// Obsolete.
using System;
class Test {
[Obsolete(" myMeth2.")]
static int myMeth(int a, int b) {
return a / b;
}
// myMeth().
static int myMeth2(int a, int b) {
return b == 0 ? 0 : a /b;
}
public static void Main() {
482
I. C#
// ,
// .
Console.WriteLine("4 / 3 is " + Test.myMeth(4, 3));
// .
Console.WriteLine("4 / 3 is " + Test.myMeth2(4, 3));
Main()
myMeth(), ,
myMeth() myMeth2().
Obsolete :
[Obsolete("message", error)]
error Boolean. true,
,
. ,
,
.
17. ,
483
18
,
.
. , ,
C# ,
C++, .. ,
. ,
C# , Java.
,
.
C# , (unsafe
code). , , ,
Common Language Runtime (CLR).
1, C# .
"" ,
, . "",
.
, , .
,
CLR.
, , ,
? ,
. C++, ,
, . ,
C#.
, ,
. ,
. , ,
, . C#
.
, (, )
, , C# ( )
.
, .
C# ,
C/C++ ( , C/C++,
C#). : C# .
C#-
. C#-
. , ,
/unsafe.
, ,
.
18. ,
485
, . ,
x y, x , y.
,
. ,
, .
- ( )
. - :
* _;
,
. , .
(*). .
_ -.
. ip int-,
:
int* ip;
float- :
float* fp;
(*)
.
, , .
, ip
int-, fp float-. :
, --.
- .
C# C/C++,
C# C/C++. C/C++ *
, .
C/C++
int* p, q;
p int- int- q.
:
int* p;
int q;
C# * ,
int* p, q;
p q int-. , C#
:
int* p;
int* q;
/C++-
C#.
486
I. C#
"*" "&"
: * &. & .
, , (:
.) ,
int* ip;
int num = 10;
ip = #
ip num.
, num.
num. ,
ip 10 ( num), ,
. &
, . ,
: ip num.
(*) (&).
, ,
, . , ,
. (
) ip num,
int val = *ip;
val 10,
num, ip. *
.
: val () ip.
*
. , .
,
*ip = 100;
100 , ip (
num). , :
ip 100.
unsafe
, ,
unsafe.
. , , Main()
, unsafe.
//
// unsafe.
using System;
class UnsafeCode {
// Main() "".
unsafe public static void Main() {
int count = 99;
18. ,
487
int* p; // int-.
p = &count; // count
// .
Console.WriteLine(
" count " + *p);
*p = 10; // 10 count
// .
Console.WriteLine(
" count " + *p);
:
count 99
count 10
fixed
fixed.
.
, , , - .
,
.
fixed :
fixed(type* p = &var) {
// . }
p , .
,
. fixed
. fixed
. , ,
.
fixed:
// fixed.
using System;
class Test {
public int num;
public Test(int i) {
num = i;
}
class FixedCode {
// Main() .
unsafe public static void Main() {
Test = new Test(19);
fixed(int* p = io.num) { //
// fixed,
// o.num .
488
I. C#
Console.WriteLine(
" o.num " + *p);
*p = 10;
// 10 count
// .
Console.WriteLine(
" o.num " + *p);
:
o.num 19
o.num 10
fixed . p
o.num, p
.
,
.
(->), (.). , ,
:
struct MyStruct {
public int x;
public int y;
, :
MyStruct = new MyStruct();
MyStruct* p; // .
p = &;
p->x = 10;
p->y = 20;
Console.WriteLine(" " + p->sum());
: ++, -, + -. ,
, . p1 int-
2 000 (.. p1 2 000).
p1++;
p1 2 004, 2 001! ,
p1 int-.
C# int- , p1
4.
, .. p1 4.
,
18. ,
489
p1--;
p 1 996, 2 000.
, , ,
, .
,
.
.
,
.
p1 = p1 + 9;
p1 p1
, p1 .
,
( , ).
, .
( ) () ,
,
. , float- double-.
,
, .
, int- (ip)
float- (fp). (
), .
//
// .
using System;
class PtrArithDemo {
unsafe public static void Main() {
int x;
int i;
double d;
int* ip = &i;
double* fp = &d;
Console.WriteLine("int double\n");
.
,
.
490
I. C#
int double
1243324 1243328
1243328 1243336
1243332 1243344
1243336 1243352
1243340 1243360
1243344 1243368
1243348 1243376
1243352 1243384
1243356 1243392
1243360 1243400
,
.
int- , double- ,
.
, ==, < >.
,
- . , p1 p2 ,
,
p1 p2 . p1 p2
, (, ,
), p1 p2
.
,
.
// .
using System;
class PtrCompDemo {
unsafe public static void Main() {
int[] nums = new int[11];
int x;
// .
fixed(int* start = &nums[0]) {
fixed(int* end = &nums[nums.Length-1]) {
for(x=0; start+x <= end-x; x++);
}
}
Console.WriteLine(
" " + x);
:
6
, start
, end .
, ,
start x,
18. ,
491
end x , start
x end x.
: start end fixed, ,
. , C#
.
C# . ,
. :
/*
. */
using System;
class PtrArray {
unsafe public static void Main() {
int[] nums = new int[10];
fixed(int* p = &nums[0], p2 = nums) {
if(p == p2)
Console.WriteLine(
" p p2 .");
}
}
}
:
p p2 .
,
&nums[0]
nums
,
, .
, , ,
.
, . ,
// .
using System;
class PtrIndexDemo {
unsafe public static void Main() {
int[] nums = new int[10];
// .
Console.WriteLine(
" .");
492
I. C#
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(
"\n .");
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));
}
:
.
p[0]: 0
p[1]: 1
p[2]: 2
p[3]: 3
p[4]; 4
p[5]: 5
p[6]: 6
p[7]: 7
p[3]: 8
p[9]: 9
.
*(p+0): 0
*(p+1): 1
*(p+2): 2
*(p+3): 3
*(p+4): 4
*(p+5): 5
*(p+6): 6
*(p+7): 7
*(p+8): 8
*(p+9): 9
, (
)
*(ptr + i)
,
:
ptr[i]
. -,
. ,
,
. -, Length.
.
18. ,
493
, C# ,
. char* , fixed-:
fixed(char* p = str) { // ...
fixed- p
, .
, .. .
. C/C++
, .
, char*- ,
, C/C++.
, char*:
// fixed-
// .
using System;
class Fixedstring {
:
.
, ,
. (multiple
indirection), .
. 18.1. ,
( ) ,
.
, ,
.
, , , ,
.
494
I. C#
, ,
.
(*) . ,
, q
int: int** q;
, q
, int-.
, ,
*, :
using System;
class Multiplelndirect {
unsafe public static void Main() {
int x; // .
int* p; //
// int-.
int** q; //
// int-.
x = 10;
p = &x; // x .
q = &p; // p q.
Console.WriteLine(**q); // x.
}
}
x, ..
10. p int-, q
int-.
:
, ,
. .
. 18.1.
, , . ,
, int-:
int*[] ptrs = new int*[3];
18. ,
495
int- var
, :
ptrs[2] = &var;
var, :
*ptrs[2]
I C# ,
.
sizeof
, ( ) C# -
. sizeof.
:
sizeof()
, .
sizeof (unsafe) . ,
,
( ) .
lock
lock . C#
.
. ,
, , ,
. :
,
? , ,
.
lock. :
lock(obj) {
// .
}
obj , .
, ,
.
. ( . 21.)
readonly
, ,
readonly, readonly-
, . ,
readonly- (,
), -
496
I. C#
. ,
.
readonly-:
// readonly-.
using System;
class MyClass {
public static readonly int SIZE = 10;
}
class DemoReadOnly {
public static void Main() {
int[]nums = new int[MyClass.SIZE];
for(int i=0; i<MyClass.SIZE; i++)
nums[i] = i;
foreach(int i in nums)
Console.Write(i + " ");
MyClass.SIZE 10.
, . ,
, , .
.
stackalloc
stackalloc .
.
:
*p - stackalloc []
p ,
, . stackalloc
(unsafe) .
,
. .
, , .
, .
.
stackalloc ,
.
stackalloc:
// stackalloc.
using System;
class UseStackAlloc {
unsafe public static void Main() {
int* ptrs = stackalloc int[3];
18. ,
497
ptrs[0] = 1;
ptrs[1] = 2;
ptrs[2] = 3;
1
2
3
using
using, ,
, using.
:
using(obj) {
// obj.
}
using(type obj = ) {
// obj.
}
obj , using.
using-, ,
obj Dispose() (
System.IDisposable). using ,
System.IDisposable.
using:
// using.
using System;
using System.IO;
class UsingDemo {
public static void Main() {
StreamReader sr = new StreamReader("test.txt");
// using.
using(sr) {
Console.WriteLine(sr.ReadLine() );
sr.Close();
}
498
// StreamReader- using.
using(StreamReader sr2 = new StreamReader("test.txt")) {
Console.WriteLine(sr2.ReadLine());
sr2.Close();
}
I. C#
StreamReader IDisposable (
TextReader). , using-.
( IDisposable . 24.)
const volatile
const ,
.
. , const- .
,
const int i = 10;
const- i, 10.
volatile ,
. ,
, ,
.
.
. , C#-
, ,
.
, (,
), ,
. volatile
, .
18. ,
499
II
C#
II C#.
I, C#
, , .NET
Framework. ,
C#,
.NET Framework. C#
. using
.
, ,
.. ,
( )
.
19
System
System,
C#. , ,
, C#-
.NET Framework. , System
C#.
System
, , System.Net.
.
System.
System
, System
:
Activator
Array
AttributeUsageAttribute
CharEnumerator
ContextBoundObject
DBNull
Environment
FlagsAttribute
LocalDataStoreSlot
MTAThreadAttribute
Object
ParamArrayAttribute
SerializableAttribute
ThreadStaticAttribute
UnhandledExceptionEventArgs
ValueType
AppDomain
AssemblyLoadEventArgs
BitConverter
CLSCompliantAttribute
ContextStaticAttribute
Delegate
EventArgs
GC
MarshalByRefObject
MulticastDelegate
ObsoleteAttribute
Random
STAThreadAttribute
TimeZone
Uri
Version
AppDomainSetup
Attribute
Buffer
Console
Convert
Enum
Exception
LoaderOptimizationAttribute
Math
NonSerializedAttribute
OperatingSystem
ResolveEventArgs
String
Type
OriBuilder
WeakReference
System
ArgIterator
Char
Double
Int32
RuntimeArgumentHandle
RuntimeTypeHandle
TimeSpan
UInt32
Void
Boolean
DateTime
Guid
Int64
RuntimeFieldHandle
SByte
TypedReference
UInt64
Byte
Decimal
Int16
IntPtr
RuntimeMethodHandle
Single
UInt16
UintPtr
System :
IAppDomainSetup
IComparable
IDisposable
IServiceProvider
IAsyncResult
IConvertible
IFormatProvider
19. System
ICloneable
ICustomFormatter
IFormattable
503
System :
AssemblyLoadEventHandler
EventHandler
AsyncCallback
ResolveEventHandler
CrossAppDomainDelegate
UnhandledExceptionEventHandler
System :
AttributeTargets
LoaderOptimization
UriHostNameType
DayOfWeek
PlatformID
UriPartial
Environment.SpecialFolder
TypeCode
, System
,
. , System
.NET Framework, C#- .
, System (, Type, Exception
Attribute) I .
System. String, C#- string,
, 20 (
).
System, C#-
.
Math
Math ,
, , . ,
Math, . 19.1. .
, , Math, static. Math, ,
Math.
Math :
public const double E
public const double PI
E , , a PI
.
Math sealed-, .. .
19.1. , Math
504
v
v
v
v
v
v
II. C#
. 19.1.
public static
double v)
public static
double v)
public static
double v)
public static
double y,
double x)
public static
double v)
double Acos(
public static
double v)
public static
double v)
public static
double v)
public static
double v)
double Atan(
v. v
-1 1
v. v
-1 1
v
double Atan2(
y/x
double Ceiling(
double Cos(
(
),
v. , v,
1.02, Ceiling() 2.0. v,
-1.02, Ceiling() -1
v
double Cosh(
double Exp(
,
v
(
),
v. , v,
1.02, Floor() 1.0. v,
-1.02, Floor() -2
dividend/divisor
double Asin(
double Floor(
19. System
v
v
base
v
10
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
505
. 19.1.
v1 v2
506
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
v1 v2
base,
exp(baseexp)
v,
v,
II. C#
. 19.1
v, ,
frac
v, ,
frac
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
-1, v , 0,
v , 1, v
v
v
v
v
v
, Sqrt(),
.
() .
// .
using System;
class Pythagorean {
public static void Main() {
double s1; double s2;
double hypot;
string str;
Console.WriteLine(" : ");
str = Console.ReadLine();
s1 = Double.Parse(str);
19. System
507
Console.WriteLine(" : ");
str = Console.ReadLine();
s2 = Double.Parse(str);
hypot = Math.Sqrt(s1*s1 + s2*s2);
Console.WriteLine(" " + hypot);
:
:
3
:
4
5
, Pow()
,
.
:
InitialInvestment = FutureValue / (1 + InterestRate) Years
Pow() double,
double-.
decimal.
/* ,
. */
using System;
class IntialInvestment {
public static void Main() {
decimal InitInvest; //
decimal FutVal; //
double NumYears; //
double IntRate;
//
//
string str;
Console.Write(" : ");
str = Console.ReadLine();
try {
FutVal = Decimal.Parse(str);
}
catch(FormatException exc) {
Console.WriteLine(exc.Message);
return;
}
Console.Write(
" (, 0.085): ");
str = Console.ReadLine();
try {
508
II. C#
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
14
, ,
, .
.
C#- . ,
, ,
. .NET-
C#:
.NET-
C#-
.NET-
C#-
Boolean
Decimal
Single
Int32
UInt16
UInt64
SByte
bool
decimal
float
int
ushort
ulong
sbyte
Char
Double
Int16
Int64
UInt32
Byte
char
double
short
long
uint
byte
19. System
509
, ,
IFormatProvider
NumberStyles.
:
Byte
SByte
Int16
UInt16
Int32
UInt32
Int64
UInt64
(. . 19.2),
, Parse(). Parse()
, . ,
Int32 Parse() int, UInt16
ushort. ( Parse()
14.)
, . 19.2,
const-:
MaxValue
MinValue
,
, .
:
IComparable, IConvertible IFormattable.
19.2. ,
v. ,
.
,
, ,
,
v
-
public static _
Parse(
string str,
IFormatProvider fmtpvdr)
510
TypeCode
. , Int32
TypeCode.Int32
, str.
,
, str
(
,
),
fmtpvdr.
,
II. C#
. 19.2
public static
_
Parse(
string str,
NumberStyles styles)
, str,
,
styles.
,
, str,
,
styles, a (
,
), fmtpvdr.
,
,
format
(
,
),
fmtpvdr
(
,
),
fmtpvdr, ,
format
public static
_
Parse(
string str,
NumberStyles styles,
IFormatProvider
fmtpvdr)
: Double
Single. Single float. . 19.3,
. 19.4. Double double.
. 19.5, . 19.6. ,
Parse() ToString()
( ,
), .
:
IComparable, IConvertible IFormattable.
19.3. , single
public int
CompareTo(object v)
v. ,
. ,
,
,
,
v
19. System
511
. 19.3
512
TypeCode
single, .. TypeCode.Single
, v
( "" "").
, v .
, v
"".
, v
"".
, str.
float,
, str
( ,
),
fmtpvdr.
float,
, str,
,
styles.
float,
, str,
,
styles, a (
,
), fmtpvdr.
float,
,
format
(
,
),
fmtpvdr
(
,
),
fmtpvdr, ,
format
II. C#
19.4. , Single
,
float
,
float
,
,
,
19.5. , Double
v. ,
.
, ,
,
,
v
-
TypeCode
Double, .., TypeCode.Double
, v
( ""
"").
, v .
, v
"".
, v
"".
, str.
double,
, str
(
,
), fmtpvdr.
double,
, str,
,
styles.
double,
19. System
513
. 19.5
, str,
,
styles,
( ,
),
fmtpvdr.
double,
, format
( ,
),
fmtpvdr
( ,
),
fmtpvdr, ,
format
public string
ToString(
string format,
IFormatProvider fmtpvdr)
19.6. , Double
,
double
,
double
,
,
,
Decimal
Decimal , .
, , ,
decimal C#-. ,
decimal
.
Decimal .
:
public Decimal(int v)
public Decimal(uint v)
public Decimal(long v)
514
II. C#
public Decimal(ulong v)
public Decimal(float v)
public Decimal(double v)
Decimal-
.
Decimal- ,
:
public Decimal(int low, int middle, int high,
bool signFlag, byte scaleFactor)
decimal . 96 , .
96- 32-
low, middle high. signFlag,
false true
.
scaleFactor, 0 28.
10 (.. 10scaleFactor),
.
,
Decimal- .
:
public Decimal(int[] parts)
int- parts 96- .
31- parts[3] ( 1
), 16-23 .
Decimal : IComparable,
IConvertible IFormattable.
decimal .
// decimal- "".
using System;
class CreateDec {
:
123.45
96- 12345,
.
, Decimal, . 19.7,
. 19.8. Decimal
, decimal-
. decimal
3.
19. System
515
19.7. , Decimal
v1 + v2
516
v1 v2.
, .
, v1 v2,
, v1 v2
v. ,
.
, ,
,
v1 / v2
,
v
, v1 v2
(
decimal),
v. , v, 1.02, Floor()
1.0. v, -1.02, Floor()
-2
, OLE
Automation v, decimal
v
int-.
-
TypeCode
Decimal, .. TypeCode.Decimal
v1 * v2
-v
, str.
decimal,
, str
(
,
), fmtpvdr.
decimal,
II. C#
. 19.7
, str,
,
styles,
decimal,
, str,
,
styles,
{ ,
),
fmtpvdr.
decimal,
v1 / v2
v, ,
decPlaces, 0-28
v1 - v2
byte- v.
. v
,
byte, OverflowException
double- v.
, double
, decimal
short- v.
. v
,
short, OverflowException
int- v.
. v
, int,
OverflowException
long- v.
, v
,
long, OverflowException
v
OLE Automation
sbyte- v.
. v
,
sbyte, OverflowException
float- v.
, float
, decimal
19. System
517
. 19.7
, format
( ,
),
fmtpvdr
( ,
),
fmtpvdr, ,
format
ushort- v.
. v
,
ushort,
OverflowException
uint- v.
. v
,
uint, OverflowException
ulong- v.
. v
,
ulong, OverflowException
, v.
,
19.8. , Decimal
,
decimal
-1 decimal
,
decimal
1 decimal
0 decimal.
char
, ( ,
) Char. ,
, .
, ToUpper(),
518
II. C#
. IsDigit() ,
.
, Char, . 19.9.
Char :
public const char MaxValue
public const char MinValue
,
char. Char IComparable
IConvertible.
19.9. , Char
v, ,
. ,
,
,
,
v
IsControl(
IsDigit(
IsDigit(
IsLetter(
-
ch, ch . -1
str[idx],
. -1
TypeCode
Char, .. TypeCode.Char
UnicodeCategory
ch. UnicodeCategory ,
System.Globalization, Unicode
UnicodeCategory
str[idx]. UnicodeCategory ,
System.Globalization, Unicode
, ch
.
, str[idx]
.
, ch
.
, str[idx]
.
, ch
.
19. System
519
. 19.9
, str[idx]
.
, ch
.
, str[idx]
.
520
, ch
, str[idx]
.
, ch
(0-9 A-F).
, str[idx]
(0-9 A-F).
, ch
.
, str[idx]
.
, ch
, .
, str[idx]
, .
, ch
Unicode.
, str[idx]
Unicode.
, ch
, .
, str[idx]
,
.
, ch
.
, str[idx]
.
II. C#
. 19.9
, ch
, .
, str[idx]
, .
char- str.
str ,
FormatException
ch, ch
.
ch
ch, ch
.
ch .
,
,
. CultureInfo ,
System.Globalization
ch, ch
.
ch
ch, ch
.
ch .
,
,
. CultureInfo ,
System.Globalization
Char-
ch
Char-
fmtpvdr ,
,
,
Char:
// ,
// Char.
using System;
class CharDemo {
public static void Main() {
string str = " . $23";
int i;
19. System
521
// .
string newstr = "";
for(i=0; i < str.Length; i++)
newstr += Char.ToUpper(str[i]);
Console.WriteLine(" : " + newstr);
:
.
$
2
3
: . $23
: . $23
522
II. C#
Boolean
Boolean bool. ,
Boolean, . 19.10.
:
public static readonly string FalseString
public static readonly string TrueString
true
false. , FalseString
WriteLine(), False.
Boolean IComparable IConvertible.
19.10. , Boolean
v. ,
. ,
false, v
true. ,
true, a v false
true,
v
-
TypeCode
Boolean, .. TypeCode.Boolean
bool- ,
str.
True, False, .
, ;
fmtpvdr ,
,
Array
System Array. Array
C#. ,
, ,
. , Array, . 19.11,
. 19.12.
Array : ICloneable, ICollection,
IEnumerable IList. ICollection, IEnumerable IList
System.Collections 22.
19. System
523
Array
IComparer.
System.Collections, Compare(),
.
int Compare(object v1, object v2)
, v1 v2,
, v1 v2, , .
.
, ,
. Array
. Sort(), ,
, /.
BinarySearch(). , int-
Sort() BinarySearch():
// .
using System;
class SortDemo {
public static void Main() {
int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };
//
// .
Console.Write(" : ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// .
Array.Sort(nums);
// .
Console.Write(" : ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
// 14.
int idx = Array.BinarySearch(nums, 14);
Console.WriteLine(" 14 " + idx);
:
:
5 4 6 3 14 9 8 17 1 24 -1 0
:
-1 0 1 3 4 5 6 8 9 14 17 24
14 9
524
II. C#
int, .. .
, Array,
. .
,
IComparable.
,
. , IComparable
, :
int CompareTo(object v)
v.
, v, ,
, ,
v. ,
, , :
// .
using System;
class MyClass : IComparable {
public int i;
public MyClass(int x) {
i = x;
}
// IComparable.
public int CompareTo(object v) {
return i - ((MyClass)v).i;
}
}
class SortDemo {
public static void Main() {
MyClass[] nums = new MyClass[5];
nums[0] = new MyClass(5);
nums[1] = new MyClass(2);
nums[2] = new MyClass(3);
nums[3] = new MyClass(4);
nums[4] = new MyClass(1);
//
// .
Console.Write(" ;
");
foreach(MyClass o in nums)
Console.Write(o.i + " ");
Console.WriteLine();
// .
Array.Sort(nums);
// .
Console.Write(" :
foreach(MyClass o in nums)
Console.Write(o.i + " ");
Console.WriteLine();
19. System
");
525
// 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
. ,
, , ,
. :
Reverse().
. :
// .
using System;
class ReverseDemo {
public static void Main() {
int[] nums = { 1, 2, 3, 4, 5 };
// .
Console.Write(" :
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
");
// .
Array.Reverse(nums);
// .
Console.Write(" :
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
");
// .
Array.Reverse(nums, 1, 3);
526
//
// .
Console.Write(" : ");
foreach(int i in nums)
Console.Write(i + " ");
Console.WriteLine();
II. C#
:
:
1 2 3 4 5
:
5 4 3 2 1
:
5 2 3 4 1
. , ().
- , ,
() . ()
:
// .
using System;
class CopyDemo {
public static void Main() {
int[] source = { 1, 2, 3, 4, 5 };
int[] target = { 11, 12, 13, 14, 15 };
int[] source2 = { -1, -2, -3, -4, -5 };
// - .
Console.Write("-: ");
foreach(int i in source)
Console.Write(i + " ");
Console.WriteLine();
// -.
Console.Write(
" -: ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
// .
Array.Copy(source, target, source.Length);
// .
Console.Write(" : ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
// target.
Array.Copy(source2, 2, target, 3, 2);
// .
Console.Write(
" : ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
19. System
527
:
-: 1 2 3 4 5
-: 11 12 13 14 15
: 1 2 3 4 5
: 1 2 3-3-4
19.11. , Array
.
true, , false,
.
true, Array
, false
.
true,
, false
.
.
. ,
19.12, , Array
, ,
, v.
.
, .
, ,
, v,
, comp.
.
, .
, ,
, v,
, start, count
.
. ,
.
, ,
, v,
, comp.
, start,
count .
. ,
.
528
II. C#
. 19.12
.
, ,
, start, count
.
, ,
"". ,
, , ,
count source
dest.
.
, () "
",
count source (
srcStart) dest (
destStart).
, C()
" ",
dest,
dest[start]
,
size t
size1*size2. t
size1*size2*size3.
t
,
sizes.
t
,
sizes.
t.
startIndexes.
, ,
,
true,
v
.
.
22, ""
19. System
529
. 19.12
.
; ,
0,
1
,
. dim
, ;
,
0,
1
-
530
TypeCode
Array, .. TypeCode.Array
,
. dim
, ;
,
0,
1
idx.
[idx1, idx2].
[idx1, idx2, idx3].
, idxs.
,
idxs
, , v.
-1, , (
, 0,
, 1)
, , v.
[start]. -1,
. (
, 0,
,
1)
, , v.
a[start] count
. -1,
. (
, 0,
,
1)
II. C#
. 19.12
,
.
, ,
v. -1, . (
, 0,
, 1)
, ,
v.
, [start]
[0], -1,
. ( ,
0,
, 1)
, ,
v.
, a[start],
count . -1,
. (
, 0,
, 1)
.
a[start] count
idx v.
[idx1, idx2] v.
[idx1, idx2, idx3] v.
, idxs,
v. ,
idxs
.
,
comp.
19. System
531
. 19.12
. k , v
, . ,
/.
,
comp. k ,
v - , .
,
/.
.
[start]
count .
,
comp. a[start]
count .
.
, start,
count . k
, v ,
. ,
/.
,
comp.
,
start, count . k
, v ,
. ,
/.
BitConverter
. ,
, .
.
,
. ,
, .
C# BitConverter.
532
II. C#
BitConverter , . 19.13.
:
public static readonly bool IsLittleEndian
true,
( ), ( )
. ( ) , ..
, (little-endian format). IsLittleEndian
false,
( ), ( ) .
(big-endian format). ,
Pentium Intel, .
BitConverter sealed-, ..
.
19.13. , BitConverter
v
long
19. System
v
v
v
v
v
v
v
v
v
v
v
double
a[idx]
bool- .
true,
false
, a[start],
char-
533
. 19.13
,
a[start], double-
, [start],
short-
,
a[start], int-
,
[start], long-
,
[start], float-
.
(
),
,
a[start], .
( ),
count ,
a[start], .
( ),
, a[start],
ushort-
,
a[start], uint-
,
a[start], ulong-
Random
,
Random. ,
.
,
Random .
Random :
public Random()
public Random(int seed)
534
II. C#
Random,
.
seed.
, Random, . 19.14.
19.14. , Random
int,
0-Int32.MaxValue-1,
int,
0-upperBound-1,
int,
lowerBound - upperBound-1,
buf
.
0-Byte.MaxValue-1,
(
), 0,0
1,0
(
), 0,0
1,0.
,
, Random
:
// ,
using System;
class RandDice {
:
5 2 4 4 1 6
Random.
, 16.
19. System
535
GC
GC C#- . ,
, . 19.15. ,
:
public static int MaxGeneration { get; }
MaxGeneration
. (. new)
, ,
, .
, MaxGeneration ,
.
GC.
,
Collect() .
, .
, ,
,
().
GC sealed-, .
19.15. , G
536
0 MaxGen
,
,
"" ,
""
( )
collect
true,
,
SuppressFinalize()
,
II. C#
Object
Object , C#- object.
Object 11, C# (
) . 19.16. Object
:
Object()
.
19.16. , Object
true,
, , ob.
false
true, ob1
, ob2.
false
. C# Finalize()
-,
" " , ..
, ,
IComparable
IComparable,
, C#-, .
IComparable ,
:
int CompareTo(object v)
v.
, v, ,
, ,
v.
19. System
537
IConvertible
IConvertible .
. ,
.
ICloneable
ICloneable, .
ICloneable :
object Clone()
. ,
Clone(), . :
.
. , O,
O.
, , .
O,
, O,
, O, , .
Clone() , .
MemberwiseClone(),
Object.
,
ICloneable. Test,
X. Test Clone().
// ICloneable.
using System;
class X {
public int a;
public X(int x) {
a = x;
}
538
II. C#
// .
public object Clone() {
Test temp = new Test(o.a, b);
return temp;
}
class CloneDemo {
public static void Main() {
Test ob1 = new Test(10, 20);
ob1.show("ob1");
Console.WriteLine(
" b2 ob1.");
Test ob2 = (Test) ob1. Clone();
ob2.show("ob2");
Console.WriteLine(" ob1.o.a 99, "
+ " ob1.b 88.");
ob1.o.a = 99;
ob1.b = 88;
ob1.show("ob1");
ob2.show("ob2");
:
ob1 : o.a: 10, b: 20
b2 ob1.
b2 : o.a: 10, b: 20
ob1.o.a 99, ob1.b 88.
ob1 : o.a: 99, b: 88
b2 : o.a: 10, b 20
, b2 ob1, ob1
b2 . .
, X,
, X .
Clone() MemberwiseClone(), Object.
, , Clone()
:
// .
public object Clone() {
Test temp = (Test) MemberwiseClone();
return temp;
}
:
ob1 : o.a: 10, b: 20
b2 ob1.
b2 : o.a: 10, b: 20
ob1.o.a 99, ob1.b 88.
19. System
539
IFormatProvider IFormattable
IFormatProvider GetFormat(),
, ,
. GetFormat() :
object GetFormat(Type fmt)
fmt . 20.
IFormattable
. IFormattable
:
string ToString(string fmt, IFormatProvider fmtpvdr)
fmt , fmtpvdr
() . 20.
540
II. C#
20
string. ,
.
string , ,
,
.
, .
,
C#, , .
C#
C# 7,
.
string, C#.
(string)
,
. C++
, C# . C#
string. string . , string
C#- .NET- System.String. , C# , , ,
String.
.
C# ( )
. ,
. ,
, ,
, , ,
.
,
. ,
string, , , .
string-
.
, , C#
StringBuilder, System.Text.
string, StringBuilder.
String
String System.
IComparable, ICloneable, IConvertible IEnumerable.String
sealed-, .. . String C# . C#- string
.NET Framework.
String.
542
II. C#
String
String ,
. ,
:
public String(char[] chrs)
public String(char[] chrs, int start, int count)
,
, chrs. ,
, count , chrs, ,
start.
, ,
. :
public String(char ch, int count)
ch , count .
, ,
:
unsafe public String(char* chrs)
unsafe public String(char* chrs, int start, int count)
,
, chrs. ,
chrs ( ). ,
, count ,
, chrs, ,
start.
, ,
:
unsafe public String(sbyte* chrs)
unsafe public String(sbyte* chrs, int start, int count)
unsafe public String(sbyte* chrs, int start, int count,
Encoding en)
,
, chrs. , chrs
( ). ,
, count ,
, chrs, ,
start. .
ASCIIEncoding. Encoding
System.Text.
.
. :
string str = " ";
, String
string :
public static readonly string Empty
Empty , .. , .
() String,
.
20.
543
String ,
:
public char this[int idx] { get; }
.
, . String
, , String ,
, .
String ,
:
public int Length { get; }
Length , .
String
String : == !=.
, , ==. ==
, , .
== String,
. !=: String .
(, < >=), ,
. , , () ,
Compare(), String.
String
String .
.
,
.
, ,
. String
, . 20.1.
Compare(). ,
( ) (.. ).
, .. ,
, , .
( ,
, ),
.
Compare()
:
// .
using System;
class CompareDemo {
public static void Main() {
string str1 = "";
string str2 = "";
544
II. C#
if(result < 0)
Console.WriteLine(str1 + " " + str4);
else if(result > 0)
Console.WriteLine(str1 + " " + str4);
else
Console.WriteLine(str1 + " " + str4);
:
.
.
.
, .
, .
20.
545
20.1. , String
, str1, ,
str2.
, str1 str2, ,
str1 str2, , str1 str2
, str1, ,
str2.
, str1 str2, ,
str1 str2, , str1 str2 .
ignoreCase true,
.
, str1, ,
str2,
( ,
),
ci. ,
str1 str2, , str1
str2, , str1 str2 .
ignoreCase true,
.
. CultureInfo
System.Globalization
, str1 str2.
str1[start1]
str2[start2] count .
, str1
str2, , str1 str2-, ,
str1 str2
, str1 str2.
str1[start1]
str2[start2] count .
, str1
str2, , str1-
srtr2-, , str1
str2 . ignoreCase true,
.
, str1 str2,
(
,
), ci.
str1[start1]
str2[start2] count .
, str1
str2, , str1-
str2-, , str1 str2
. ignoreCase true,
.
. CultureInfo
System.Globalization
546
II. C#
. 20.1
, str1, ,
str2, ,
.
, str1 str2,
, str1 str2, ,
str1 str2
, str1 str2,
,
.
str1[start1] str2[start2] count .
,
str1 str2, ,
str1- str2-, ,
str1 str2
,
str. ,
str, ,
str, ,
,
str. ,
str, ,
str, ,
() . , 7, +. -,
, String.
+ ,
.
, , Concat(),
:
public static string Concat(string str1, string str2)
, str2,
str1.
Concat() :
public static string Concat( string str1,
string str2,
string str3)
,
str1, str2 str3. ,
+, Concat().
Concat() ,
:
public static string Concat(params string[] strs)
20.
547
Concat()
. Concat()
:
// Concat().
using System;
class ConcatDemo {
public static void Main() {
string result = String.Concat(
" ", " ",
" ", " ", " ",
" ", " ",
"String.");
Console.WriteLine(": " + result);
}
}
:
:
String.
Concat() string-, a object-.
, . Concat()
:
public static string Concat(object v1, object v2)
public static string Concat( object v1,
object v2,
object v3)
public static string Concat(params object[] v)
,
v2, v1.
,
v1, v2 v3. ,
, v.
, :
// Concat().
using System;
class ConcatDemo {
548
II. C#
:
: 10 20 False 23.45
Concat()
.
ToString(), . ,
10 Int32.ToString(). Concat()
. Concat()
,
.
String ,
( ).
.
, IndexOf(), :
public int IndexOf(char ch)
public int IndexOf(string str)
IndexOf(), ,
ch .
str. 1,
.
,
LasItndexOf(), :
public int LastIndexOf(char ch)
public int LastIndexOf(string str)
LastIndexOf(), ,
ch .
str. 1,
.
String : IndexOfAny()
LastIndexOfAny(). ,
. :
public int IndexOfAny(char[] a)
public int LastIndexOfAny(char[] a)
IndexOfAny()
, . LastIndexOfAny()
,
. 1,
.
,
.
StartsWith() EndsWith():
public bool StartsWith(string str)
public bool EndsWith(string str)
StartsWith() true,
, str. EndsWith()
true, ,
str. false.
20.
549
:
// .
using System;
class StringSearchDemo {
public static void Main() {
string str =
"C# .";
int idx;
Console.WriteLine("str: " + str);
idx = str.IndexOf('');
Console.WriteLine(
" '': " + idx);
idx = str.LastIndexOf('');
Console.WriteLine(
" '': " + idx);
idx = str.IndexOf("");
Console.WriteLine(
" \"\": " + idx);
idx = str.LastIndexOf("");
Console.WriteLine(
" \"\": " + idx);
char[] chrs = { '', '', '' };
idx = str.IndexOfAny(chrs);
Console.WriteLine(
" '', '' '': " + idx);
if(str.StartsWith("C# "))
Console.WriteLine(
"str \"C# \"");
if(str.EndsWith("."))
Console.WriteLine(
"str \".\"");
:
str: C# .
'': 20
'': 41
"": 17
"": 28
'', '' '': 4
str "C# "
str "."
,
.
550
II. C#
, String, . 20.2.
20.2. , String
true,
, str.
false
ch
. -1,
str
. -1,
ch
. ,
start. -1,
str
. ,
start. -1,
ch
. ,
start, count .
-1,
str
. ,
start, count .
-1,
,
. -1,
,
. ,
start. -1,
,
. ,
start, count .
-1,
ch
. -1,
str
. -1,
ch,
.
, ,
start,
. -1,
20.
551
. 20.2
str,
.
, ,
start,
. -1,
ch,
.
, ,
start, count .
-1,
str,
.
, ,
start, count .
-1,
,
. -1,
,
. ,
, start,
. -1,
,
. ,
, start,
count . -1,
true,
, str.
false
public int
LastIndexOfAny(
char[] a)
public int
LastIndexOfAny(
char[] a,
int start)
public int
LastIndexOfAny(
char[] a,
int start,
int count)
public bool StartsWith(
string str)
()
. .
. string
Split(), Join().
Split() :
public string[] split(params char[] seps)
public string[] split(params char[] seps, int count)
, . ,
, seps. seps
null-, .
,
count.
Join():
552
II. C#
// .
string[] parts = str.Split(seps);
Console.WriteLine(
" : ");
for(int i=0; i < parts.Length; i++)
Console.WriteLine(parts[i]);
// .
string whole = String.Join(" | ", parts);
Console.WriteLine(" : ");
Console.WriteLine(whole);
:
:
:
| | | | | | | | |
|
,
, .
, , Split()
, , 100
(, 100).
20.
553
, (
), . .
,
, 10 + 5, .
// .
using System;
class TokenizeDemo {
public 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 + n2);
break;
case "-":
Console.WriteLine(n - n2);
break;
case "*":
Console.WriteLine(n * n2);
break;
case "/":
Console.WriteLine(n / n2);
break;
}
:
: 100 + 19 , : 119
: 100 / 3.3 , : 30.3030303030303
: -3 + 9 , : -27
: 100 - 87 , : 13
554
II. C#
.
, , . ,
print.
.
, ,
. , ,
, .
,
, . . , C#
, .
,
Trim():
public string Trim()
public string Trim(params char[] chrs)
. ,
chrs. ,
.
C#
.
:
public string PadLeft(int len)
public string PadLeft(int len, char ch)
,
len. ,
, ch.
, .
:
public string PadRight(int len)
public string PadRight(int len, char ch)
,
len. ,
, ch. ,
.
:
//
// .
using System;
class TrimPadDemo {
public static void Main() {
string str = "";
Console.WriteLine(" : " + str);
20.
555
// .
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 + "|");
:
:
|
|
|
|
||
|###### |
|################|
||
,
Insert() :
public string Insert(int start, string str)
str , .
() start. ,
.
Remove() :
public string Remove(int start, int count)
count. (),
, start. ,
.
Replace()
. :
public string Replace(char ch1, char ch2)
public string Replace(string str1, string str2)
ch1 ch2.
556
II. C#
str1 str2. ,
.
,
Insert(), Remove() Replace():
// , .
using System;
class InsRepRevDemo {
public static void Main() {
string str = " ";
Console.WriteLine(" : " + str);
// .
str = str.Insert(4, " ");
Console.WriteLine(str);
// .
str = str.Replace("", "");
Console.WriteLine(str);
// .
str = str.Replace('', 'X');
Console.WriteLine(str);
// .
str = str.Remove(4, 5);
Console.WriteLine(str);
:
:
String ,
, .. . ToUpper()
ToLower():
public string ToLower()
public string ToUpper()
ToLower()
, ToUpper() . ,
. ,
, ,
.
20.
557
Substring()
Substring() .
:
public string Substring(int idx)
public string Substring(int idx, int count)
,
idx, .
, , idx,
count . .
Substring() :
// Substring().
using System;
class SubstringDemo {
public static void Main() {
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("str: " + str);
Console.Write("str.Substring(15): ");
string substr = str.Substring(15);
Console.WriteLine(substr);
:
str: ABCDEFGHIJKLMNOPQRSTUWXYZ
str.Substring(15): PQRSTUVWXYZ
str.Substring(0, 15): ABCDEFGHIJKLMNO
(, int double)
, ,
. C#
, .
, I,
.
, Console.WriteLine(),
String.Format() ToString().
, ,
, .
558
II. C#
:
() . ,
,
. ,
. ,
( ),
.
,
. , ,
. C# .
IFormatProvider.
.NET Framework.
, ,
.
.
3, .
WriteLine(),
,
.
WriteLine(),
WriteLine():
WriteLine("_",
arg0, arg1, ... , argN);
WriteLine()
, +, _
: .
, ,
.
:
{_, : )
_
( ).
, .
. ,
, . ,
{0} arg0, {1} arg1 ..
WriteLine()
, ( ) ,
_. ,
_ ,
, .
,
.
.
, , ,
, . ,
20.
559
, , .
.
, , . 20 3.
.
, , , ,
, F2,
,
,
, . , ,
, ,
.
. ,
, ,
.
,
:
//
// .
using System;
class FormatDemo {
public static void Main() {
double v = 17688.65849;
double v2 = 0.15; int x = 21;
Console.WriteLine("{0:F2}", v);
Console.WriteLine("{0:N5}", v);
Console.WriteLine("{0:e}", v);
Console.WriteLine("{0:r}", v);
Console.WriteLine("{0:p}", 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 %
560
II. C#
15
000000000021
$189.99
,
.
20.3.
C
c
D
(
)
d
E
D
(
E)
(
)
F
- F-
f-
(
)
N
P
,
Parse()
"" (
"
*.)
(
A-F)
F
f
G
g
N
n
P
p
R r
(
a-f)
.
.
.
. F
. f
.
.
String.Format()
ToString()
WriteLine()
,
, ,
. ,
20.
561
,
. GUI-,
Windows, - .
: String.Format()
ToString().
String.Format()
Format(), String ( . 20.4).
Format() WriteLine(), ,
Format() , .
20.4. Format()
v
, str.
str,
v1
, str, v2
. str,
v1, v2 v3
,
str. str,
, v,
,
str.
str,
, v,
,
str,
, fmtprvdr.
str,
,
, String.Format().
.
// String.Format()
// .
using System;
class FormatDemo {
public static void Main() {
562
II. C#
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
string str = String.Format("{0:F2}", v);
Console.WriteLine(str);
str = String.Format("{0:N5}", v);
Console.WriteLine(str);
str = String.Format("{0:e}", v);
Console.WriteLine(str);
str = String.Format("{0:r}", v);
Console.WriteLine(str);
str = String.Format("{0:p}", v2);
Console.WriteLine(str);
str = String.Format("{0:X}", x);
Console.WriteLine(str);
str = String.Format("{0:D12}", x);
Console.WriteLine(str);
WriteLine(), String.Format()
. ,
1 10:
// Format().
using System;
class FormatDemo2 {
public static void Main() {
int i;
int sum = 0;
int prod = 1;
string str;
/*
1 10. */
for(i=1; i <= 10; i++) {
sum += i;
prod *= i;
str = String.Format(
":{0,3:D} :{1,8:D}", sum, prod);
Console.WriteLine(str);
}
20.
563
:
: 1 :
1
: 3 :
2
: 6 :
6
: 10 :
24
: 15 :
120
: 21 :
720
: 28 :
5040
: 36 :
40320
: 45 : 362880
: 55 : 3628800
:
str = String.Format(":{0,3:D} :{1,8:D}",
sum, prod);
Format() :
( sum), ( prod). ,
,
WriteLine().
(: :), .
ToString()
,
(, Int32 Double),
ToString():
public string ToString(string fmt)
ToString()
, fmt.
, 188.99,
C:
string str = 189.99.ToString("C");
,
ToString(). WriteLine() Format(),
(
), ToString() .
,
ToString().
.
// ToString()
// .
using System;
class ToStringDemo {
public static void Main() {
double v = 17688.65849;
double v2 = 0.15;
int x = 21;
564
II. C#
str = 189.99.ToString("C");
Console.WriteLine(str);
, C#
, ,
(picture format).
, (.. ) ,
.
I. .
-
, ,
. , . 20.5.
20.5. -,
#
.
,
%
0
20.
565
. 20.5
, ,
e0 E+0 E-0
e0 e+0 -0
.
#
. ( )
, ()
. . #
, , .
.
, #,
. ,
# , .
( )
. , , ##.##,
, .
, - 0.
- 0
, ,
. ,
. ,
Console.WriteLine("{0:00##.#00}", 21.3);
:
0021.300
,
, ( )
, ( ) .
, #
. ,
Console.WriteLine("{0:#,###.#)", 3421.3);
:
3,421.3.
,
.
(
) . ,
Console.WriteLine("{0:#,###.#}", 8763421.3);
:
8,763,421.3.
.
( ),
566
II. C#
. 1 000.
,
Console.WriteLine(
" : {0:#, ###, .#}", 8763421.3);
:
: 8,763.4
, ,
.
-
. , ,
, .
,
Console.WriteLine(
" {0:##.# }",
21.3);
:
21.3
, \t \n.
- ,
( ).
0. 0
, .
. , ().
E+ e+,
: , , - -.
; ,
, .
- ; :
-;-;-
:
Console.WriteLine("{0:#.##;(#.##);0.00}", num);
num ,
. num ,
. num ,
0.00. - ;
. ,
, -.
,
-. - -
.
, :
// .
using System;
20.
567
class PictureFormatDemo {
public static void Main() {
double num = 64354.2345;
Console.WriteLine(" : " + num);
// .
Console.WriteLine(
" : " +
"{0:#.##}", num);
//
// .
Console.WriteLine(" : {0:#,###.##}", num);
//
// .
Console.WriteLine(
" : " +
"{0:#.###+00}", num);
// .
Console.WriteLine(" : " + "{0:#0,}", num);
/* ,
-. */
Console.WriteLine(" , " +
" " +
" -.");
Console.WriteLine("{0:#.#;(#.##);0.00}", num);
num = -num;
Console.WriteLine("{0:#.##;(#.##);0.00}", num);
num = 0.0;
Console.WriteLine("{0:#.##;(#.##);0.00}", num);
// .
num = 0.17;
Console.WriteLine(" : {0:#%}", num);
:
: 64354.2345
: 64354.23
: 64,354.23
: 6.435+04
: 64
, .
64354.2
(64354.23)
0.00
: 17%
568
II. C#
,
DateTime. 19, DateTime .
. :
02/25/2002
Monday, February 25, 2002
12:59:00
12:59:00 PM
,
. C#
.
, . 20.6.
,
,
.
20.6.
D
d
T
t
f
f
g
g
M
m
R
r
s
U
u
Y
y
,
R
;
(Universal Time Coordinated UTC)
Y
,
, :
// .
using System;
class TimeAndDateFormatDemo {
20.
569
f:
F:
g:
G:
{0:f}",
{0:F}",
{0:g}",
{0:G}",
dt);
dt);
dt);
dt);
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
Console.WriteLine("
m:
:
r:
R:
{0:m}",
{0:M}",
{0:r}",
{0:R}",
dt);
dt);
dt);
dt);
:
d: 10.09.2003
D: 10 2003 .
t: 14:53
: 14:53:11
f: 10 2003 . 14:53
F: 10 2003 . 14:53:11
g: 10.09.2003 14:53
G: 10.09.2003 14:53:11
m: 10
: 10
r: Wed, 10 Sep 2003 14:53:11 GMT
R: Wed, 10 Sep 2003 14:53:11 GMT
s: 2003-09-10T14:53:11
u: 2003-09-10 14:53:11Z
U: 10 2003 . 11:53:11
y: 2003 .
Y: 2003 .
.
. . (
) ToString(),
DateTime.
(\).
// .
using System;
570
II. C#
class SimpleClock {
public static void Main() {
string t;
int seconds;
DateTime dt = DateTime.Now;
seconds = dt.Second;
for(;;) {
dt = DateTime.Now;
//
// seconds.
if(seconds != dt.Second) {
seconds = dt.Second;
t = dt.ToString("T");
if(dt.Minute==0 && dt.Second==0)
t = t + "\a";
//
// .
Console.WriteLine(t);
,
.
, . ,
() , , .
-, . 20.7.
, , d, f, g, m, M, s t
, ,
. 20.6. , ,
.
. ,
, (%).
:
//
// .
using System;
class CustomTimeAndDateFormatsDemo {
public static void Main() {
DateTime dt = DateTime.Now;
20.
571
Console.WriteLine(" m : {0:m}",
dt);
Console.WriteLine(" m : {0:%m}",
dt);
:
: 11:14
24- : 11:14
: 11, 2003
: A.D.
: 11:14:52
m : 11
m : 14
: A.D. . . anno Domini, .. .
20.7. -,
d
dd
ddd
dddd
f, ff, fff,
ffff, fffff,
ffffff,
fffffff
g
h
hh
H
HH
m
mm
M
MM
MMMM
s
572
, 1-31
, 1-31. 19
.
"f"
1-12
1-12. 1-9
0-23
0-23. 1-9
. 1-9
1-12
1-12. 1-9
II. C#
. 20 7
ss
t
, 1-9
"" "P", . ( ) P.M. ( ),
AM. P.M.
,
. 1-9
. 1-9
, fmt
tt
y
yy
yyyy
z
zz
zzz
:
/
% fmt
C# , .
.
, , . 20.8.
G F. ,
, Flags.
, .
Flags G
. F
, ,
, .
:
// .
using System;
class EnumFmtDemo {
enum Direction { , , , }
[Flags] enum Status { =0x1, _=0x2,
=0x4, _=0x8,
_= 0x10,
_=0x20
}
public static void Main() {
Direction d = Direction.;
Console.WriteLine("{0:G}",
Console.WriteLine("{0:F}",
Console.WriteLine("{0:D}",
Console.WriteLine("{0:X}",
20.
d);
d);
d);
d);
573
Console.WriteLine("{0:G}",
Console.WriteLine("{0:F}",
Console.WriteLine("{0:D}",
Console.WriteLine("{0:X}",
s);
s);
s);
s);
3
00000003
, _
, _
9
00000009
20.8.
G
g
F
f
D
d
X
x
574
.
Fiags,
( , )
G
. ,
, ,
, , Flags
f
d
.
X
II. C#
21
C# , ,
(multithreaded
programming). ,
.
(thread), .
, .
,
C#, , .NET Framework.
, , , C#
,
.
:
. .
. , , ,
,
. , ,
, ( )
Internet. -
,
.
. ,
, ,
. ,
. ,
- ,
.
, - -
. -
, -
.
,
,
(), .
, - ( ,
) , ().
( ). ,
,
. ,
, ,
Internet.
.
. ( ).
, ..
. .
576
II. C#
. , ,
() .
.NET Framework :
(foreground) , (background).
, , .. .
- ,
,
.
-
, ,
. C# ,
, .
,
(main thread),
. ,
. .
C# .NET Framework -, . , C#,
, , . ,
, ,
. , C#
. ,
C#
, C++ (
).
, ,
System.Threading.
:
using System.Threading;
Thread
C# Thread,
. Thread sealed-, .. .
Thread .
.
, Thread. Thread
:
public Thread(ThreadStart entryPoint)
entryPoint , ,
. ThreadStart , .NET
Framework:
public delegate void ThreadStart()
21.
577
, void
.
,
Start(), Thread. :
public void Start()
, ,
, entryPoint. entryPoint-
. Start()
, ,
ThreadStateException. , Thread
System.Threading.
:
// .
using System;
using System.Threading;
class MyThread {
public int count;
string thrdName;
public MyThread(string name) {
count = 0;
thrdName = name;
}
// ( ) .
public void run() {
Console.WriteLine(thrdName + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrdName +
", count = " + count);
count++;
} while(count < 10);
Console.WriteLine(thrdName + " .");
}
}
class MultiThread {
public static void Main() {
Console.WriteLine(" .");
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(new ThreadStart(mt.run));
// , .
newThrd.Start();
do {
Console.Write(".");
578
II. C#
Thread.Sleep(10);
} while(mt.count != 10);
Console.WriteLine(" .");
. MyThread
. run() ,
0 9. Sleep(),
Thread. Sleep() ,
, , .
:
public static void Sleep(int milliseconds)
milliseconds ,
. milliseconds ,
,
.
Main()
Thread:
// MyThread.
MyThread mt = new MyThread(" #1");
// .
Thread newThrd = new Thread(new ThreadStart(mt.run));
// , .
newThrd.Start();
, MyThread.
Thread
mt.run , . ,
Start() .
run() . Start()
Main(), do. ,
, .
:
.
. #1 .
.... #1, count = 0
....... #1, count = 1
.... #1, count = 2
...... #1, count = 3
.... #1, count = 4
..... #1, count = 5
...... #1, count = 6
.... #1, count = 7
....... #1, count = 8
.... #1, count = 9
#1 .
.
,
. ,
. ,
21.
579
.
,
.
, do ,
count 10. count
10 , newThrd,
.
.
,
. -,
.
MyThread Thread
MyThread. -,
MyThread, Thread Name,
. Name :
public string Name { get; set; }
Name ,
.
:
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name; // .
thrd.Start(); // .
}
// .
void run() {
Console.WriteLine(thrd.Name + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " .");
class MultiThreadImproved {
580
II. C#
Console.WriteLine(" .");
, .
, thrd
MyThread.
.
, .
, :
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// .
void run() {
Console.WriteLine(thrd.Name + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " .");
}
class MoreThreads {
public static void Main() {
21.
581
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
..... #1, count = 1
#2, count = 1
#3, count = 1
.... #1, count = 2
#2, count = 2
#3, count = 2
..... #1, count = 3
#2, count = 3
#3, count = 3
.... #1, count = 4
#2, count = 4
#3, count = 4
..... #1, count = 5
#2, count = 5
#3, count = 5
..... #1, count = 6
#2, count = 6
#3, count = 6
.... #1, count = 7
#2, count = 7
#3, count = 7
..... #1, count = 8
#2, count = 8
#3, count = 8
.... #1, count = 9
#1 .
#2, count = 9
#2 .
#3, count = 9
#3 .
.
582
II. C#
,
. - ,
.
, .
count,
. , Thread
, .
IsAlive. :
public bool IsAlive { get; }
IsAlive true, ,
, . false.
, MoreThreads
, :
// IsAlive
// .
class MoreThreads {
public static void Main() {
Console.WriteLine(" .");
//
MyThread mt1 =
MyThread mt2 =
MyThread mt3 =
.
new MyThread(" #1");
new MyThread(" #2");
new MyThread(" #3");
do {
Console.Write("."); Thread.Sleep(100);
} while( mt1.thrd.IsAlive &&
mt2.thrd.IsAlive &&
mt3.thrd.IsAlive);
Console.WriteLine(" .");
MoreThreads
. ,
IsAlive.
, ,
Join().
:
public void Join()
Join() , , , .
(join . . )
21.
583
, .
,
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(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// .
void run() {
Console.WriteLine(thrd.Name + " .");
do {
Thread.Sleep(500);
Console.WriteLine(" " + thrd.Name +
", count = " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " .");
}
// Join() .
class JoinThreads {
public static void Main() {
Console.WriteLine(" .");
// .
MyThread mt1 = new MyThread(" #1");
MyThread mt2 = new MyThread(" #2");
MyThread mt3 = new MyThread(" #3");
mt1.thrd.Join();
Console.WriteLine(" #1 .");
mt2.thrd.Join();
Console.WriteLine(" #2 .");
mt3.thrd.Join();
Console.WriteLine(" #3 .");
584
II. C#
Console.WriteLine(" .");
. ,
, , .
.
#1 .
#2 .
#3 .
#1, count = 0
#2, count = 0
#3, count = 0
#1, count = 1
#2, count = 1
#3, count = 1
#1, count = 2
#2, count = 2
#3, count = 2
#1, count = 3
#2, count = 3
#3, count = 3
#1, count = 4
#2, count = 4
#3, count = 4
#1, count = 5
#2, count = 5
#3, count = 5
#1, count = 6
#2, count = 6
#3, count = 6
#1, count = 7
#2, count = 7
#3, count = 7
#1, count = 8
#2, count = 9
#3, count = 8
#1, count = 9
#1 .
#2, count = 9
#2 .
#3, count = 9
#3 .
#1 .
#2 .
#3 .
.
, Join()
.
IsBackground
, .NET Framework :
. ,
, -
21.
585
,
.
.
IsBackground, Thread :
public bool IsBackground { get; set; }
,
IsBackground true. false ,
.
. , ,
, .
,
. , , ,
,
.
, ( ),
, . ,
,
, ,
.
, .
.
Priority, Thread.
:
public ThreadPriority Priority{ get; set; }
ThreadPriority ,
:
ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest
ThreadPriority.Normal.
, ,
, , .
MyThread. run() ,
. 1 000
000 000, , stop true.
stop false. ,
1 000 000 000, stop true.
( ,
).
currentName . ,
, .
586
II. C#
, currentName
. ,
.
, .
// .
using System;
using System.Threading;
class MyThread {
public int count;
public Thread thrd;
static bool stop = false;
static string currentName;
/* . ,
. */
public MyThread(string name) {
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name; currentName = name;
}
// .
void run() {
Console.WriteLine(" " + thrd.Name + " .");
do {
count++;
if(currentName != thrd.Name) {
currentName = thrd.Name;
Console.WriteLine(" " + currentName);
}
} while(stop == false && count < 1000000000);
stop = true;
class PriorityDemo {
public 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();
21.
587
mt1.thrd.Join();
mt2.thrd.Join();
Console.WriteLine();
Console.WriteLine(" " + mt1.thrd.Name +
" " +
mt1.count);
Console.WriteLine(" " + mt2.thrd.Name +
" " +
mt2.count);
.
. ,
,
. ,
,
588
II. C#
. . ,
, , .
,
, .
.
, ..
. , ,
.
, .
C#,
. lock.
C# ,
.
lock :
lock(object) {
// , .
}
object .
, ,
lock , ,
, ,
. ,
. .
sumIt(), :
// lock
// .
using System;
using System.Threading;
class SumArray {
int sum;
public int sumIt(int[] nums) {
lock(this) { // .
sum =0;
// .
for(int i=0; i < nums.Length; i++) {
sum += nums[i];
Console.WriteLine(
" " +
Thread.CurrentThread.Name +
" " + sum);
Thread.Sleep(10); // .
}
return sum;
class MyThread {
21.
589
// .
void run() {
Console.WriteLine(thrd.Name + " .");
answer = sa.sumIt(a);
Console.WriteLine(" " + thrd.Name +
" " + answer);
Console.WriteLine(thrd.Name + " .");
}
class Sync {
public static void Main() {
int[] a = {1, 2, 3, 4, 5};
MyThread mt1 = new MyThread("
MyThread mt2 = new MyThread("
mt1.thrd.Join();
mt2.thrd.Join();
}
}
:
#1 .
#2 .
#1
#1
#1
#1
#1
#2
#1 15
#1 .
#2
#2
#2
#2
#2 15
#2 .
590
#1", a);
#2", a);
1
3
6
10
15
1
3
6
10
15
II. C#
, .
. .
SumArray. sumIt(),
. , MyThread, static- sa
SumArray. , MyThread
SumArray.
. ,
sum SumArray. ,
sumIt() , sum ""
. ,
sumIt() . ,
Sync, , ..
.
sumIt() lock
. ,
this.
lock, . Sleep()
, (
), . sumIt()
, . ,
, , sumIt() ,
() .
.
lock,
sumIt(). sumIt() ,
. ,
sum ,
, sumIt(). ,
sumIt() ,
, sum
. , ,
lock
sumIt():
#1 .
#1 1
#2 .
#2 1
#1 3
#2 5
#1 8
#2 11
#1 15
#2 19
#1 24
#2 29
#2 29
#2 .
#1 29
#1 .
, sumIt()
, sum . ,
lock.
21.
591
1. lock ,
,
.
2. , ,
,
.
3. , .
, lock
, private-, internal.
.
,
,
, , , . ,
, ,
.
, , ,
. , ,
lock .
? ,
: (
) , lock. ,
. ,
sumIt() .
sumIt() MyThread.
// lock
// .
using System;
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 {
592
II. C#
// lock sumIt().
lock(sa) answer = sa.sumIt(a);
Console.WriteLine(" " + thrd.Name +
" " + answer);
Console.WriteLine(thrd.Name + " .");
class Sync {
public 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();
sa.sumIt(),
sumIt(). :
// lock sumIt().
lock(sa) answer = sa.sumIt(a);
,
.
,
, static-,
, .
. static-, lock
:
21.
593
lock(typeof(class)) {
// .
}
class , static-,
.
Monitor lock
lock ,
, Monitor,
System.Threading. Monitor
. ,
, Enter(), Exit().
public static void Enter(object syncOb)
public static void Exit(object syncOb)
syncOb . Enter()
, ,
. Microsoft , lock-
Enter()
Exit(). lock C#,
C#- .
TryEnter() Monitor.
:
public static bool TryEnter(object syncOb)
true,
syncOb, false .
, , .
Monitor : Wait(), Pulse() PulseAll().
.
Wait(), Pulse() PulseAll()
. ( T)
lock- ( R), .
T? T R,
, .
,
. , T
, . R
, T , .
,
, , ,
. C#
Wait(), Pulse() PulseAll().
Wait(), Pulse() PulseAll() Monitor.
lock- .
594
II. C#
, Wait(), ..
() ,
. ,
Pulse() PulseAll(), .
Pulse() , ,
. PulseAll()
.
Wait():
public static bool Wait(object waitOb)
public static bool Wait(object waitOb, int milliseconds)
.
, .
waitOb , .
Pulse() PulseAll() :
public static void Pulse(object waitOb)
public static void PulseAll(object waitOb)
waitOb , .
Wait(), Pulse() PulseAll() , lock, SynchronizationLockException.
Wait() Pulse()
Wait() Pulse(),
,
. TickTock, : tick()
tock(). tick() , tock() .
,
tick(), tock().
,
-, .. , .
// Wait() Pulse()
// .
using System;
using System.Threading;
class TickTock {
public void tick(bool running) {
lock(this) {
if(!running) { // .
Monitor.Pulse(this);
//
// .
return;
}
Console.Write("");
Monitor.Pulse(this);
Monitor.Wait(this);
}
//
//
//
//
tock().
tock().
21.
595
class MyThread {
public Thread thrd;
TickTock ttOb;
// .
public MyThread(string name, TickTock tt) {
thrd = new Thread(new ThreadStart(this.run));
ttOb = tt;
thrd.Name = name;
thrd.Start();
}
// .
void run() {
if(thrd.Name == "") {
for(int i=0; i<5; i++) ttOb.tick(true);
ttOb.tick(false);
} else {
for(int i=0; i<5; i++) ttOb.tock(true);
ttOb.tock(false);
}
}
class TickingClock {
public static void Main() {
TickTock tt = new TickTock();
MyThread mt1 = new MyThread("", tt);
MyThread mt2 = new MyThread("", tt);
596
mt1.thrd.Join();
mt2.thrd.Join();
Console.WriteLine(" ");
:
II. C#
. Main()
TickTock tt, .
run() MyThread .
, tick(),
tock().
true. ,
true. (
false) .
tick() tock().
tick(), :
public void tick(bool running) {
lock(this) {
if(!running) { // .
Monitor.Pulse(this); //
// .
return;
}
Console.Write(" ");
Monitor.Pulse(this);
Monitor.Wait(this);
}
//
//
//
//
tock().
tock().
, tick()
lock-. , Wait() Pulse()
. running.
. false,
. Pulse(),
. , ,
() , ,
Pulse() Wait().
Pulse()
. Wait() tick() ,
Pulse(). ,
tick() ,
, .
tock() tick(), ,
. , ,
Pulse(), Wait(). ,
tick() tock(), ,
, tick() ... ,
.
Pulse() ,
Wait(). ,
21.
597
tick() tock()
Wait(). ,
. ,
Pulse() .
Pulse() , .
,
<CTRL + C>. , Wait()
tock()
Pulse(), tock() .
( tock()) .
-
Wait() Pulse() ,
, TickTock
. Wait() Pulse().
// TickTock.
class TickTock {
public void tick(bool running) {
lock(this) {
if(!running) { // .
return;
}
Console.Write(" ");
Console.WriteLine("");
TickTock
:
, tick() tock()
!
,
, .
(deadlock) ,
598
II. C#
, .
, , , .
,
, !
, , . ,
.
TickTock. , Pulse()
tick() tock(), (.. tock() tick())
, .
, ,
. ,
. ,
,
.
MethodImplAttribute
MethodImplAttribute,
. lock ,
MethodImplAttribute
System.Runtime.CompilerServices.
,
, :
public MethodImplAttribute(MethodImplOptions opt)
opt .
MethodImplOptions.Synchronized.
.
TickTock,
MethodImplAttribute:
// MethodImplAttribute
// .
using System;
using System.Threading;
using System.Runtime.CompilerServices;
class TickTock {
/*
tick() . */
[MethodImplAttribute(MethodImplOptions.Synchronized)]
public void tick(bool running) {
if(!running) { // .
Monitor.Pulse(this); //
// .
return;
}
Console.Write(" ");
Monitor.Pulse(this);
//
21.
599
Monitor.Wait(this);
// tock().
// ,
// 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;
// .
public MyThread(string name, TickTock tt) {
thrd = new Thread(new ThreadStart(this.run));
ttOb = tt;
thrd.Name = name;
thrd.Start();
}
// .
void run() {
if(thrd.Name == "") {
for(int i=0; i<5; i++) ttOb.tick(true);
ttOb.tick(false);
} else {
for(int i=0; i<5; i++) ttOb.tock(true);
ttOb.tock(false);
}
}
class TickingClock {
public static void Main() {
TickTock tt = new TickTock();
MyThread mt1 = new MyThread("", tt);
MyThread mt2 = new MyThread("", tt);
600
II. C#
mt1.thrd.Join();
mt2.thrd.Join();
Console.WriteLine(" .");
TickTock
( ).
lock-
MethodImplAttribute . .
lock C#,
.
,
. ,
.
, . ,
, .
.
.
, ,
.
Thread.Suspend(),
Thread.Resume().
:
public void Suspend()
public void Resume()
, ThreadStateException.
, , , .
, Thread.Abort().
:
public void Abort()
Abort() ThreadAbortException
, . .
, (
). ,
Abort() , ,
, ,
Abort() Join(). (
) Abort() .
, finally- .
,
:
//, .
using System;
using System.Threading;
21.
601
class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// .
void run() {
Console.WriteLine(thrd.Name + " .");
for(int i = 1; i <= 1000; i++) {
Console.Write(i + " ");
if((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
}
}
Console.WriteLine(thrd.Name + " .");
}
class SuspendResumeStop {
public static void Main() {
MyThread mt1 = new MyThread(" ");
Thread.Sleep(1000);
//
// .
mt1.thrd.Suspend();
Console.WriteLine(" .");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine(" .");
Thread.Sleep(1000);
mt1.thrd.Suspend();
Console.WriteLine(" .");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine(" .");
Thread.Sleep(1000);
Console.WriteLine(" .");
mt1.thrd.Abort();
602
mt1.thrd.Join(); // .
Console.WriteLine(" .");
II. C#
:
.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
.
41 42 43 44 45 46 47 48 49 50
.
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
.
81 82 83 84 85 86 87 88 89 90
.
91 92 93 94 95 96 97 98 99 100
101 102 103 104 105 106 107 108 109 110
111 112 113 114 115 116 117 118 119 120
.
.
Abort()
Abort():
public void Abort(object info)
info ,
. ExceptionState
ThreadAbortException.
, :
// Abort(object).
using System;
using System.Threading;
class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
// .
void run() {
try {
Console.WriteLine(thrd.Name + " .");
for(int i = 1; i <= 1000; i++) {
Console.Write(i + " ");
if((i%10)==0) {
Console.WriteLine(); Thread.Sleep(250);
}
}
Console.WriteLine(thrd.Name +
" .");
21.
603
} catch(ThreadAbortException exc) {
Console.WriteLine(
" , = " +
exc.ExceptionState);
class UseAltAbort {
public static void Main() {
MyThread mt1 = new MyThread(" ");
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
.
41 42 43 44 45 46 47 48 49 50
, = 100
.
, Abort()
100. ExceptionState
ThreadAbortException,
.
Abort()
.
ThreadAbortException,
ResetAbort().
. ResetAbort() :
public static void ResetAbort()
ResetAbort() ,
, .
ResetAbort() :
// ResetAbort().
using System;
using System.Threading;
class MyThread {
public Thread thrd;
604
II. C#
// .
void run() {
Console.WriteLine(thrd.Name + " .");
for(int i = 1; i <= 1000; i++) {
try {
Console.Write(i + " ");
if((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
}
} catch(ThreadAbortException exc) {
if((int)exc.ExceptionState ==0) {
Console.WriteLine(
" ! = " +
exc.ExceptionState);
Thread.ResetAbort();
} else
Console.WriteLine(
" , = " +
exc.ExceptionState);
}
}
Console.WriteLine(thrd.Name + " .");
}
class ResetAbort {
public static void Main() {
MyThread 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(" .");
21.
605
:
.
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
.
! = 0
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
.
, = 100
.
, , Abort() ,
, ResetAbort()
, .
.
ThreadState,
Thread:
public Thread ThreadState{ get; }
,
ThreadState. :
ThreadState.Aborted
ThreadState.AbortRequested
ThreadState.Background
ThreadState.Running
ThreadState.Stopped
ThreadState.StopRequested
ThreadState.Suspended
ThreadState.SuspendRequested
ThreadState.Unstarted
ThreadState.WaitSleepJoin
. ,
ThreadState.WaitSleepJoin, ,
Wait(), Sleep() Join().
, C#-
, ,
.
.
,
Thread, .
CurrentThread, Thread.
:
public static Thread CurrentThread{ get; }
, .
,
606
II. C#
CurrentThread, . ,
, .
, ,
, :
// .
using System;
using System.Threading;
class UseMain {
public static void Main() {
Thread thrd;
// .
thrd = Thread.CurrentThread;
// .
if(thrd.Name == null)
Console.WriteLine(" .");
else
Console.WriteLine(" : " + thrd.Name);
// .
Console.WriteLine(": " + thrd.Priority);
Console.WriteLine();
// .
Console.WriteLine(" .\n");
thrd.Name = " ";
thrd.Priority = ThreadPriority.AboveNormal;
Console.WriteLine(
" : " +
thrd.Name);
Console.WriteLine(" : " +
thrd.Priority);
:
. : Normal
.
:
: AboveNormal
:
. , Join()
thrd.Join();
Main(), ,
, !
21.
607
( ). ,
,
. ,
. :
.
,
!
C# - ,
- . ,
, ,
. C# Process,
System.Diagnostics.
Start(), Process. :
public static Process Start(string name)
name ,
.
Close(),
, . Close() :
public void Close()
. GUI, Windows,
CloseMainWindow(),
:
public bool CloseMainWindow()
, .
true, .
false, GUI-
. , CloseMainWindow()
. , .
Kill():
public void Kill()
Kill() .
. ,
, , , .
WaitForExit().
:
public void WaitForExit()
public bool WaitForExit(int milliseconds)
608
II. C#
, ,
. WaitForExit(),
, true,
, false, .
.
Windows WordPad.exe.
// .
using System;
using System.Diagnostics;
class StartProcess {
public static void Main() {
Process newProc = Process.Start("wordpad.exe");
Console.WriteLine(" .");
newProc.WaitForExit();
newProc.Close(); // .
Console.WriteLine(" .");
WordPad,
. ,
WordPad.
WordPad .
21.
609
22
C# .
System.Collections ,
.
, ,
.
, , , , . C#-.
,
.
. ,
ArrayList, Hashtable, Stack Queue, .
,
.
.NET Framework :
, .
,
, . ,
/.
object, .
. ,
,
.
, ,
. ,
. , BitArray ,
.
(), IEnumerator IEnumerable.
.
IEnumerable,
, IEnumerator. ,
,
, .
,
, foreach.
. C++-,
, C#-
(Standard Template Library STL), C++. ,
C++ , C# . Java.
Java- Collections Framework,
C#-.
22.
611
System.Collections .
, ,
. , ,
. 22.1.
.
ICollection
ICollection ,
. ,
. IEnumerable.
ICollection, .
ICollection :
true, ,
false
,
object SyncRoot
{ get; }
Count ,
, . Count ,
, . ICollection :
void CopyTo(Array target, int startIdx)
CopyTo() ,
target, , startIdx. ,
CopyTo() C#-.
ICollection IEnumerable,
GetEnumerator():
IEnumerator GetEnumerator()
.
22.1.
ICollection
IEnumerable
,
GetEnumerator(),
,
,
, /
IEnumerator
IList
IDictionary
612
II. C#
. 22.1
IDictionaryEnumerator
,
IDictionary
Compare(),
,
-
IComparer
IHashCodeProvider
IList
IList ICollection
, .
, ICollection, IList
( . 22.2).
.
,
NotSupportedException.
22.2. , IList
int Add(
object obj)
void Clear()
bool Contains(
object obj)
obj .
,
true,
, obj,
false
obj, ()
. obj ,
-1
obj ,
idx. ,
idx , ,
obj
obj
. ,
, ,
"
,
, idx. ,
,
, ""
int IndexOf(
object obj)
void Insert(
int idx,
object obj)
void Remove(
object obj)
void RemoveAt(
int idx)
IList Add().
, Add() object.
object ,
. ( ),
(boxing).
Remove()
RemoveAt(). Remove() , RemoveAt()
, .
Clear().
22.
613
, ,
Contains(). IndexOf(),
Insert().
IList :
bool IsFixedSize { get; }
bool IsReadOnly { get; }
, IsFixedSize
true. ,
. , IsReadOnly
true. , .
IList :
object this[int idx] { get; set; }
. .
Add(). ,
.
IDictionary
IDictionary ,
. ,
. , ,
IDictionary, /.
.
IDictionary ICollection. ,
IDictionary, . 22.3.
NotSupportedException.
22.3. , IDictionary
void Add(
object k,
object v)
/,
k v. k .
, k ,
ArgumentException
/
true,
k .
false
void Clear()
bool Contains(
object k)
IDictionaryEnumerator
GetEnumerator()
void Remove(
object k)
, k
/ IDictionary-,
Add(). ,
. - ,
Remove() .
Clear().
614
II. C#
, ,
Contains(), .
GetEnumerator() , IDictionary.
"" (/) .
IDictionary :
true,
true,
, Keys Values ,
, .
IDictionary :
object this[object key] { get; set; }
. .
, ,
.
IComparer
IComparer Compare(),
:
int Compare(object v1, object v2)
22.
615
Compare() , v1
v2, , v1 v2, ,
.
.
IHashCodeProvider
IHashCodeProvider ,
GetHashCode().
, ( -)
Object.GetHashCode(), .
IHashCodeProvider .
DictionaryEntry
System.Collections
DictionaryEntry. , /,
DictionaryEntry.
:
public object Key { get; set; }
public object Value { get; set; }
. DictionaryEntry
:
public DictionaryEntry(object k, object v)
k , v .
, ,
, . ,
: ,
.
.
.
. .
, :
ArrayList
, ..
- /
, , :
/
, , :
Hashtable
Queue
SortedList
Stack
616
II. C#
ArrayList
ArrayList ,
. C#
,
. , ,
. ,
. ArrayList.
ArrayList ,
. ArrayList
.
. .
ArrayList, , , .
ArrayList ICollection, IList, IEnumerable
ICloneable. ArrayList :
public ArrayList()
public ArrayList(ICollection )
public ArrayList(int capacity)
ArrayList-
, 16 . ,
, .
. (
) .
ArrayList- , ,
, .
, ,
ArrayList, .
. 22.4. ArrayList
Sort().
, BinarySearch().
ArrayList- , Reverse().
ArrayList ,
. , InsertRange(),
ArrayList- . RemoveRange()
.
,
SetRange(). ,
. .
ArrayList .
Synchronized().
22.4. ArrayList
,
v.
. ,
.
22.
617
. 22.4
,
v, ,
comp. .
,
.
,
v, ,
comp. ,
startIdx, count
. .
,
.
,
, startIdx, ,
ar.
count ,
, srcIdx, ,
ar, ,
destIdx.
ArrayList.
idx
count .
,
ar ArrayList-
618
, ,
, ,
startIdx
v
. ,
-1
ar ArrayList-,
,
count ,
, idx
count
, startIdx
,
startIdx, ,
, comp. comp
,
II. C#
. 22.4
, comp.
startIdx
endIdx. comp ,
,
,
.
type
Capacity
Count
, , ArrayList,
Capacity:
public virtual int Capacity { get; set; }
Capacity
ArrayList.
, ArrayList- .
, ArrayList- ,
. ,
ArrayList-,
Capacity . ,
.
, ArrayList-,
Capacity .
Count. ,
Count, ICollection,
, .
Capacity , Count,
ArgumentOutOfRangeException.
ArrayList- ,
, Capacity Count.
, TrimToSize().
ArrayList
. ArrayList-,
. .
.
.
// ArrayList-.
using System;
using System.Collections;
class ArrayListDemo {
public static void Main() {
22.
619
// .
ArrayList al = new ArrayList();
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" : " +
al.Count);
Console.WriteLine();
Console.WriteLine(" 6 .");
// .
al.Add('');
al.Add('A');
al.Add('E');
al.Add('B');
al.Add('D');
al.Add('F');
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" : " +
al.Count);
// , .
Console.Write(" : ");
for(int i=0; i < al.Count; i++)
Console.Write(al[i] + " ");
Console.WriteLine("\n");
Console.WriteLine(" 2 .");
// .
al.Remove('F');
al.Remove('A');
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(" : " +
al.Count);
// foreach.
Console.Write(": ");
foreach(char c in al)
Console.Write(c + " ");
Console.WriteLine("\n");
Console.WriteLine(" 20 .");
// ,
// .
for(int i=0; i < 20; i++)
al.Add((char)('a' + i));
Console.WriteLine(" : " +
al.Capacity);
Console.WriteLine(
" 20 : " +
al.Count);
Console.Write(": ");
foreach(char c in al)
620
II. C#
:
: 16
: 0
6 .
: 16
: 6
: D F
2 .
: 16
: 4
: D
20 .
: 32
20 : 24
: C E B D a b c d e f g h i j k l m n o p q r s t
.
: X Y Z D a b c d e f g h i j k l m n o p q r s t
,
, 16. ,
, , .
ArrayList-
ArrayList
Sort(). ,
BinarySearch().
:
// ArrayList-
// .
using System;
using System.Collections;
class SortSearchDemo {
public static void Main() {
// .
ArrayList al = new ArrayList();
22.
621
// .
al.Add(55);
al.Add(43);
al.Add(-4);
al.Add(88);
al.Add(3);
al.Add(19);
Console.Write(" : ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
// .
al.Sort();
// foreach
// .
Console.Write(" : ");
foreach(int i in al)
Console.Write(i + " ");
Console.WriteLine("\n");
Console.WriteLine(" 4 3 " +
al.BinarySearch(43));
:
: 55 43 -4 88 3 19
: -4 3 19 43 55 88
4 3 3
ArrayList-
, ,
. ,
, .
(, , ,
.
.)
ArrayList- ,
.
ToArray(). . -,
. -,
, ,
. ArrayList-
, , :
// ArrayList- .
using System;
using System.Collections;
622
II. C#
class ArrayListToArray {
public 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();
// .
int[] ia = (int[]) al.ToArray(typeof(int));
int sum = 0;
// .
for(int i=0; i<ia.Length; i++)
sum += ia[i];
Console.WriteLine(" : " + sum);
:
: 1 2 3 4 : 10
.
ToArray(), int.
.
, ToArray(), Array,
int[], ,
.
Hashtable
Hashtable ,
-. , , -
, (hashing).
, ,
-,
. - ,
, . -
, .. - .
,
, , , .
Hashtable IDictionary, ICollection, IEnumerable,
ISerializable, IDeserializationCallback ICloneable.
Hashtable ,
( ):
public Hashtable()
public Hashtable(IDictionary )
22.
623
true, Hashtabie , k.
fls
true, Hashtable , v.
false
Hashtable-
IDictionaryEnumerator
Hashtable-, ht
Hashtable, ,
, public-.
, Hashtable- :
public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
Hashtable
,
. Hashtable protected-
Hcp Comparer, .
Hashtable /
DictionaryEntry, ,
. ,
Hashtable- Add(),
: .
624
II. C#
, Hashtable-
. ,
.
, Hashtable-:
// Hashtable-.
using System;
using System.Collections;
class HashtableDemo {
public static void Main() { // -.
Hashtable ht = new Hashtable();
// -.
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
ht.Add("", " ");
// .
ht[""] = " ";
// .
ICollection c = ht.Keys;
// .
foreach(string str in c)
Console.WriteLine(str + ": " + ht[str]);
:
:
:
:
:
:
, /
. ,
- ht. -,
Keys. - ht,
, .
, , IDictionary
Hashtable, .
SortedList
SortedList ,
/ , .
SortedList IDictionary, ICollection, IEnumerable
ICloneable.
SortedList , :
22.
625
public SortedList()
public SortedList(IDictionary c)
public SortedList(int capacity)
public SortedList(IComparer comp)
,
16 . SortedList-,
, .
SortedList-,
, capacity. ,
, .
,
.
, 16 .
SortedList- ,
, . ,
, .
SortedList- ,
. ,
, , .
SortedList ,
, .
. 22.6. , SortedList- ,
ContainsKey(). ,
, ContainsValue().
SortedList-
IDictionaryEnumerator, GetEnumerator(). ,
, /,
IDictionaryEnumerator. SortedList Synchronized().
22.6. , SortedList
true, SortedList , k.
false
true, SortedList , v.
false
, idx
626
IDictionaryEnumerator
SortedList-
, idx
IList- ,
SortedList-
IList- ,
SortedList-
II. C#
. 22.6
, k.
-1,
,
v. -1,
,
idx, , v
SortedList, sl
Capacity
Count
.
, ,
GetByIndex(), , ,
SetByIndex(). , ,
GetKey(). GetKeyList(),
GetValueList().
IndexOfKey(),
IndexOfValue(). SortedList ,
IDictionary,
, .
SortedList ,
, .
, SortedList-,
:
public virtual ICollection Keys { get; }
public virtual ICollection Values { get; }
SortedList-.
Hashtable-, SortedList- /
DitionaryEntry, ,
SortedList,
.
SortedList
,
, Hashtable-.
, , SortedList .
// SortedList-.
using System;
using System.Collections;
class SLDemo {
public static void Main() {
// SortedList.
SortedList sl = new SortedList();
22.
627
// .
sl.Add("", " ");
sl.Add("", " ");
sl.Add("", " ");
sl.Add("", " ");
// .
sl[""] = " ";
// .
ICollection c = sl.Keys;
// .
Console.WriteLine(
" , " +
".");
foreach(string str in c)
Console.WriteLine(str + ": " + sl[str]);
Console.WriteLine();
// , .
Console.WriteLine(
" , " +
" .");
for(int i=0; i<sl.Count; i++)
Console.WriteLine(sl.GetByIndex(i));
Console.WriteLine();
// .
Console.WriteLine(
" .");
foreach(string str in c)
Console.WriteLine(str + ": " + sl.IndexOfKey(str));
:
, .
:
:
:
:
:
, .
.
: 0
: 1
: 2
: 3
: 4
628
II. C#
Stack
, , ,
(last-in, first-out LIFO). , ,
. , ,
, .. .
.
,
( ,
).
, , Stack.
ICollection, IEnumerable ICloneable.
, ,
, , ,
.
Stack :
public Stack()
public Stack(int capacity)
public Stack(ICollection c)
,
10 . ,
capacity. ,
, .
, , Stack,
, . 22.7.
, ,
, Push(). ,
Pop(). Pop() ,
, InvalidOperationException. Peek()
, .
22.7. , Stack
true, v
.
false
Count ,
, ,
, ,
v
Stack-,
stk
,
:
Integer, .
22.
629
// 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();
foreach(int i in st)
Console.Write(i + " ");
Console.WriteLine();
try {
showPop(st);
} catch(InvalidOperationException) {
Console.WriteLine(" .");
}
. ,
InvalidOperationException),
( ).
630
II. C#
: Push(22)
: 22
: Push(65)
: 65 22
: Push(91)
: 91 65 22
: Pop ->
: 65 22
: Pop ->
: 22
: Pop ->
:
: Pop ->
91
65
22
.
Queue
.
(first-in, first-out FIFO). , ,
, .
? , , ,
, .
,
( ) , Internet.
.
, , Queue.
ICollection, IEnumerable ICloneable.
, ,
, , ,
,
2,0.
Queue :
public Queue()
public Queue(int capacity)
public Queue(int capacity, float growFact)
public Queue(ICollection c)
, 32 , 2,0.
, capacity,
2,0. ,
growFact. ,
, .
, , Queue,
, . 22.8.
.
, Enqueue().
, Dequeue(). Dequeue() ,
InvalidOperationException. () ,
.
22.
631
22.8. , Queue
true, v
.
false
Count ,
,
v
,
,
q
,
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();
Console.WriteLine();
632
II. C#
:
: Enqueue(22)
: 22
: Enqueue(65)
: 22 65
: Enqueue(91)
: 22 65 91
: Dequeue ->
: 65 91
: Dequeue ->
: 91
: Dequeue ->
:
: Dequeue ->
22
65
91
.
BitArray
BitArray .
, ,
. BitArray
ICollection,
IEnumerable ICloneable.
BitArray . , BitArray , :
public BitArray(bool[] bits)
bits BitArray. bits.
, bits .
BitArray- .
:
public BitArray(byte[] bits)
, bits,
bits[0] , bits[l]
22.
633
.. BitArray-
int-, :
public BitArray(int[] bits)
bits[0] 32 , bits[l]
32 ..
BitArray-
:
public BitArray(int size)
size ,
false.
,
:
public BitArray(int size, bool v)
,
v.
, BitArray- .
public BitArray(BitArray bits)
,
bits, .
BitArray- .
, .
BitArray ,
, (. . 22.9).
, BitArray Synchronized(). ,
,
IsSynchronized false.
BitArray- ,
SyncRoot.
22.9. , BitArray
()
, ba. BitArray,
,
idx
()
BitArray-,
()
, ba. BitArray,
, idx,
v
634
v
, ba. BitArray,
II. C#
BitArray ,
, Length:
public int Length { get; set; }
Length
. , Length ,
Count, . Count
, Length. ,
Length BitArray-.
, .
BitArray- , ,
false.
BitArray :
object this[int idx] { get; set; }
.
, BitArray-:
// BitArray.
using System;
using System.Collections;
class BADemo {
public static void showbits(string rem,
BitArray bits) {
Console.WriteLine(rem);
:
ba:
False False False False False False False False
22.
635
ba Not():
True True True True True True True True
ba2:
True True False False False False True False
ba XOR ba2:
False False True True True True False True
.NET Framework
,
(
System.Collections.Specialized)
Coiiectionsutii
,
,
/ ListDictionary
Hashtable
, /
/,
, string
,
-
/, ,
string
HybridDictionary
ListDictionary
NameValueCollection
StringCollection
StringDictionary
System.Collections
, CollectionBase, ReadOnlyCollectionBase DictionaryBase,
,
foreach,
, IEnumerator
IEnumerator Current
object Current { get; }
636
II. C#
Current ,
. Current ,
,
.
IEnumerator . , MoveNext(),
:
bool MoveNext()
MoveNext()
. true,
, false,
. MoveNext()
Current .
Reset():
void Reset()
Reset() ,
MoveNext().
,
. GetEnumerator(),
, .
, .
, :
1. ( ),
GetEnumerator().
2. , MoveNext(). ,
, MoveNext()
true.
3.
Current.
ArrayList,
.
// .
using System;
using System.Collections;
class EnumeratorDemo {
public static void Main() {
ArrayList list = new ArrayList(1);
for(int i=0; i < 10; i++)
list.Add(i);
// .
IEnumerator etr = list.GetEnumerator();
while(etr.MoveNext())
Console.Write(etr.Current + " ");
22.
637
Console.WriteLine();
// .
etr.Reset();
while(etr.MoveNext())
Console.Write(etr.Current + " ");
Console.WriteLine();
:
0123456789 0123456789
, ,
foreach , .
.
IDictionaryEnumerator
, 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().
, MoveNext() false.
IDictionaryEnumerator Hashtable:
//
// IDictionaryEnumerator.
using System;
using System.Collections;
class IDicEnumDemo {
public static void Main() {
// -.
638
II. C#
// .
IDictionaryEnumerator etr = ht.GetEnumerator();
Console.WriteLine(
" Entry.");
while(etr.MoveNext())
Console.WriteLine(etr.Entry.Key + ": " + etr.Entry.Value);
Console.WriteLine();
Console.WriteLine(" " +
" Key Value.");
etr.Reset();
while(etr.MoveNext())
Console.WriteLine(etr.Key + ": " + etr.Value);
:
Entry.
: 555-3456
: 555-9876
: 555-3452
: 555-7756
Key Value.
: 555-3456
: 555-9876
: 555-3452
: 555-7756
, int, string char. ,
. .
, , ,
. , , ,
, Inventory,
ArrayList.
// .
using System;
22.
639
using System.Collections;
class Inventory {
string name;
double cost;
int onhand;
class InventoryList {
public static void Main() {
ArrayList inv = new ArrayList();
// .
inv.Add(new Inventory("", 5.95, 3));
inv.Add(new Inventory(" ", 8.29, 2));
inv.Add(new Inventory("", 3.50, 4));
inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
:
:
: $5.95 : 3
: $8.29 : 2
: $3.50 : 4
: $19.88 : 8
Inventory
.
object,
.
, , .
, , ,
,
40 , ,
. , ,
,
. ,
.
640
II. C#
,
, , , :
. , ArrayList- ,
Inventory. . -,
Inventory IComparable.
, . -,
, IComparer.
.
IComparable
( ArrayList) ,
(
SortedList), ,
. IComparable.
CompareTo(),
, .
CompareTo() :
int CompareTo(object obj)
CompareTo() ,
obj. ,
( ) , ,
, obj,
, obj.
. CompareTo()
ArgumentException, obj
.
IComparable. inventory,
, IComparable,
Inventory.
// IComparable.
using System;
using System.Collections;
class Inventory : IComparable {
string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-16}: {1,8:C} : {2}",
name, cost, onhand);
}
22.
641
// IComparable.
public int CompareTo(object obj) {
Inventory b;
b = (Inventory) obj;
return name.CompareTo(b.name);
}
class IComparableDemo {
public static void Main() {
ArrayList inv = new ArrayList();
// .
inv.Add(new Inventory("", 5.95, 3));
inv.Add(new Inventory(" ", 8.29, 2));
inv.Add(new Inventory("", 3.50, 4));
inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i); }
Console.WriteLine();
// .
inv.Sort();
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
( ,
Sort() ):
:
: $5.95
: 3
: $8.29
: 2
: $3.50
: 4
: $19.88
: 8
:
: $8.29
: 2
: $3.50
: 4
: $5.95
: 3
: $19.88
: 8
IComparer
IComparable
( ) , .
IComparer. ,
IComparer,
642
II. C#
, . IComparer
Compare():
int Compare(object obj1, object obj2)
Compare() obj1 obj2.
Compare() ,
, , obj1 obj2,
, obj1 obj2.
.
CompareTo() ArgumentException,
.
IComparer
SortedList, ArrayList.Sort(IComparer),
.
IComparer , ,
IComparable.
.
IComparer. CompInv,
IComparer Inventory.
Sort(), ,
, .
// IComparer.
using System;
using System.Collections;
// CompInv.
// Inventory.
class CompInv : IComparer {
// IComparer.
public int Compare(object obj1, object obj2) {
Inventory a, b;
a = (Inventory) obj1;
b = (Inventory) obj2;
return a.name.CompareTo(b.name);
}
}
class Inventory { public string name;
double cost;
int onhand;
public Inventory(string n, double c, int h) {
name = n;
cost = c;
onhand = h;
}
public override string ToString() {
return
String.Format("{0,-16}: {1,8:} : {2}",
name, cost, onhand);
22.
643
class MailList {
public static void Main() {
CompInv comp = new CompInv();
ArrayList inv = new ArrayList();
// .
inv.Add(new Inventory("", 5.95, 3));
inv.Add(new Inventory(" ", 8.29, 2));
inv.Add(new Inventory("", 3.50, 4));
inv.Add(new Inventory("", 19.88, 8));
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
Console.WriteLine();
// , IComparer.
inv.Sort(comp);
Console.WriteLine(
" :");
foreach(Inventory i in inv) {
Console.WriteLine(" " + i);
}
.
,
.
,
. ,
, .
. ,
SortedList .
.
644
II. C#
23
Internet
C# ,
Internet . ,
C# -
Internet. , C++,
Internet, ,
,
. C# .NET Library
, Internet-.
. ,
System.Net,
, Internet.
, System.Net.Sockets, ,
.
System.Net, ,
.
ASP.NET-
System.Web.
System.Net
System.Net , .
,
, . , ,
System.Net:
AuthenticationManager
CookieCollection
CredentialCache
DnsPermissionAttribute
FileWebRequest
HttpVersion
IPAddress
NetworkCredential
ServicePointManager
SocketFermissionAttribute
WebHeaderCollection
WebProxy
Authorization
CookieContainer
Dns
EndPoint
FileWebResponse
HttpWebRequest
IPEndPoint
ProtocolViolationException
SocketAddress
WebClient
WebPermission
WebRequest
Cookie
CookieException
DnsPermission
EndpointPermission
GlobalProxySelection
HttpWebResponse
IPHostEntry
ServicePoint
SocketPermission
WebException
WebPermissionAttribute
WebResponse
System.Net :
IAuthenticationModule
IWebProxy
ICertificatePolicy
IWebRequestCreate
ICredentials
:
HttpStatusCode
TransportType
646
NetworkAccess
WebExceptionStatus
II. C#
, System.Net :
HttpContinueDelegate.
System.Net ,
Internet-
.
WebRequest WebResponse. ,
. ( ,
.) , ,
HTTP,
HttpWebRequest HttpWebResponse.
HttpWebRequest HttpWebResponse
,
, WebClient. ,
( ) ,
WebClient.
Internet-
(Uniform Resource Identifier URI). URI-
. URI-
(Uniform Resource Locator URL).
System.Net Microsoft
URI, . ,
URI-, Internet-
.
U RI- :
Protocol://ServerID/Filth?Query
Protocol (, HTTP).
ServerID (, Osborne.com
Weather.com). FilePath .
FilePath , ,
ServerID. , Query ,
. Query . C# URI-
Uri, .
Internet-
, System.Net,
Internet -. , -
, . ,
URI- Web-.
, URI-. ,
.
, WebRequest WebResponse,
, Microsoft (pluggable protocols).
23. Internet
647
, .
Internet-
(HyperText Transfer Protocol HTTP).
(File Transfer Protocol FTP). , URI . , URI-,
HTTP://MyWebSite.com, HTTP,
.
, WebRequest WebResponse ,
-, .
, .
RegisterPrefi(), WebRequest.
WebRequest ( ),
URI.
, .
.NET- HTTP. ,
URI- HTTP, HTTP , . ,
HTTP, HttpWebRequest HttpWebResponse.
WebRequest WebResponse, ,
,
HTTP.
System.Net ,
. Internet-
, .
, .
.
, , .
. ,
" ". , , Internet
. ,
, .
Internet , ,
.
, : WebRequest WebResponse,
System.Net.
WebRequest
WebRequest .
, .
, . WebRequest,
, . 23.1,
. 23.2. .
WebRequest public-.
URI-,
( WebRequest), .
Create(), WebRequest.
Create() ,
WebRequest .
648
II. C#
23.1. ,
WebRequest
public static
WebRequest Create(
string uri);
WebRequest- URI-,
, uri.
, URI-.
, ,
WebRequest.
,
NotSupportedException.
URI-,
UriFormatException
WebRequest- URI-,
, uri.
, URI-.
, ,
WebRequest.
,
NotSupportedException
,
URI-
.
WebReponse.
URI.
WebException
public static
WebRequest Create(
Uri uri);
23.2. , WebRequest
.
, Internet-
public virtual
WebHeaderCollection
Headers{ get; set; }
public virtual string
Method { get; set; }
public virtual bool
PreAuthenticate
{ get; set; }
public virtual IWebProxy
Proxy { get; set; }
public virtual Uri
RequestUri { get; }
public virtual int
Timeout { get; set; }
.
,
( ,
)
true,
. false,
URI
proxy-.
, proxy-
URI
,
.
Timeout.Infinite
23. Internet
649
WebResponse
WebResponse ,
. WebResponse .
, .
WebResponse GetResponse(),
WebRequest.
( WebReponse), . ,
WebResponse, . 23.3, .
23.4. .
WebResponse public-.
23.3. , WebResponse
, .
,
GetResponseStream()
, URI.
URI
23.4. , WebResponse
.
-1,
, URI
URI, .
,
URI-
HttpWebRequest HttpWebResponse
HttpWebRequest HttpWebResponse (
WebRequest WebResponse, ) HTTP.
,
HTTP-.
. Internet-
.
Internet WebRequest
WebResponse. ,
, -
Internet-. , ,
.
Internet. , URI-. -
650
II. C#
Web- Osborne.com,
McGraw-Hill,
Web-.
400 , ,
.
// Internet.
using System;
using System.Net;
using System.IO;
class NetDemo {
public static void Main() {
int ch;
// URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// .
Stream istrm = resp.GetResponseStream();
/* html-,
URI. " "
,
400 .
400 , <ENTER>
. */
. ( ,
, Web-, .)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Find all the right computer books and learning tools at
Osborne McGraw-Hill/TITLE>
23. Internet
651
652
II. C#
<Enter>.
. ,
ReadByte(). ,
int-,
char. 1.
, , ,
Close() resp.
. , , .
, Internet
.
.
Web- Osborne.com
HttpWebRequest HttpWebResponse.
HTTP-,
, WebRequest
WebResponse. Create() GetResponse()
:
// WebRequest- URI-.
WebRequest req = WebRequest.Create(
"http://www.osborne.com");
// .
WebResponse resp = req.GetResponse();
Microsoft , ,
,
, WebRequest WebResponse.
, .
HTTP (
HTTP-),
HttpWebRequest HttpWebResponse.
, ,
, ,
.
,
.
Create(), GetResponse() GetResponseStream().
.
, Create()
Create(), WebRequest,
. , URI-, ,
NotSupportedException. URI, UriFormatException.
Create(), ,
ArgumentNullException, ,
.
23. Internet
653
, GetResponse()
, ..
GetResponse(), WebException. ,
, WebException
, : Response Status.
Response
WebResponse.
GetResponse(), . Response
:
public WebResponse Response { get; }
- , , ,
status. :
public WebExceptionStatus Status { get; }
WebExceptionStatus ,
:
ConnectFailure
NameResolutionFailure
ProtocolError
RequestCanceled
ServerProtocolViolation
TrustFailure
ConnectionClosed
Pending
ProxyNameResolutionFailure
SecureChannelFailure
Success
KeepAliveFailure
PipelineFailure
ReceiveFailure
SendFailure
Timeout
, GetResponseStream()
GetResponseStream() GetResponse
ProtocolViolationException, ,
, .
GetResponseStream(), ,
.
IOException.
, ,
:
// .
using System;
using System.Net;
using System.IO;
class NetExcDemo {
public static void Main() {
int ch;
try {
654
II. C#
// WebRequest- URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// .
Stream istrm = resp.GetResponseStream();
/* html-,
URI. " "
,
400 .
400 , <ENTER>
. */
for(int i=1;; i++) {
ch = istrm.ReadByte();
if(ch == -1) break;
Console.Write((char) ch);
if((i%400)==0) {
Console.Write("\n .");
Console.Read();
}
}
}
}
}
}
}
// , .
// istrm.
resp.Close();
catch(WebException exc) {
Console.WriteLine(" : " + exc.Message +
"\n : " + exc.Status);
catch(ProtocolViolationException exc) {
Console.WriteLine(" : " + exc.Message);
catch(UriFormatException exc) {
Console.WriteLine(" URI: " + exc.Message);
catch(NotSupportedException exc) {
Console.WriteLine(" : " + exc.Message);
catch(IOException exc) {
Console.WriteLine("I/O Error: " + exc.Message);
,
Internet-. ,
Create()
WebRequest.Create("http://www.osborne.com/moonrocket");
, ,
:
: The remote server returned an error: (404) Not
Found. : ProtocolError
23. Internet
655
URI
, , . 23.1
WebRequest.Create() .
URI , .
URI Uri. Uri URI-.
Uri, URI-,
Create(). URI- .
Internet- Uri,
.
Uri .
:
public Uri(string uri)
public Uri(string base, string rel)
Uri- URI-,
. Uri- URI, rel, URI-,
base. URI- URI-,
.
Uri , ,
URI- .
.
,
HTTP
30
URI-
. :
// Uri.
using System;
using System.Net;
656
II. C#
class UriDemo {
public static void Main() {
Uri sample = new Uri(
"http://MySite.com/soraefile.txt?SomeQuery");
Console.WriteLine(": " + sample.Host);
Console.WriteLine(": " + sample.Port);
Console.WriteLine(": " + sample.Scheme);
Console.WriteLine(" : " +
sample.LocalPath);
:
: mysite.com
: 80
: http
: /somefile.txt
: ?SomeQuery
: /somefile.txt?SomeQuery
HTTP-
HttpWebResponse,
, , , ,
URI- .
, . 23.5 (
WebResponse). .
23.5. , HttpWebResponse
.
.
, -1
cookie-,
,
URI-
,
23. Internet
657
. 23.5
public Version
Version,
HTTP,
URI-,
. ,
URI-
,
HttpStatusCode,
,
,
ProtocolVersion { get; }
public uri ReponseUri { get; }
Headers, HttpWebResponse,
HTTP-:
public WebHeaderCollection Headers{ get; }
HTTP- /, .
WebHeaderCollection.
, /,
(. 22).
AllKeys. , ,
.
, .
, Web-
Osborne.com:
// Web-.
using System;
using System.Net;
class HeaderDemo {
public static void Main() {
// WebRequest- URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.osborne.com");
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// .
string[] names = resp.Headers.AllKeys;
// /.
Console.WriteLine("{0,-20}{1}\n", "", "");
foreach(string n in names)
Console.WriteLine("{0,-20}{1]", n, resp.Headers[n]);
// , .
658
II. C#
resp.Close();
( ,
Web- Osbome.com , ,
, ):
Date Mon, 14 Jan 2002 17:45:50 GMT
Server Apache/1.3.9 (Unix) PHP/3.0.14
Keep-Alive timeout=30, max=500
Connection Keep-Alive
Transfer-Encoding chunked
Content-Type text/html
cookie-
cookie-, HTTP-,
Cookies, HttpWebResponse. Cookie-,
, /.
Web-.
Cookies:
public CookieCollection Cookies { get; set; }
CookieCollection
ICollection
IEnumerable, (. 22).
, cookie-
.
CookieCollection
Cookie. Cookie ,
cookie-. Name Value:
public string Name { get; set; }
public string Value { get; set; }
, cookie- Name,
Value.
cookie-, ,
cookie-. HttpWebRequest
CookieContainer:
public CookieContainer CookieContainer { get; set; }
CookieContainer , ,
cookie-.
CookieContainer.
CookieCollection, .
CookieContainer cookie-.
cookie-,
URI-, . ,
Web- cookie-, ,
.
/* cookie-.
, cookie-
Web-,
23. Internet
659
.
,
Cookie,
Cookie http://MSN.COM
cookie-,
Web- MSN.COM. */
using System;
using System.Net;
class CookieDemo {
public static void Main(string[] args) {
if(args.Length != 1) {
Console.WriteLine("Usage: CookieDemo <uri>");
return;
}
// WebRequest- URI-.
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create(args[0]);
// cookie-.
req.CookieContainer = new CookieContainer();
// .
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
// cookie-.
Console.WriteLine(" cookie-: " +
resp.Cookies.Count);
Console.WriteLine("40,-20){1}", "", "");
for(int i=0; i < resp.Cookies.Count; i++)
Console.WriteLine("{0, -20}{1}",
resp.Cookies[i].Name, resp.Cookies[i].Value);
// , .
resp.Close();
LastModified
, Web- URI. HttpWebResponse ,
LastModified:
public DateTime LastModified { get; }
LastModified URI-.
Web- Microsoft.com:
660
II. C#
// LastModified.
using System;
using System.Net;
class HeaderDemo {
public static void Main() {
HttpWebRequest req = (HttpWebRequest)
WebRequest.Create("http://www.Microsoft.com");
HttpWebResponse resp = (HttpWebResponse)
req.GetResponse();
Console.WriteLine(
" : " +
resp.LastModified);
resp.Close();
: MiniCrawler
, Internet-
WebRequest WebReponse, Web-.
Web- ( MiniCrawler),
Web- . Web-
. MiniCrawler
. URI-,
- Web-.
, Web- :
, ( ) .
MiniCrawler . -,
, .. ,
href=. . -,
, .. , . ,
. , , Web- .
, . ,
MiniCrawler - ?
C#-
.
, MiniCrawler:
// MiniCrawler: Web-.
using System;
using System.Net;
using System.IO;
class MiniCrawler {
23. Internet
661
// .
static string FindLink(string htmlstr,
ref int startloc) {
int i;
int start, end;
string uri = null;
string lowcasestr = htmlstr.ToLower();
i = lowcasestr.IndexOf("href=\"http", startloc);
if(i != -1) {
start = htmlstr.IndexOf('"', i) + 1;
end = htmlstr.IndexOf('"', start);
uri = htmlstr.Substring(start, end-start);
startloc = end;
}
return uri;
662
II. C#
str = rdr.ReadToEnd();
curloc = 0;
do {
// URI-
// .
link = FindLink(str, ref curloc);
if(link != null) {
Console.WriteLine(" : " + link);
Console.Write(", , ?");
answer = Console.ReadLine();
if(string.Compare(answer, "C", true) == 0) {
uristr = string.Copy(link);
break;
}
else if(string.Compare(
answer, "B", true) == 0) {
break;
} else if(string.Compare(
answer, "", true) == 0) {
Console.WriteLine(" .");
}
} else {
Console.WriteLine(" .");
break;
}
} while(link.Length > 0);
}
}
}
}
}
}
// , .
resp.Close();
} while(uristr != null);
catch(WebException exc) {
Console.WriteLine(" : " + exc.Message +
"\n : " + exc.Status);
catch(ProtocolViolationException exc) {
Console.WriteLine(" : " + exc.Message);
catch(UriFormatException exc) {
Console.WriteLine(" URI: " + exc.Message);
catch(NotSupportedException exc) {
Console.WriteLine(" : " + exc.Message);
catch(IOException exc) {
Console.WriteLine("I/O Error: " + exc.Message);
Console.WriteLine(" MiniCrawler.");
MiniCrawler:
23. Internet
663
C:>MiniCrawler http://osborne.com
http://osborne.com
: http://www.osborne.com/aboutus/aboutus.shtml
, , ?
.
:
http://www.osborne.com/downloads/downloads.shtml
, , ?
http://www.osborne.com/downloads/downloads.shtml
, . URI-,
MiniCrawler , . Main() URI uristr. , uristr
null, ,
URI- . , .
GetResponseStream(), ( )
streamReader-. ReadToEnd(),
.
.
FindLink(),
MiniCrawler. FindLink(), ,
, . ,
, htmlstr startloc, .
, startloc ref-. FindLink()
,
href="http, . , URI uri, startloc
. startloc
ref-, Main(),
,
. FindLink() uri.
, , uri null, ,
.
Main() FindLink()
,
. ( <>),
( <>) (
<>). <>,
.
.
, .
, MiniCrawler.
, Web-,
, . ,
- Web- , ,
. ( )
.. , Web- ,
, ( )
.
664
II. C#
, URI- URI-
. Stack.
: .
WebClient
WebClient.
, ( ) ,
WebRequest WebResponse WebClient.
WebClient , ,
.
WebClient :
public WebClient()
(. . 23.6) (.
. 23.7). UriFormatException,
URI- , WebException,
.
23.6. , WebClient
URI,
null-.
, ,
WebClient,
.
null
,
/,
. URI "?".
,
"@"
public ICredentials
Credentials { get; set; }
public WebHeaderCollection
Headers{ get; set;}
public NameValueCollection
QueryString { get; set;}
public WebHeaderCollection
ResponseHeaders{ get;}
23.7. , WebClient
Web-, URI-
uri.
Web-, URI-
uri,
, fname
,
URI-,
uri.
23. Internet
665
. 23.7
,
URI-,
uri.
,
URI-,
uri.
. ,
how,
, info,
URI-, uri.
, info,
URI-, uri.
. , how,
fname, URI-,
uri.
,
fname, URI-,
uri. . ,
how,
, ,
vals, URI-,
uri.
, ,
vals, URI-,
uri. ,
how,
WebClient
:
// WebClient
// .
using System;
using System.Net;
using System.IO;
class WebClientDemo {
public static void Main() {
WebClient user = new WebClient();
string uri = "http://www.osborne.com";
string fname = "data.txt";
try {
Console.WriteLine(
" Web- " + uri +
" " + fname);
user.DownloadFile(uri, fname);
666
II. C#
} catch(WebException exc) {
Console.WriteLine(exc);
} catch(UriFormatException exc) {
Console.WriteLine(exc);
}
Console.WriteLine(" .");
Web- Osborne.com
data.txt. ,
, ,
.
URI-:
, uri.
WebReguest WebResponse
, ,
WebClient,
. ,
Web-. , WebClient
.
23. Internet
667
III
C#
III C#-.
. C#
, ,
,
C#.
Windows ,
System.Windows.Forms. ,
:
.
24
C#
,
. -
C#, -
(component-oriented language). C# .NET Framework
,
.
, COM- (Component
Object Model ) ,
. C#- .
. ,
.
. .
. ,
. ,
. ,
, ,
. ,
, .
, , (client). ,
.
. .
.
, ,
.
, .
. ,
.
public-. , ,
, .
, ( ) .
, .
, , ,
. ,
, (component model).
.
,
, -
24.
671
,
. ,
. - ( )
( ) .
,
.
, .
C# .NET Framework COM. COM Windows
C++.
, C# .NET Framework. , COM . , C#
.NET Framework . ,
COM-,
C#.
C#-
C#,
. , ,
( ) .
, ? : .
, , .NET
Framework. , :
System.ComponentModel.IComponent.
IComponent ,
.NET Framework.
IComponent,
System.ComponentModel.Component. Component
IComponent. ,
. ,
Component,
IComponent, .
, C# " "
.
C#- : .
. ,
.
. .
C#- COM-
C#- , COM-.
, COM, , COM-
( ),
, . ,
,
672
III. C#
AddRef().
Release(). ,
. , C#- . C#
, ,
.
IComponent Component
, .
IComponent
IComponent ,
. IComponent
. site:
ISite Site { get; set; }
Site .
. null-, .
, IComponent, Disposed
:
event EventHandler Disposed
, ,
Disposed.
IComponent System.IDisposable,
Dispose():
void Dispose()
, .
Component
IComponent, , Component,
IComponent .
.
Component, , ,
.NET- .
Component .
Component ,
.
Component .
, Container, :
public IContainer Container { get; }
Container ,
. , null.
, Container , .
, Site, IComponent.
Component :
public virtual ISite Site {get; set; }
24.
673
Site ISite,
. null, .
Site , .
Component .
ToString(). , Dispose(),
. :
public void Dispose()
Dispose(), , ,
. Dispose(),
IDisposable.
Dispose().
Dispose():
protected virtual public void Dispose(bool how)
how true,
, , .
how false, .
Dispose() (protected), .
. ,
Dispose() Dispose(bool).
, ,
Dispose(bool), , .
,
Dispose(bool), Component.
Component MarshalByRefObject,
, ,
, .
( ) ,
. ,
,
MarshalByRefObject . , C# .
,
CipherComp,
. ,
. .
, Encode(),
. ,
Decode(), .
, ( ).
// -.
// CipherLib.cs.
using System.ComponentModel;
namespace CipherLib {
674
//
// .
III. C#
// , CipherComp
// Component.
public class CipherComp : Component {
// .
public string Encode(string msg) {
string temp = "";
for(int i=0; i < msg.Length; i++)
temp += (char) (msg[i] + 1);
return temp;
}
// .
public string Decode(string msg) {
string temp = "";
for(int i=0; i < msg.Length; i++)
temp += (char) (msg[i] - 1);
return temp;
}
, . ,
, CipherLib.cs.
, Visual Studio IDE.
System.ComponentModel.
,
.
CipherComp CipherLib.
.
,
.
CipherComp Component. ,
CipherComp , .NET-
. CipherComp ,
.
.
, CipherComp
. , .
Encode() Decode(). CipherComp
, Dispose(bool). ,
Encode() Decode() ,
, CipherComp.
CipherLib
dll-, exe-.
Visual Studio IDE, CipherLib
(Class Library project).
,
24.
675
/t:library. , CipherLib,
:
csc /t:library CipherLib.es
CipherLib.dll,
CipherComp.
, CipherComp
. ,
CipherComp,
.
// , CipherComp.
using System;
using CipherLib; //
// CipherComp..
class CipherCompClient {
public static void Main() {
CipherComp cc = new CipherComp();
string text = " ";
string ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext);
, CipherLib.
CipherComp .
CipherComp,
.
CipherComp .
Dispose() .
, Dispose() ,
. , C#,
, .
Dispose() .
, ,
, . CipherComp ,
Dispose() . Dispose()
,
.
-,
, CipherLib.dll.
/r. , client
:
csc /r:CipherLib.dll client.es
676
III. C#
Dispose()
CipherComp , .
Dispose(bool).
, Dispose(bool) ,
. ,
.
,
,
. ,
. ,
, - . ,
, , , ,
,
, ,
. ,
,
. :
Dispose(bool).
Dispose(bool)
.
1. Dispose(bool) true
, .
false
, .
2. Dispose(bool) ,
.
3. Dispose(bool) Dispose(bool),
.
4.
, ,
Dispose(false).
2,
. private-,
.
,
Dispose(bool).
// ,
// Dispose(bool).
class MyComp : Component {
bool isDisposed; // true,
public MyComp {
24.
677
Dispose()
Dispose(bool), ,
.
Dispose(bool)
Dispose(bool),
CipherComp ,
. ,
Encode() Decode().
CipherComp.
Dispose(bool) ,
. , Dispose(bool),
WriteLine().
// ,
// .
using System;
using System.ComponentModel;
using System.IO;
namespace CipherLib {
// ,
// .
public class CipherComp : Component {
static int useID = 0;
int id; // .
bool isDisposed; // true,
FileStream log;
//
public CipherComp() {
isDisposed = false; // .
try {
678
III. C#
//
~CipherComp() {
Console.WriteLine(" " + id);
Dispose(false);
}
// .
// .
public string Encode(string msg) {
string temp = "";
for(int i=0; i < msg. Length; i++)
temp += (char) (msg[i] + 1);
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;
}
// .
// .
public string Decode(string msg) {
string temp = "";
for(int i=0; i < msg.Length; i++)
temp += (char) (msg[i] -1);
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;
24.
679
isDisposed = true;
// .
base.Dispose(dispAll);
CipherComp.
:
static int useID = 0;
int id; // .
bool isDisposed; // true,
FileStream log;
int-, (static),
CipherComp. useID
,
CipherComp
id
, useID
, isDisposed , .
(log) FileStream,
.
CipherComp:
public CipherComp() {
isDisposed = false; // .
try {
log = new FileStream("CipherLog" + useID,
FileMode.Create);
id = useID;
useID++;
} catch {FileNotFoundException exc) {
Console.WriteLine(exc);
log = null;
}
}
isDisposed false,
, CipherComp .
. ,
CipherLog useID.
useID id . ,
CipherComp
, (ID).
, CipherComp ,
,
.
( , ).
, Dispose(bool).
Encode() ,
. log- ,
Encode()
. , Encode()
,
680
III. C#
. Decode() , ,
.
Dispose(bool),
CipherComp. :
protected override void Dispose(bool dispAll) {
Console.WriteLine("Dispose(" + dispAll +
") " + id);
if(!isDisposed) {
if(dispAll) {
Console.WriteLine(" " +
" " + id);
log.Close(); // .
isDisposed = true;
}
// .
base.Dispose(dispAll);
, Dispose(bool) protected-.
, .
, Dispose(), Component.
Dispose(bool) isDisposed.
, . isDisposed
false, dispAll.
true, , isDisposed
true. : dispAll true,
. dispAll false,
(
). , Dispose(bool),
( Component).
, . WriteLine()
,
.
CipherComp:
~CipherComp() {
Console.WriteLine(" "
+ id);
Dispose(false);
}
Dispose(bool) false.
: ,
.
.
.
WriteLine() ,
.
, CipherComp,
, .
-, :
// -,
// CipherComp.
24.
681
using System;
using CipherLib;
//
// CipherComp.
class CipherCompClient {
public static void Main() {
CipherComp cc = new CipherComp();
string text = "";
string ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext);
string plaintext = cc.Decode(ciphertext);
Console.WriteLine(plaintext);
text = " - C#.";
ciphertext = cc.Encode(text);
Console.WriteLine(ciphertext);
plaintext = cc.Decode(ciphertext);
Console.WriteLine(plaintext);
cc.Dispose(); // .
:
!.!!!?!D$/
- C#.
Dispose(True) 0
0
CipherLog0
:
!.!!!?!D$/
- C#.
(,
).
, -
Dispose(bool) true. ,
Dispose() CipherComp. ,
Dispose() Dispose(bool) true,
.
Dispose() -,
. :
!.!!!?!D$/
- C#.
0
Dispose(False) 0
Dispose(False) 0
682
III. C#
Dispose() , CipherComp
. , ,
. , ,
, , ,
Dispose(bool) false. Dispose(bool)
Dispose()
Dispose(bool), CipherComp.
Dispose(bool) . , ,
Dispose() , , ,
.
Dispose(bool)
.
CipherComp
, . ,
.
, CipherComp,
Encode(). , :
,
isDisposed. , Encode()
Decode():
// .
// .
public string Encode(string rasg) {
// .
if(isDisposed) {
Console.WriteLine(": .");
return null;
}
string temp = "";
for(int i=0; i < msg.Length; i++)
temp += (char) (msg[i] + 1);
// .
for(int i=0; i < temp.Length; i++)
log.WriteByte((byte) temp[i]);
return temp;
// .
// .
public string Decode(string msg) {
// .
if(isDisposed) {
Console.WriteLine(": .");
return null;
}
24.
683
return temp;
isDisposed, true,
.
.
using
18, using
. Dispose()
. , using
:
using(obj) {
// obj.
}
using(type obj = initializer) {
// obj.
}
obj , using.
using-, .
obj Dispose()
( System.IDisposable). using
, System.IDisposable (,
, ).
-, CipherComp
Dispose()
using:
// using.
using System;
using CipherLib; //
// CipherComp.
class CipherCompClient {
public static void Main() {
// .
using(CipherComp cc = new CipherComp()) {
string text = " using.";
684
III. C#
:
?!vtjoh/
using.
Dispose(True) 0
0
-,
Dispose() . ,
: using Dispose(),
, using .
, .
, .
, . ,
Dispose() ,
.
.
, Container,
System.ComponentModel. Container
:
public Container()
.
Container
Add(), :
public virtual void Add(IComponent comp)
public virtual void Add(IComponent comp,
string compName)
,
comp. ,
comp, , compName.
,
. ,
, ArgumentException.
Site.
, Remove():
public virtual void Remove(IComponent comp)
, :
, comp,
. ,
Remove() comp .
24.
685
Container Dispose().
Dispose() , ,
Dispose(). , , ,
- Dispose().
Container Components:
public virtual ComponentCollection Components { get; }
,
.
, Component Container Site,
.
Container Site ( )
. Container ,
. Site ,
, . Site
ISite. ISite :
true,
CipherComp. ,
.
Site . ,
Dispose(), .
( , using,
Dispose().)
//
// .
using System;
using System.ComponentModel;
using CipherLib; //
// CipherComp.
class UseContainer {
public static void Main(string[] args) {
string str = " .";
Container cont = new Container();
CipherComp cc = new CipherComp();
CipherComp cc2 = new CipherComp();
686
III. C#
cont.Add(cc);
cont.Add(cc2, " ");
Console.WriteLine(" : " + str);
str = cc.Encode(str);
Console.WriteLine(
" : " +
str);
str = cc.Decode(str);
Console.WriteLine(
" : " +
str);
str = ", , ";
Console.WriteLine(" : " + str);
str = cc2.Encode(str);
Console.WriteLine(
" : " +
str);
str = cc2.Decode(str);
Console.WriteLine(
" : " + str);
Console.WriteLine("\n cc2: " + cc2.Site.Name);
Console.WriteLine();
// .
cont.Dispose();
:
: .
: !/
: .
: , ,
: -!-!
: , ,
cc2:
Dispose(True) 1 1
Dispose(True) 0 0
, Dispose()
.
.
24.
687
-
,
. ,
, .
, , ,
. ,
,
.
.
.
-
(), ,
.
. :
,
, .
- .
C# :
?
: !
688
III. C#
25
Windows
, ,
, .. , (
).
C# ,
, , . ,
Windows GUI- (graphics user mterface
), ,
, C# Windows-.
Windows-
,
Windows. , C# .NET Framework
. .NET- ,
Forms, Windows-.
C# System.Windows.Forms Windows-
.
Windows- , .
, .
Windows. , , ,
. , Windows, .
Windows-
C# .NET Framework
Windows-, .
Windows Windows API (Application Programming Interface ),
,
Windows. API-
. API- ,
, , .
, Windows-
.
,
API-. ,
MFC (Microsoft Foundation Classes Microsoft).
C++; MFC- C++.
- MFC
Windows- . MFC-
, .. ,
. , MFC ,
API-, Windows-
-
.
690
III. C#
Windows-,
. Visual Studio
,
Windows-.
, . Visual
Studio ,
. Visual Studio
Windows-, .
Windows-
,
.
C#, Visual Studio, Windows-,
, ,
, , ,
,
. ,
.
Windows
Windows-, ,
Windows,
Windows-.
, ,
.
. ,
Read()
WriteLine(). , , ,
, .
Windows :
Windows .
: ,
Windows. ,
. , , Windows,
, - Windows.
25. Windows-
691
, Windows-
, Windows.
, Windows
. ,
, .
, .
:
. Windows- ,
. , .
Windows-
Windows-, C#, .
, ,
. ,
, .
.
, , . ,
Windows-.
, . ,
Windows-,
.
.
Form
Form ,
Form. Form ,
, , .
System.ComponentModel.Component (.
24) System.Windows.Forms.Control. Control ,
Windows- . , Form
Control, .
Form Control
.
Windows-,
Windows-,
. ,
. ,
. ,
Windows-. ,
Windows-:
// Windows-,
// .
692
III. C#
using System;
using System.Windows.Forms;
// WinSkel - Form.
class WinSkel : Form {
public WinSkel() {
// .
Text = " Windows-";
}
// Main() .
[STAThread]
public static void Main() {
WinSkel skel = new WinSkel(); // .
// .
Application.Run(skel);
}
, , . 25.1.
. 25.1. , WinSkel
. ,
: System System.Windows.Forms.
System STAThread,
Main(), a System.Windows.Forms
Windows Forms.
WinSkel, Form. ,
WinSkel . ()
.
WinSkel :
Text = " Windows-";
Text, .
,
Windows-. Text :
public virtual string Text { get; set; }
Text Control.
Main(),
Main(), . , ,
25. Windows-
693
. , Main()
STAThread. Microsoft ,
Main() Windows-. STAThread
(threading model),
, .. ,
(single-threaded apartment STA).
, , Windows-
:
.
Main() WinSkel skel.
Run(), Application:
Application.Run(skel);
. Application
System.Windows.Forms ,
Windows-.
Run():
public static void Run(Form ob)
. WinSkel
Form, WinSkel Run().
, . 25.1.
(300 300 ).
. , , ,
. , ,
, .
: ,
Windows API, !
Windows, . , , ,
Form.
,
Application.Run() .
Windows-
Windows- ,
, Visual Studio. , ,
, (
), IDE. ( ,
, ,
Visual Studio.) Windows.
Windows- WinSkel.cs ,
:
csc /t:winexe WinSkel.cs
/t:winexe Windows-,
. ,
WinSkel.
694
III. C#
(IDE)
Visual Studio IDE,
Windows Application. File , New , Project
( , , ). New Project (
) Windows Application (Windows-). WinSkel.
Form1.cs. . ,
WinSkel, Add
, Add New Item ( , ).
, . 25.2.
:
.
. . ,
.
Windows ,
, , . ,
.
, .
25. Windows-
695
.
Button,
ButtonBase. ButtonBase
, Control.
Button :
public Button()
, .
, , ,
, Text .
Location . Location
Control :
public Point Location { get; set; }
Point,
System.Drawing. :
public int X { get; set; }
public int Y { get; set; }
,
100, 200, :
Button MyButton = new Button();
MyButton.Text = " ";
MyButton.Location = new Point(100, 200);
.
Add(), ,
. Controls,
Control. Add():
public virtual void Add(Control cntl)
cntl .
,
.
.
, .
// .
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton = new Button();
public ButtonForm() {
696
III. C#
[STAThread]
public static void Main() {
ButtonForm skel = new ButtonForm();
Application.Run(skel);
}
ButtonForm,
Form. Button MyButton.
ButtonForm , .
, . 25.3.
, . , ,
.
. 25.3.
( -
), ,
. , ,
. C#-,
, .
, ,
, .
, ,
Click.
Click Button. ( Click
Control.) :
public Event EventHandler Click;
25. Windows-
697
EventHandler :
public delegate void EventHandler(object who,
EventArgs args)
, , who, ,
, args.
args , EventArgs.
,
.
,
. .
// .
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton = new Button();
public ButtonForm() {
Text = " ";
MyButton = new Button();
MyButton.Text = "";
MyButton.Location = new Point(100, 200);
// .
MyButton.Click += new EventHandler(MyButtonClick);
Controls.Add(MyButton);
}
[STAThread]
public static void Main() {
ButtonForm skel = new ButtonForm();
Application.Run(skel);
}
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if(MyButton.Top == 200)
MyButton.Location = new Point(10, 10);
else
MyButton.Location = new Point(100, 200);
}
:
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if(MyButton.Top == 200)
MyButton.Location = new Point(10, 10);
else
MyButton.Location = new Point(100, 200);
}
698
III. C#
MyButtonClick() ,
EventHandler, ,
Click. ,
protected.
, ,
, ,
. (
):
public int Top { get; set; }
public int Bottom { get; }
public int Left { get; set; }
public int Right { get; }
,
Top Left, Bottom Right,
. (
Width Height.)
, ,
, , 200,
: 10, 10.
100, 200.
.
MyButtonClick() ,
, Click.
ButtonForm :
MyButton.Click += new EventHandler(MyButtonClick);
MyButtonClick().
, MyButtonClick()
-. , who
, . ,
, , .
MyButtonClick() :
// ,
// .
protected void MyButtonClick(object who, EventArgs e) {
Button b = (Button) who;
if(b.Top == 200)
b.Location = new Point(10, 10);
else
b.Location = new Point(100, 200);
}
who Button,
( MyButton) .
, , .
, ,
.
25. Windows-
699
Windows-
. , .
(
), , . ,
, MessageBox.
.
Show().
Show() . :
public static DialogResult Show(
string msg,
string caption,
MessageBoxButtons mbb)
, , msg,
caption. , ,
mbb. .
MessageBoxButtons ,
:
AbortRetryIgnore
OK
OKCancel
RetryCancel
YesNo
YesNoCancel
,
. , mbb YesNo,
.
, Show(), ,
. :
Abort
Cancel
Ignore
No
None
OK
Retry
Yes
, Show(),
, . ,
,
, ,
, .
,
. , ,
, ,
. ,
. ,
.
// .
using System;
using System.Windows.Forms;
using System.Drawing;
class ButtonForm : Form {
Button MyButton;
Button StopButton;
public ButtonForm() {
Text = " ";
700
III. C#
// .
MyButton = new Button();
MyButton.Text = "";
MyButton.Location = new Point(100, 200);
StopButton = new Button();
StopButton.Text = "";
StopButton.Location = new Point(100, 100);
// .
MyButton.Click += new EventHandler(MyButtonClick);
Controls.Add(MyButton);
StopButton.Click += new EventHandler(StopButtonClick);
Controls.Add(StopButton);
[STAThread]
public static void Main() {
ButtonForm skel = new ButtonForm();
Application.Run(skel);
}
// MyButton.
protected void MyButtonClick(object who, EventArgs e) {
if(MyButton.Top == 200)
MyButton. Location = new Point(10, 10);
else
MyButton.Location = new Point(100, 200);
}
// StopButton.
protected void StopButtonClick(object who, EventArgs e) {
// Yes.
// .
DialogResult result = MessageBox.Show(
" ?",
"",
MessageBoxButtons.YesNo);
if(result == DialogResult.Yes)
Application.Exit();
}
, . ,
ButtonForm . ,
StopButtonClick().
StopButtonClick()
:
// Yes,
// .
DialogResult result = MessageBox.Show(
" ?",
"",
MessageBoxButtons.YesNo);
25. Windows-
701
.
? .
Show(), ,
result. ,
:
if(result == DialogResult.Yes) Application.Exit();
, .
Application.Exit(),
. ,
.
. 25.4.
. 25.4. ,
Windows- ,
. .
, , .
, ,
. .
, ,
.
.
MainMenu , MenuItem
. (,
), . MainMenu
MenuItem Menu.
Windows-,
, . ,
.
Click,
MenuItem. , ,
Click, ,
.
Menu, :
public MainMenu Menu { get; set; }
702
III. C#
.
, .
.
1. MainMenu.
2. MainMenu MenuItem,
.
MenuItems, .
3. MenuItem- MenuItem, ,
.
MenuItems, .
4. .
5. MainMenu Menu, .
, ,
: , .
// .
MainMenu MyMenu = new MainMenu();
// .
MenuItem m1 = new MenuItem("");
MyMenu.MenuItems.Add(m1);
// "".
MenuItem subm1 = new MenuItem("");
m1.Menuitems.Add(subm1);
MenuItem subm2 = new MenuItem("");
m1.Menuitems.Add(subm2);
MenuItem subm3 = new MenuItem("");
m1.Menuitems.Add(subm3);
.
MainMenu MyMenu.
. m1
. MyMenu.
, .
, m1,
. MenuItem-
, ,
, MenuItem-. ,
subm1subm3 m1, File
, , .
,
. ,
Click.
subm1subm3
.
// .
subm1.Click += new EventHandler(MMOpenClick);
subm2.Click += new EventHandler(MMCloseClick);
subm3.Click += new EventHandler(MMExitClick);
25. Windows-
703
, ,
MMExitClick().
, Menu MainMenu:
Menu = MyMenu;
,
.
, .
// .
using System;
using System.Windows.Forms;
class MenuForm : Form {
MainMenu MyMenu;
public MenuForm() {
Text = " ";
// .
MainMenu MyMenu = new MainMenu();
// .
MenuItem m1 = new MenuItem("");
MyMenu.MenuItems.Add(m1);
MenuItem m2 = new MenuItem("");
MyMenu.MenuItems.Add(m2);
// .
MenuItem subm1 = new MenuItem("");
m1.MenuItems.Add(subm1);
MenuItem subm2 = new MenuItem("");
m1.MenuItems.Add(subm2);
MenuItem subm3 = new MenuItem("");
m1.MenuItems.Add(subm3);
// "".
MenuItem subm4 = new MenuItem("");
m2.MenuItems.Add(subm4);
MenuItem subm5 = new MenuItem(" ");
m2.MenuItems.Add(subm5);
MenuItem subm6 = new MenuItem("");
m2.MenuItems.Add(subm6);
// .
subm1.Click += new EventHandler(MMOpenClick);
subm2.Click += new EventHandler(MMCloseClick);
subm3.Click += new EventHandler(MMExitClick);
subm4.Click += new EventHandler(MMCoordClick);
subm5.Click += new EventHandler(MMChangeClick);
subm6.Click += new EventHandler(MMRestoreClick);
704
III. C#
// .
Menu = MyMenu;
[STAThread]
public static void Main() {
MenuForm skel = new MenuForm();
Application.Run(skel);
}
// .
protected void MMCoordClick(object who, EventArgs e) {
// , .
string size =
string. Format(" {0}: {1}, {2}\n{3}: {4}, {5} ",
", ", Top, Left,
", ", Bottom, Right);
// .
MessageBox.Show(size, " ",
MessageBoxButtons.OK);
}
// .
protected void MMChangeClick(object who, EventArgs e) {
Width = Height = 200;
}
// .
protected void MMRestoreClick(object who, EventArgs e) {
Width = Height = 300;
}
// .
protected void MMOpenClick(object who, EventArgs e) {
MessageBox.Show(" ", "",
MessageBoxButtons.OK);
}
// .
protected void MMCloseClick(object who, EventArgs e) {
MessageBox.Show(" ", "",
MessageBoxButtons.OK);
}
// .
protected void MMExitClick(object who, EventArgs e) {
DialogResult result = MessageBox.Show(
" ?",
"",
MessageBoxButtons.YesNo);
if(result == DialogResult.Yes) Application.Exit();
}
. 25.5.
25. Windows-
705
. 25.5. ,
. (
, ) .
,
, .
. ,
.
: ,
.
. ,
.
.
,
200 .
Width Height:
public int Width { get; set; }
public int Height { get; set; }
300x300.
.
, Windows- .
Windows ,
. Windows-,
.
, System.Windows.Forms.
Windows-, ,
() . ,
Windows.Drawing, ,
.
Windows.Drawing ,
Windows GDI (Graphics Device Interface).
, .
706
III. C#
26
,
, , (10 5) * 3,
? , , ,
.
,
.
(expression parsing), ,
,
, .
,
, .
,
. ,
(recursive-descent
parser), ,
. ,
.
, ,
C#.
. ,
GUI- - .
C++. ,
C#, , C#
.
,
, .
, . , ,
:
;
+, -, /, *, ^, % =;
;
.
(^) (
, C#), (=) .
.
:
10-8
(100 - 5) * 14 / 6
a + b - c
10 ^ 5
= 10 - b
,
:
708
III. C#
+ - ()
^
* / %
+
=
.
, , . -,
( ,
26 , A Z).
(a A
). -, , double,
. ,
,
.
:
,
, . ,
:
10 - 2 * 3
, 4. ,
, ,
.
:
= while( ) {
=
b =
= a op b
}
, ,
;
.. ,
10 2 * 3 24 (.. 8 * 3), 4,
.
, ,
.
, , ,
. ,
, , , ..
,
.
, ,
. ( ,
, ,
.
.)
26.
709
.
, ,
(recursive data structures), ..
, . ,
+, -, *, / ,
:
-> [+ ][- ]
-> [* ][/ ]
-> , ()
, ->
.
. ,
: , ,
, . ,
.
10 + 5 *
: 10 5 * B. : 5 B.
, .
14 * (7 - )
: 14 (7 - ).
, .
: .
,
,
.
. ,
,
:
9/3 - (100 + 56)
.
1. , 9/3.
2. .
3.
3. , (100 + 56).
.
4. . 156.
5. 156 3. 153.
, , .
, .
. -,
710
III. C#
. -,
, .
.
( double),
.
. ,
.
,
. ,
* - (W + 10)
: , *, B, -, (, W, +, 10 ).
,
.
,
, .
, ,
.
. , ,
GetToken().
, , Parser.
,
, GetToken(). , Parser
:
class Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// ,
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string exp; // .
int expIdx; // .
string token; // .
Types tokType; // .
Types.
.
: , .
variable, number delimiter, Types.
delimiter , . none
. Errors
, .
, ,
exp. , exp , 10+4.
expIdx
. token,
tokType,
26.
711
GetToken().
, , exp,
expIdx, .. exp[expIdx].
token, tokType. GetToken()
IsDelim(), ,
.
// .
void GetToken() {
tokType = Types.NONE;
token = "";
if(expIdx == exp.Length) return; //
// .
while(expIdx < exp.Length &&
Char.IsWhiteSpace(exp[expIdx])) ++expIdx;
// .
if(expIdx == exp.Length) return;
if(IsDelim(exp[expIdx])) { // ?
token += exp[expIdx];
expIdx++;
tokType = Types.DELIMITER;
} else if(Char.IsLetter(exp[expIdx])) { //
// ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.VARIABLE;
} else if(Char.IsDigit(exp[expIdx])) { // ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.NUMBER;
// true,
// .
bool IsDelim(char ) {
if((" +-/*%A=()".IndexOf(c) != -1)) return true;
return false;
}
GetToken().
, ,
expIdx exp.Length.
712
III. C#
expIdx , ,
, , ( ).
, GetToken()
. exp[expIdx]
, , , (
). ,
, token, tokType
DELIMITER. ,
, . ,
token, tokType VARIABLE.
, ,
, token, tokType
NUMBER. ,
, token .
GetToken(),
. ,
, .
, .
.
, GetToken(), :
+ 100 - ( * ) /2
GetToken()
( ):
+
100
(
)
/
2
VARIABLE
DELIMITER
NUMBER
DELIMITER
DELIMITER
VARIABLE
DELIMITER
VARIABLE
DELIMITER
DELIMITER
NUMBER
, ,
. ,
, .
GetToken() , .
26.
713
, ,
.
/*
,
. */
using System;
// .
class ParserException : ApplicationException {
public ParserException(string str) : base(str) { }
class Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// .
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string exp; // .
int expIdx; // .
string token; // .
Types tokType; // .
// .
public double Evaluate(string expstr)
{
double result;
exp = expstr;
expIdx =0;
try {
GetToken();
if(token == "") {
SyntaxErr(Errors.NOEXP); //
// .
return 0.0;
}
EvalExp2(out result);
if(token != "") //
// null-.
SyntaxErr(Errors.SYNTAX);
return result;
} catch(ParserException exc) {
//
// .
Console.WriteLine(exc);
714
III. C#
return 0.0;
}
// .
void EvalExp2(out double result)
{
string op;
double partialResult;
EvalExp3(out result);
while((op = token) == "+" || op == "-") {
GetToken();
EvalExp3(out partialResult);
switch(op) {
case "-":
result = result - partialResult;
break;
case "+":
result = result + partialResult;
break;
}
}
}
// .
void EvalExp3(out double result)
{
string op;
double partialResult = 0.0;
EvalExp4(out result);
while((op = token) == "*" ||
op == "/" || op == "%") {
GetToken();
EvalExp4(out partialResult);
switch(op) {
case "*":
result = result * partialResult;
break;
case "/":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = result / partialResult;
break;
case "%":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
result = (int) result % (int) partialResult;
break;
}
}
}
// .
void EvalExp4(out double result){
double partialResult, ex;
26.
715
int t;
EvalExp5(out result);
if(token == "^") {
GetToken();
EvalExp4(out partialResult);
ex = result;
if(partialResult == 0.0) {
result = 1.0;
return;
}
for(t=(int)partialResult-1; t > 0; t--)
result = result * (double)ex;
}
// + -.
void EvalExp5(out double result) {
string op;
op = "";
if((tokType == Types.DELIMITER) &&
token == "+" || token == "-") {
op = token;
GetToken();
}
EvalExp6(out result);
if(op == "-") result = -result;
}
// .
void EvalExp6(out double result)
{
if((token == "(")) {
GetToken();
EvalExp2(out result);
if(token != ")")
SyntaxErr(Errors.UNBALPARENS);
GetToken();
}
else Atom(out result);
}
// .
void Atom(out double result) {
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token);
} catch(FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetToken();
return;
default:
716
III. C#
result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;
// .
void SyntaxErr(Errors error)
{
string[] err = {
" ",
" ",
" ",
" "
};
throw new ParserException(err[(int)error]);
}
// .
void GetToken() {
tokType = Types.NONE;
token = "";
if(expIdx == exp.Length) return;
//
// .
// .
if(expIdx == exp.Length) return;
if(IsDelim(exp[expIdx])) { // ?
token += exp[expIdx];
expIdx++;
tokType = Types.DELIMITER;
} else if(Char.IsLetter(exp[expIdx])) {
//
// ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length)
break;
}
tokType = Types.VARIABLE;
}
else if(Char.IsDigit(exp[expIdx])) { // ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length)
break;
}
tokType = Types.NUMBER;
}
26.
717
// true,
// .
bool IsDelim(char c) {
if((" +-/*%^=()".IndexOf(c) != -1)) return true;
return false;
}
}
: +, -, *, /
%. , (^)
,
.
, Parser.
Evaluate(),
, . ,
Evaluate().
:
// .
using System;
class ParserDemo {
public static void Main() {
string expr;
Parser p = new Parser();
Console.WriteLine(
" .");
for(;;) {
Console.Write(" : ");
expr = Console.ReadLine();
if(expr == "") break;
Console.WriteLine(": " + p.Evaluate(expr));
:
.
: 10-2*3
: 4
: (10-2)*3
: 24
: 10/3
: 3.33333333333333
: 10/3.5
: 2.85714285714286
:
718
III. C#
Parser.
GetToken(), Parser .
exp. Evaluate().
, ,
C#-. , ,
:
"10 - 5"
"2 * 3.3 / (3.1416 * 3.3)"
exp expIdx.
expIdx . expIdx
. token
, tokType .
Evaluate(),
, , .
EvalExp2()EvalExp6() Atom()
.
. ,
, .
EvalExpl().
SyntaxErr()
. GetToken() IsDelim(), ,
. GetToken()
.
, .
, ,
:
10 - 3 * 2
Evaluate() .
(""),
, Evaluate() 0.0.
10. EvalExp2(). EvalExp2()
EvalExp3(), EvalExp4(), EvalExp5().
EvalExp5() ,
. , EvalExp6().
EvalExp6() EvalExp2()
( , ), Atom()
. ,
Atom() result 10.
, .
, , ( ),
, .. ,
. -,
Eval2().
. -,
. ,
3, .
Atom() 3 result *.
26.
719
EvalExp3(), , 2.
, 2 3.
EvalExp2(), .
4. ,
; , ,
, .
SyntaxErr(),
ParserException,
. ParserException ;
, Parser. ,
,
.
,
. .
,
,
. ,
.
. ,
Z.
Parser.
26- double. , Parser :
double[] vars = new double[26];
Parser ,
:
public Parser() {
// .
for(int i=0; i < vars.Length; i++)
vars[i] = 0.0;
}
0.0.
.
Z, vars
ASCII- .
FindVar(). :
// .
double FindVar(string vname) {
if(IChar.IsLetter(vname[0])){
SyntaxErr(Errors.SYNTAX);
return 0.0;
}
return vars[Char.ToUpper(vname[0])-'A'];
}
720
III. C#
, (.. )
, 12 test,
.
.
Atom(),
, . :
// .
void Atom(out double result) {
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token);
} catch(FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetToken();
return;
case Types.VARIABLE:
result = FindVar(token);
GetToken();
return;
default:
result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;
}
}
, ,
,
. ,
(=).
Parser EvalExp1().
. , ,
, Evaluate() EvalExp1(),
EvalExp2(). EvalExp1():
// .
void EvalExp1(out double result) {
int varIdx;
Types ttokType;
string temptoken;
if(tokType == Types.VARIABLE) {
// .
temptoken = String.Copy(token);
ttokType = tokType;
// .
varIdx = Char.ToUpper(token[0]) - 'A';
GetToken();
if(token != "=") {
26.
721
PutBack();
//
// ,
// .
token = String.Copy(temptoken);
tokType = ttokType;
} else {
GetToken(); //
exp.EvalExp2(out result);
vars[varIdx] = result;
return;
}
}
EvalExp2(out result);
EvalExp1() , . ,
,
,
. , = 100 ,
, , /10
. EvalExp1()
. ,
PutBack(), :
// .
void PutBack()
{
for(int i=0; i < token.Length; i++)
expIdx;
}
:
/*
, . */
using System;
// .
class ParserException : ApplicationException {
public ParserException(string str) : base(str) { }
public override string ToString() {
return Message;
}
}
class Parser {
// .
enum Types { NONE, DELIMITER, VARIABLE, NUMBER };
// .
enum Errors { SYNTAX, UNBALPARENS, NOEXP, DIVBYZERO };
string exp; // .
int expIdx; // .
string token; // .
722
III. C#
Types tokType; // .
// .
Double[] vars = new double[26];
public Parser() {
// .
for(int i=0; i < vars.Length; i++)
vars[i] = 0.0;
}
// .
public double Evaluate(string expstr)
{
double result;
exp = expstr;
expIdx = 0;
try {
GetToken();
if(token == "") {
SyntaxErr(Errors.NOEXP); // .
return 0.0;
}
EvalExp1(out result); //
//
// EvalExp1().
if(token != "") //
// .
SyntaxErr(Errors.SYNTAX);
return result;
} catch(ParserException exc) {
// .
Console.WriteLine(exc);
return 0.0;
}
}
// .
void EvalExp1(out double result) {
int varIdx;
Types ttokType;
string temptoken;
if(tokType == Types.VARIABLE) {
// .
temptoken = String.Copy(token);
ttokType = tokType;
// .
varIdx = Char.ToUpper(token[0]) - 'A';
GetToken();
26.
723
if(token != "-") {
PutBack();
//
// ,
// .
token = String.Copy(temptoken);
tokType = ttokType;
} else {
GetToken();
//
// exp.
EvalExp2(out result);
vars[varIdx] = result; return;
}
}
EvalExp2(out result);
// .
void EvalExp2(out double result)
{
string op;
double partialResult;
EvalExp3(out result);
while((op = token) == "+" || op == "-") {
GetToken();
EvalExp3(out partialResult);
switch(op) {
case "-":
result = result - partialResult;
break;
case "+":
result = result + partialResult;
break;
}
}
}
// .
void EvalExp3(out double result)
{
string op;
double partialResult = 0.0;
EvalExp4(out result);
while((op = token) == "*" ||
op == "/" || op == "%") {
GetToken();
EvalExp4(out partialResult);
switch(op) {
case "*":
result = result * partialResult;
break;
case "/":
if(partialResult == 0.0)
SyntaxErr(Errors.DIVBYZERO);
724
III. C#
}
// .
void EvalExp4(out double result) {
double partialResult, ex;
int t;
EvalExp5(out result);
if(token == "^") {
GetToken();
EvalExp4(out partialResult);
ex = result;
if(partialResult ==0.0) {
result =1.0; return;
}
for(t=(int)partialResult-1; t > 0; t--)
result = result * (double)ex;
}
}
// + -.
void EvalExp5(out double result)
{
string op;
op = "";
if((tokType == Types.DELIMITER) &&
token == "+" || token == "-") {
op = token;
GetToken();
}
EvalExp6(out result);
if(op == "-") result = -result;
}
// .
void EvalExp6(out double result)
{
if((token =="(")) {
GetToken();
EvalExp2(out result);
if(token != ")")
SyntaxErr(Errors.UNBALPARENS);
GetToken();
}
else Atom(out result);
}
26.
725
// .
void Atom(out double result)
{
switch(tokType) {
case Types.NUMBER:
try {
result = Double.Parse(token);
} catch (FormatException) {
result = 0.0;
SyntaxErr(Errors.SYNTAX);
}
GetToken();
return;
case Types.VARIABLE:
result = FindVar(token);
GetToken();
return;
default:
result = 0.0;
SyntaxErr(Errors.SYNTAX);
break;
}
}
// .
double FindVar(string vname) {
if(Char.IsLetter(vname[0]) ) {
SyntaxErr(Errors.SYNTAX);
return 0.0;
}
return vars[Char.ToUpper(vname[0])-'A'];
}
// .
void PutBack()
{
for(int i=0; i < token.Length; i++)
expIdx--;
}
// .
void SyntaxErr(Errors error)
{
string[] err = {
" ",
" ",
" ",
" "
};
throw new ParserException(err[(int)error]);
}
// .
void GetToken()
{
tokType = Types.NONE;
token = "";
726
III. C#
// .
if(expIdx == exp.Length) return;
if(IsDelim(exp[expIdx])) { // ?
token += exp[expIdx]; expIdx++;
tokType = Types.DELIMITER;
} else if(Char.IsLetter(exp[expIdx])) {
//
// ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.VARIABLE;
} else if(Char.IsDigit(exp[expIdx])) { // ?
while(!IsDelim(exp[expIdx])) {
token += exp[expIdx];
expIdx++;
if(expIdx >= exp.Length) break;
}
tokType = Types.NUMBER;
}
// true,
// .
bool IsDelim(char c) {
if((" +-/*%^=()".IndexOf(c) != -1))
return true;
return false;
}
,
, .
, :
= 10/4
-
C = * (F - 21)
26.
727
,
.
(, ). ,
, :
10 ** 8
((10 - 5) * 9
/8
, ,
.
.
, .
, ,
SyntaxErr(), .
, -
, Atom(), FindVar() EvalExp6(),
.
SyntaxErr()
ParserException, .
Evaluate(). ,
.
.
,
. ,
, , , .
.
. , ,
, ,
. , ,
:
STRING;
GetToken(), ;
case- Atom() STRING.
, :
= ""
b = ""
c = + b
b, ,
"".
728
III. C#
:
-,
.
.
, Parser .
. Parser Component.
Dispose(bool). !
.
26.
729
C#
XML
C# .
// /* */. XML- XML. (XML- .)
XML- ///, XML-
, , , .
XML-,
. XML-
XML-. XML-
IntelliSense Visual Studio.
XML
C# XML-, . A.1.
, XML, . <list> (<>)
. :
. :
<listheader>
<term> </term>
<description> </description>
</listheader>
. .
:
<item>
<term> _ </term>
<description> </description>
</item>
_.
_ .
<item>.
A.1. XML
<> </>
, ,
,
,
, ,
,
<code> </code>
<example>
</example>
<exception cref="">
explanation
</exception>
<include file =
'_'
path ='
[@_ = "ID_"]' />
<list type = "">
_
_
</list>
, XML-
. _
. , ID
, _, ID_,
.
,
: bullet (), number
() table ()
A. XML
733
. A.1
<para> </para>
<param name =
'_' >
</param>
<paramref name =
"_" />
<permission cref =
"">
</permission>
<remarks>
</remarks>
<returns>
</returns>
<see cref "" />
<seealso cref =
"" />
<summary>
</summary>
<value>
</value>
,
_. ,
, _
,
, .
,
, ,
,
, ,
,
,
". "
, ,
,
, ,
XML-
XML-, ,
/doc. , DocTest.cs, XML, :
csc DocTest.cs /doc:DocTest.xml
XML-
Visual Studio IDE, Property Pages (
), View , Property Pages (,
). Configuration Properties ,Build (
, ). XML- XML
Documentation File (XML- ).
XML-
XML-:
// XML-.
using System;
734
IV.
///
///
///
///
<remark>
XML-.
Test .
</remark>
class Test {
/// <summary>
/// Main().
/// </summary>
public static void Main() {
int sum;
sum = Summation(5);
Console.WriteLine(" " + 5 +
" " + sum);
}
/// <summary>
/// Summation() .
/// <param name = "val">
/// val.
/// </param>
/// <see cref="int"> </see>
/// <returns>
/// int-.
/// </returns>
/// </summary>
static int Summation(int val) {
int result = 0;
, XmlTest.cs.
csc XmlTest.cs /doc:XmlTest.xml
,
XmlTest.xml, :
<?xml version="1.0"?>
<doc>
<assembly>
<name>t</name>
</assembly>
<members>
<member name="T:Test">
<remark>
XML-.
Test .
</remark>
</member>
<member name="M:Test.Main">
<summary>
Main().
A. XML
735
</summary>
</member>
<member name="M:Test.Summation(System. Int32) ">
<summary>
Summation() .
<param name="val">
val.
</param>
<see cref="T:System.Int32"> </see>
<returns>
int-.
</returns>
</summary>
</member>
</members>
</doc>
,
. ,
XML-.
736
IV.
C#
,
,
, ,
,
, C#
, ,
, C++ C#
,
, ,
() , , ..
( ) C#-
,
,
(,
), , 1,
-,
,
-, RS-232,
( , ) -, ,
1 ,
738
IV.
(-
Parallax,
Inc.
(www.parallaxinc.com).
RS-232, Parallax.
RS-232, 300
. ,
BASIC Stamp.
, .
.
, ,
. ,
. (
RS-232). BASIC Stamp
. ,
BASIC Stamp ,
.
. ,
,
.
, .
,
.
, .
, -
C++. ,
C#. ,
.
, C#-.
. C#
739
#
#define, 441
#elif, 441; 444
#else, 443
#endregion, 446
#error, 445
#if, 441
#line, 445
#region, 446
#undef, 445
#warning, 445
.
.NET Framework, 27
A
A.D., 570
abstract, 309; 340
Access specifier, 39
Anno Domini, 570
API, 688
Application Programming Interface, 688
ApplicationException, , 350; 370
ArgumentException, , 384; 392; 641
ArgumentNullException, , 384; 392;
406
ArgumentOutOfRangeException, ,
617
Array, , 521
ArrayList, , 615
ArrayTypeMismatchException, , 365
as, , 450
ASCII, 60; 376
Assembly, 446
Assembly, , 465
AttributeTargets, , 480
AttributeUsage, , 473; 479
740
BitArray, , 631
BitConverter, , 530
bool, 54; 61; 521
Boolean, , 521
Boxing, 315
break, 109; 120
BufferedStream, , 378
Button, , 694
ButtonBase, , 694
byte, 54; 376; 406
Byte, , 406
Bytecode, 25
, , 24
C++, , 24
catch, 350; 357
char, 54; 60; 376
Char, , 516
checked, 372
class, 39; 127
Client, 669
CLR (Common Language Runtime), 27;
350
CLS (Common Language Specification), 29
COBOL, 31
CollectionBase, , 634
CollectionsUtil, , 634
COM, 669; 670
COM (Component Object Model), 18
Common Language Runtime, 27; 350; 365
Common Language Specification, 29
Common Type System, 29
Component model, 669
Component Object Model, 18; 669
Component, , 670
Conditional, , 480
Console, , 40; 377
Console. Error, , 376; 382
Console. In, , 376; 380
Console.Out, , 376
const, , 498
ConstructorInfo, , 461
continue, 122
Control, , 694
Cookie, , 657
CookieCollection, , 657
CookieContainer, , 657
CTS (Common Type System), 29
CultureInfo, , 519
D
DateTime, , 567
Deadlock, 596
decimal, 54; 58; 406
Decimal, , 406; 512
default, 446
Delegate, 410
delete, 149
DictionaryBase, , 634
DictionaryEntry, , 614
DirectoryNotFoundException, , 384
DivideByZeroException, , 350; 365
DLL, 470
double, 44; 54; 57; 406; 509
Double, , 406; 509
do-while, 119
Dynamic link library, 470
E
Encoding, , 541
enum, 345
Enumeration, 345
ESC-, 66
Event, 416
EventArgs, , 426
Event Handler, , 428
Exception, , 350; 363
explicit, 246
Expression parsing, 706
F
false, 61; 237
FIFO, 629
File Transfer Protocol, 646
FileNotFoundException, , 384; 392
FileStream, , 378; 383
finally, 350; 362
fixed, 487
float, 44; 55; 57; 406; 509
for, , 47; 110
foreach, 120; 168; 609; 634
Form, , 690
FormatException, , 406
Forms, , 688
FORTRAN, 31
FTP, 646
FullName, , 452
G
GC, , 534
goto, 123
GUI, 688
H
Hashing, 621
Hashtable, , 621
HTTP, 646
HttpWebRequest, , 646; 648
HttpWebResponse, , 646; 648
HybridDictionary, , 634
HyperText Transfer Protocol, 646
I
ICloneable, , 536
ICollection, , 610
IComparable, , 535; 639
IComparer, , 611; 613; 640
IComponent, , 670
IConvertible, , 536
IDE (Integrated Development
Environment), 34
IDictionary, , 610; 612
IDictionaryEnumerator, , 611;
613; 636
IEnumerable, , 609; 613
IEnumerator, , 609; 613
if, , 45; 103
if-else-if, 105
IFormatProvider, , 538
IHashCodeProvider, , 611; 614
IList, , 610; 611
implicit, 246
Indexer, 257
IndexOutOfRangeException, , 158;
351; 365
Instance variable, 32
int, 42; 55; 406
Int16, , 406
Int32, , 406
Int64, , 406
Integrated Development Environment, 34
interface, 320
internal, , 446
InvalidCastException, , 365
741
J
Java, 25
Java Virtual Machine, 25
JIT-, 28
JVM (Java Virtual Machine), 25
L
Length, , 165
LIFO, 627
List Dictionary, , 634
lock, 495; 587
long, 55; 406
M
Main(), 213
MainMenu, , 700
MarshalByRefObject, , 672
Math, , 58; 502
MemberInfo, , 455
MemoryStream, , 378; 402
Menu, , 700
MenuItem, , 700
Message, , 363
MessageBoxButtons, , 698
Method overloading, 203
MethodBase, , 455
MethodImplAttribute, , 597
MethodInfo, , 455
MFC, , 688
Microsoft Foundation Classes, 688
Microsoft Intermediate Language, 28; 446
Monitor, , 592
MSIL (Microsoft Intermediate Language),
28; 446
Multicasting, 413
Multiple indirection, 493
Multithreaded programming, 574
N
Namespace, 38; 432 NameValueCollection,
, 634 new, 147; 291; 331; 340
742
P
params, , 197
Pascal, 23
Picture format, 563
Pluggable protocols, 645
Preprocessor, 441
private, , 39; 180
Process, , 606
protected, , 283; 340
ProtocolViolationException, , 652
public, , 39; 180
Q
Queue, , 629
R
Random, , 532
readonly, 495
ReadOnlyCollectionBase, , 634
Recursive descent parser, 19
Ref, 414
ref, , 191; 207
Reflection, 453
Reflection API, 454
return, 123; 137
RTTI, 449
Runtime type identification, 449
S
sbyte, 55; 406
Sbyte, , 406
Scope, 70
sealed, 313
SecurityException, , 384
SeekOrigin, , 400
short, 55; 406
Single, , 406; 509
Single-threaded apartment, 692
sizeof, 495
Sorted List, , 623
Spaghetti code, 23
Sqrt(), , 57
STA, 692
Stack, 33
Stack, , 627
stackalloc, 496
StackOverflowException, , 365; 366
StackTrace, , 363
static, , 39; 218
Stream, 376
Stream, , 377
StreamReader, , 379; 391
StreamWriter, , 379
string, 540
string, , 172
StringBuilder, , 178; 540
StringCollection, , 634
StringDictionary, , 634
StringReader, , 379; 404
StringWriter, , 379; 404
struct, 340
switch, 106; 348
System, , 38; 406; 500
System.Attribute, , 473
System.AttributeUsageAttribute, , 480
System.Collections, ,
609; 610
System.Collections.ICollection,
, 334
System. Collections. IEnumerator,
, 334
System.Collections.Specialized,
, 634
System.ComponentModel.Component,
, 670; 690
System.ComponentModel.IComponent,
, 670
System.Delegate, , 415
System.Diagnostics, ,
606
System.Diagnostics.ConditionalAttribute,
, 480
System.Exception, , 350
System.IComparable, , 334
System.IDisposable, , 497
System.Net, , 644
System.Net.Sockets, ,
644
System.Object, , 313
System.ObsoleteAttribute, , 481
System.Reflection, ,
455
System.Reflection.MemberInfo, , 453
System.String, , 175; 540
System.Text, , 178; 540
System.Threading, ,
575
System.Type, , 452
System.Windows.Forms, , 688
System.Windows.Forms.Control, ,
690
SystemException, , 350
T
TargetSite, , 363
TextReader, , 378
TextWriter, , 378
this, 151; 212
Thread, 574
Thread, , 575
ThreadAbortException, , 602
Threading model, 692
ThreadState, , 604
throw, 350; 360
true, 61; 237
try, 350; 358
typeof, , 452
U
uint, 55; 406
UInt16, , 406
UInt32, , 406
UInt64, , 406
ulong, 55; 406
Unboxing, 315
unchecked, 372
Unicode, 60; 376
Uniform Resource Identifier, 645
Uniform Resource Locator, 645
Universal Time Coordinated, 567
743
UNIX, 23
unsafe, 484; 486
Unsafe code, 484
URI, 645
URI, , 654
URL, 645
ushort, 55; 406
using, 39; 435; 497; 499
using, , 682
UTC, 567
V
value, 258; 266; 422
virtual, 301; 340
Visual Studio .NET,
, 34
void, 40; 134
volatile, , 498
W
WebClient, , 663
WebException, , 652
WebExceptionStatus, , 652
WebHeaderCollection, , 656
WebRequest, , 645; 646
WebResponse, , 645; 648
while, 117
Windows.Drawing, ,
704
Windows-, 688
Windows-, 690
X
XML, 728
A
, 309
, 257
, 706
, 40; 140
, 213
, 473
AttributeUsage, 473; 479
Conditional, 480
MethodImplAttribute, 597
Obsolete, 481
744
-, 25
C#, 499
, 48
, 24
, 596
Java, 25
, 301
, 82
, 410
, 149
, 302
,
449
, 441
, 51
, 86
, 156
, 257
, 328
, 264
, 260
, 157
, 68
, 32
, 82
, 32; 127
ApplicationException, 350
ArgumentException, 384; 392; 641
ArgumentNullException, 384; 392; 406
ArgumentOutOfRangeException, 617
Array, 521
ArrayList, 615
Assembly, 465
BinaryReader, 394; 395
BinaryWriter, 394
BitArray, 631
BitConverter, 530
BufferedStream, 378
Button, 694
ButtonBase, 694
CollectionBase, 634
CollectionsUtil, 634
Component, 670; 671
Console, 40; 52; 377
ConstructorInfo, 461
Control, 694
Cookie, 657
CookieCollection, 657
CookieContainer, 657
CultureInfo, 519
DictionaryBase, 634
DirectoryNotFoundException, 384
DivideByZeroException, 350
Encoding, 541
EventArgs, 426
Exception, 350; 363
FileNotFoundException, 384; 392
FileStream, 378; 383
Form, 690
FormatException, 406
GC, 534
Hashtable, 621
HttpWebRequest, 646; 648
HttpWebResponse, 646; 648
Hybrid Dictionary, 634
IOException, 384
ListDictionary, 634
MainMenu, 700
MarshalByRefObject, 672
Math, 58; 502
MemberInfo, 455
MemoryStream, 378; 402
Menu, 700
MenuItem, 700
MethodBase, 455
MethodInfo, 455
Monitor, 592
NameValueCollection, 634
NotSupportedException, 386; 611
object, 313; 340; 535; 609
ObjectDisposedException, 385
OverflowException, 372; 407
Process, 606
ProtocolViolationException, 652
Queue, 629
Random, 532
ReadOnlyCollectionBase, 634
SecurityException, 384
SortedList, 623
Stack, 627
Stream, 377
StreamReader, 379; 389; 391
StreamWriter, 379; 389
String, 540
StringBuilder, 178; 540
StringCollection, 634
StringDictionary, 634
StringReader, 379; 404
StringWriter, 379; 404
System.Attribute, 473
System.AttributeUsageAttribute, 480
System.ComponentModel.Component,
670; 690
System.Delegate, 415
System.Diagnostics.ConditionalAttribute,
480
745
System.Exception, 350
System.Object, 313
System.ObsoleteAttribute, 481
System.Reflection.MemberInfo, 453
System.String, 175; 540
System.Type, 452
System.Windows.Forms.Control, 690
SystemException, 350
TextReader, 378; 389
TextWriter, 378; 389
Thread, 575
ThreadAbortException, 602
URI, 654
WebClient, 663
WebException, 652
WebHeaderCollection, 656
WebRequest, 645; 646
WebResponse, 645; 648
, 278
, 278
, 669
C#, 51
, 609
, 38
csc.exe,
34
, 669
, 669
, 446
, 65
, 144; 285
, 670; 683
, 495
, 551; 709
, 65
, 66
, 67
, 65
746
Object.GetHashCode(), 237
Read(), 380
ReadLine(), 381
Sqrt(), 57
ToString(), 364
Write(), 379
WriteLine(), 379
, 309
, 301
, 320
, 413
, 573
,
493
, 669
, 33; 277
, 330
, 279
, 634
, 70
, 70
, 349
, 32; 127
-
, 24; 31
, 31
, 484
&, 486
*, 486
?,99
[], 257
->, 488
as, 450
is, 449
new, 147; 340
typeof, 452
XOR ( ), 94
, 48; 82
, 81
1, 95
, 92
, 93
, 48; 82
, 95
, 46
, 393
, 246
, 43; 89
, 80
, 81
, 84
, 87
, 84
, 90
, 101
, 89
, 96
C# , 109
C# C++, 150; 155; 160; 172;
202; 280; 345; 410; 485; 540; 575; 609;
670
C# Java, 484
, 453
, 629
, 140
, 476
, 476
, 134
, 226
, 208
, 240
, 203
, 224 true false, 23 7
, 236
, 228
, 42; 68
, 70
, 68
, 70
, 345
MessageBoxButtons, 698
SeekOrigin, 400
ThreadState, 604
UnicodeCategory, 517
WebExceptionStatus, 652
, 347
, 283
, 32; 302
, 708
, 557
, 376; 574
, 376
, 380
, 378
, 73
, 441
, 315
, 74
, 101
, 48
Microsoft, 28
, 431
System, 38; 431; 500
System.Collections, 609; 610
System.Collections.Specialized, 634
System.Diagnostics, 606
System.IO, 377
System.Net, 644
System.Net.Sockets, 644
System.Text, 178; 540
System.Threading, 575
Windows.Drawing, 704
, 645
, 646
, 646
, 574
, 215
, 266
Length, 165
Message, 363
StackTrace, 363
TargetSite, 363
, 327
, 208
, 60
, 586
-, 376
, 365
, 29
, 149
, 416
, 39; 128
, 62; 557
, 180
,
29
, 132
747
, 33; 627
, 66; 172; 540
, 340; 488
Boolean, 521
Char, 516
Decimal, 512
DictionaryEntry, 614
, 23
, 507
, 283
XML, 729
bool, 61
char, 60
decimal, 58
double, 44
int, 44
string, 172
, 57
, 54
, 42
, 54
, 55
, 55
, 55
, 54
, 55
, 54
, 54
, 55
, 55
, 484
,
645
, 60
, 66
, 446
, 563
, 556
, 567
, 571
, 32
X
, 621
-, 621
, 47
for, 47
, 116
, 116
, 66
, 728
, 670
748