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

-

-
2014

004.438 #
32.973.26-018.1
12

. .
12

C# . .: -, 2014.
432 .: .
ISBN 978-5-9775-0943-5

C#. C#
.NET. , , . . : , , , , , , , , .
Windows,
. , Windows Forms . SharpDevelop.

004.438 #
32.973.26-018.1
:

.
.

30.12.13.
60 901/16. . . . . 27.
700 .
"-", 191036, -, ., 20.
""
199034, -, 9 , 12/28

ISBN 978-5-9775-0943-5

. ., 2014
, "-", 2014


..............................................................................................9
I.
C# ............................11
1. C# .NET .......13
.NET Framework ........................................................... 17
.NET Framework ........................................................... 17

2. C# ............19
......................................................................................... 19
SharpDevelop
C# ................................................................................................... 23

3. , ............................33
.................................................................................................. 37
........................................................................ 38
............................................................... 40
.............................................................................. 41
...................................................................................... 43
............................................................................... 49
for ................................................................................................. 50
........................................................................... 54
char ................................................................................................ 55
string .............................................................................................. 60
string ....................... 62

.................................................................... 63

........................... 65
.................................................................................. 66
....................................... 68
............................................. 70
var .......................................................................................................... 72
........... 73
........................................................................... 73
........................................... 74
.......................................................................... 76
............................................................................. 76
................. 78
....................................................................... 78
................................................ 79
.................................................................................. 79
................................................................................ 80
........................................................................................ 82

4. ............................................................................85
.................................................................... 90
if ............................................................................................ 93
goto ....................................................................................... 94
......................................... 94
.............................................. 97
................................................ 100
switch ........................................................................ 102
................................................................. 105
............................................................................... 106

5. ..........................................................................107
................................................................................ 107
foreach ........................................................................................ 111
.............................................................................. 113

6. -......115
............................................................................................................. 115
.......................................................................................................... 116

7. ...........................121
............................................................................................................ 121
....................................................................... 122
............................................................................. 125

............................................................................................. 128
........................................... 133

II. -
...........................................................135
8. ........................................................137
this ................................................................................... 146
static ................................................................................ 147
.......................................................................... 149
................................................................................... 149
- ................. 150
..................................................................................... 150
get set ................ 152
............................... 155
.................................... 160
......................................................... 160
............................................................ 161
.
partial .......................................................................... 163
...................................................................................... 167
............................................................ 171
................................................. 171
............................ 175
................................................................ 177
..................................................................................... 178
.................................................................................. 182
............................................................................ 183
................................... 184
......................................................... 184
as is ............................................................................... 185
................................................................................................... 191
........................................................................................................ 193

9. ....................195
try catch ......................................................................................... 195
finally .................................................................................................. 200

10. .................................................................203

11. , , .
IL DASM .........................................................................211
........................................................................................................ 212
.................................................................................... 214

12. . .............................................223
................................................................................................... 223
IEnumerable IEnumerator ................................................. 229
............................................... 233
IDictionary ............................................................................... 242
..................................................................................................... 254
....................................................................................... 255
Array List<T> ............................................................................. 258
Array ......................................................................................... 258
List<T> ..................................................................................... 271
IList ......................................................................... 277
................................................................. 283
................................................................................................. 286
........................................................... 292

13. ...................................................293
...................................................................................................... 295
................................................................................... 302
- .................................................................................... 306
- ..................................................................................... 308

14. LINQ .........................................311


..................................................................... 312
var ............................................................. 326

15.
Windows ..........................................................................................327
........................................................................... 330
.............................................................. 332
........................................................................................ 333
....................................................................................... 340
............................................ 343

16. - ...............................................349
DirectoryInfo .................................................................................... 350

Directory ........................................................................................... 354


DriveInfo ........................................................................................... 356
FileInfo ............................................................................................. 358
File .................................................................................................... 363
Stream ............................................................................................... 366
FileStream......................................................................................... 367
StreamWriter, StreamReader ......................................................... 369
StringWriter StringReader .......................................................... 378
StringReader ..................................................................................... 384
BinaryWriter BinaryReader ........................................................ 385

17. .............................391
Thread ............................................................................................... 393
.................................... 396
AutoResetEvent ................................................................................. 406
............................................................... 411
Timer ................................................................................................. 413

18. Windows Forms ..........................417


................................................ 420
System.EventArgs System.EventHandler ........................................ 426

................................................................429


C#
, C/C++
, Borland C++Builder
Visual C++. , .
. , , . , .
, , Visual C++
2008. C ,
. - , , ,
, , . Microsoft
! !
. , , , ... ,
. . (2010),
(2012). , . ++, #.
++ -
, ,
++. , , , ,
. , ++, "" C#.
,
-. , Java. , , , ! , Java, , ++, .
C#:
++, Java -

10

C#. ++ .
, . ,
++, C# , . . , ,
, int, float, string, double, ,
, ! , , , , , ,
-, .
, , , .
.
- ,
, .
, (
), , , .
- , , ,
, . . , ... . .
,
, . .

.
. - , , , , . ,
.
C#? ,
, , Windows Forms, ADO.NET .
, , , , . C#
.
, ,
. ,
18- Windows Forms.
C#.



C#
1.

C# .NET

2.

C#

3.

4.

5.

6.

7.

C#
.NET
.NET ( " ") .NET Framework . ,
/ , .
. C#
( " ") .NET.
() () Windows
C ( ""
) Windows, API ( " ",
""). Application Programming Interface . ,
. , "" "", , .
: .
API
, , Borland C++Builder, . ,
C .
- (), -

14

I. C#

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

1. C# .NET

15

-
. , C# ,
, . , C#
C, , Java, Visual
Basic 6. . . , ,
" , ,
, ,
",
C# ,
, Java, , Visual Basic 6,
, C++. Microsoft .NET 4.0 Framework Software Development Kit (SDK)
Visual Studio 2010, .NET C#, F#, JScript .NET, Visual
Basic, C++/CLI. CLI (Common Language Infrastructure, ) C++ .NET. .NET, C#. Windows, , Microsoft,
Windows. Mac OS X, UNIX, Linux. .
.NET
, C#, F#, S#, Visual Basic . Microsoft Visual Studio
(2008, 2010, 2012),
.NET. , .NET,
. , C++ ( ,
, ). , ,
,
, , - ,
, -,
() ( ) ,
,
. , .NET Framework
, .
: (Common Language
Runtime, CLR), , -

16

I. C#

, .NET Framework, ,
, . ( , ),
.NET Framework :
 . -


, . .NET Framework CLR
;
 .

, . .NET Framework .NET Framework, CTS (Common Type System).


.NET Framework;
 .

,
.NET Framework;
 . .NET Framework

, ASP.NET -, ADO.NET Windows Communication Foundation , ();


 . .NET

Framework , , CIL (Common


Intermediate Language),
CLR.
, , ,
,
;
 . , ,

.NET Framework
,
;
 . .NET Framework

1. C# .NET

17

CLR . , , .NET Framework,


;
 .

.NET Framework, (exe- dll-, ), .NET


Framework. , .NET Framework, Silverlight, Windows
Phone 7 Xbox 360.

.NET Framework
.NET Framework, , -
.NET Framework .
Windows, .NET
Framework . ,
, .NET
Framework,
.NET Framework . , .NET Framework.
, - .NET Framework,
,
.
- . ,
.NET Framework. ,

.

.NET Framework
,
.NET Framework, .
.NET Framework
, .NET Framework , .

18

I. C#

.NET
Framework :
1. .NET Framework,
. .NET
Framework 4.5.
2. .NET Framework,
.
Visual Basic, C#, F# C++ Microsoft. , .NET
Framework, Common Language
Infrastructure (CLI). . , . ,
.NET, ( , , , .NET).
3. , . (Integrated Development Environment, IDE) Microsoft .NET Framework Microsoft Visual Studio, , 2010. Express.
, .NET. 2.


C#

C#, , ( )
,
, , .

C#?

WordPad .
C#
cs (" "). . 2.1 2.2
C#- WordPad
.
. ?
Visual Studio 2010 2011 (
2011), Tools
Visual Studio Command Prompt ( exe- ). ,
. C# , csc.exe. <Enter>. ,
.
(, . . ),

20

I. C#

. 2.1. WordPad

. 2.2. WordPad

2. C#

21

WordPad , .
D:. WordPad D:\. TestApp.cs (. 2.2). D:\,
. . 2.3.

. 2.3. C#

. 2.3 ,
, . . .
MS-DOS " D:\". cd ( . change directory).
, . ( , exe) ,
.
C# ,
Microsoft .NET Framework,
. C#, csc.exe (C-Sharp Compiler),
. , , ,
. ,
. , csc.exe, csc /?.
,
C#. -

22

I. C#

. Windows XP
,
Windows 7. , ,
, ( " ")
. . ,

(. 2.4).

. 2.4.

, ,
. ,
( Windows XP), .
Windows XP, ( Windows 7
)
. , Path, ,
. Path
. .NET Framework SDK.
C:\Windows\Microsoft.NET\Framework\v3.5, , C:\Windows\Microsoft.NET\Framework.
C#-
- Visual Studio. , , , .
Microsoft # SharpDevelop.
SharpDevelop , - www.sharpdevelop.com.

2. C#

23

SharpDevelop
Download.
Downloads for SharpDevelop 4.3.
,
C#-. : ,
Visual Studio, .

SharpDevelop

C#
SharpDevelop . 2.5.

. 2.5. SharpDevelop

(Start Page), , Usage Data Collector


SharpDevelop .
, SharpDevelop (
, -

24

I. C#

). Choose Project, , .
, , .

Open solution, . ,
( ).
. 2.6.

. 2.6. Choose Project

Start Page Errors ().


. "
", " ", " ", " "
. , SharpDevelop,
Visual Studio, , ( ),
,
,
. (Dock),
. . . ,

2. C#

25

, .
, Windows,
. ,
. . 2.7.

. 2.7. SharpDevelop

, ,
.
 Float. " ".

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

, View
. (. 2.8).
View , , .
, . , ,
, , View | Show start page.

26

I. C#

. 2.8. SharpDevelop View

 Dock as Tabbed Document. , ,


(. 2.9).
.

. 2.9. Dock as Tabbed Document

2. C#

27

, ,
. SharpDevelop, , , ( Outline
. 2.9). ( ) .
, ,

(. 2.10).

. 2.10. SharpDevelop

, , . 2.10. . ,
,
(. 2.11).
,
, (. 2.12).
.

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

28

I. C#

. 2.11.

. 2.12.

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

2. C#

29

. ,
SharpDevelop,
: ,
.
View .

. 2.13.

, , , C#-, .
SharpDevelop?
, Visual Studio: , solution.
(project), ,
, , (. Project). , , .
, . .
: C# ,
, . , , ,

30

I. C#

. 2.14.


(. 2.142.16).
, ,
, -
, .
(, , ( , , . .
) ,
,

. .) ,
,
, . 2.15.
(. . 2.15), Create (),
( ), ,
Projects (), : Solution app1, app1 (. 2.16).

2. C#

31

. 2.15. .

. 2.16.

32

I. C#

2 SharpDevelop app1.cs.
3.1.
3.1

/* Created by SharpDevelop.
* User: user
* Date: 09.11.2012
* Time: 14:56
*
* To change this template use Tools | Options |
* Coding | Edit Standard Headers.
*/
using System;
namespace app1
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

34

I. C#

, ,
, .
. , . -
.
, /*, */ , , SharpDevelop, . .
, ,
"".
, : //. /*...*/.
. , , ,
, . , .
(
) using System;. ,

, . , - , , . . System ,
System . , Console,
-, . . -
, ,
.
namespace
app1, (). , ( ).
namespace,

3. ,

35

: . ,
(
),
. .
, namespace app1, (
), class Program. C# ,
, , ,
( public static void
Main(string[] args)) ,
. , ,
: ( ).
, , , , , , " ".
.
Main. . Main

"". , ,
.
,
. Main , . . , ,
,
, ( ) . , Main, , . Main() ,
.
( Main()) .
. , , ,
Main():
public static void Main()

"" .

36

I. C#

Main(), ( ):
Console.WriteLine("Hello World!"); //
// "Hello World!"
// TODO: Implement Functionality Here
// ,
// , . .
Console.Write("Press any key to continue...");
/* "Press any key to
continue... " ( ) */
Console.ReadKey(true); //

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

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

Console, System. (
), -,
Console. . -
(. . - ).
:
 WriteLine( )

: , , , , . "

3. ,

37

" ,
: ,
, . . .
 Write( ). , WriteLine(),

.
,

. .
 ReadLine(). (:

, <Enter>).
( . ).
 Read(). .

(
. ).

, ( ).
, , , . .
: , .
. . . . , .
. . . .
.
. , ? , . ,
, (, , ,
. .). . .
, , . .
:
, ( : ,

38

I. C#

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


. 3.1 :
, .
3.1. C#

()


(

)

sbyte

128 +128

sbyte

byte

0 255

byte

short

32 768 +32 767

short

ushort

0 65 535

ushort us=12;

int

2 147 483 648 +2 147 483 647

int i=-14;

uint

0 4 294 967 295

uint ui=14;

sb=12;
b=12;
si=-12;

3. ,

39
3.1 ()

(

)

()

long

9 223 372 036 854 775 808


9 223 372 036 854 775 807

long lg=-14;

ulong

0 18 446 744 073 709 551 615

ulong

ul=14;

- .
sbyte .
( ) (). 8 (). ,
, 27, . . 128 ( ).
.

u unsigned, . . .
. , , . .
. . 28 1 =
= 256 1 = 255. 28 1?
1, 1 (
).
, , .
,
.
, :
_ _

, . . . =,
:
. . .

, . "", . , . , m > n .

40

I. C#


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

: . .
. , 125,5 0,1255103.
0,1255 , 3 . :
. ,
.
: float double. float
, double . , , . . . ,
. . , - "", , . . ,
, .
. . ? , : ,
(, ,
,
), .
, .
. float -

3. ,

41

67 , double
1516 . , . . ,
, , . , 125,5. , . ,
125,500001. - . 125.5,
, . . , , .
, . , 125,500001
flo. , ,
: float flo = 125.5;. : float flo;
flo = 125.5;. flo 125,5 : (flo-125.5)<0.01, .


, , , . . , , ,
,
, . , ,
- . ,
. , , ,
, . , . . ?
. : ,
, . . , . ,
. . , , ,
, . .
. , - ,
, : ,
, , ,
. decimal (). : , .

42

I. C#

. . , , , ,
.
,
, . . - . :
_

, :
decimal d1;
decimal d2 = 2;
decimal d3 = 2M;

d1 . ( - , . . , - ). , ,
, . . ,
, .
. C#
(, - , )
,
. ,
. ,
d1 . . 3.1.
, a , . b=a;,
. a , . decimal d2 = 2;
, . , 2 int,
int
decimal. .
decimal d3 = 2M; . M 2 ,
decimal.

3. ,

43

. 3.1. decimal-


, ,
. , , . .
.
. . .
:
= (5 / 9) * (F 32)

, F .
: 0, 20, 40, ..., 300.
.
* .

44

I. C#

:
1. . . , Main() , SharpDevelop . , Save, Save All File .
( 3.2).
3.2

/* Created by SharpDevelop.
* User: user
* Date: 09.11.2012
* Time: 14:56
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
namespace app1
{
class Program
{
public static void Main()
{
Console.WriteLine("
:");
Console.WriteLine(" ");
int lower, upper, step;
double fahr, cels;
lower=0;
upper=300;
step=20;
fahr=lower;
while(fahr <= upper)
{
cels=(5.0/9.0)*(fahr-32.0);
Console.WriteLine("{0:f}
{1:f}", fahr, cels);
fahr=fahr+step;
}

3. ,

45

Console.Write(" >");
Console.Read();
}
}
}

2. .
<F8>. Build
SharpDevelop Build Solution.
"" <F8>, . . ,
,
. <F8> ,
"Build finished successfully" (" "), . . exe-
. ""
<F5> (. 3.2). : Debug | Run.

. 3.2.

Debug . .

46

I. C#

. , ,
, . ,
, .
<F5>, .
, :
( ).
- ,
. , . , ,
. ,
<F10>.
( ), , <F10>, . ? ? ,
, <F10>, <F11>.
. ,
<F10>. "" Debug SharpDevelop.
, , .
Errors . Line , ( )
. .
http://msdn.microsoft.com/ru-ru/library/ms228296.aspx.
(. 3.2).
WriteLine(),
.
, . "
", ?
,
-. Console.Read(), , ,
. , ,
Console.WriteLine(), , , .
.
int lower, upper, step;
double fahr, cels;

3. ,

47

, .
, ( ,
, , ) , . int . ,
.
( , ).
.
,
, .
, .
.
fahr, cels (
) .
, .
float? float,
: ,
(5 9 ).
, /.
: , . 5:9 ,
( ), . -
. : , ,
, , . float, double.
. (, , fahr cels float) fahr (
float) 32.0 ( double ,
double). ,
float double.
.

-

48

I. C#

. while , .
, , while.
while, . , (
, while)
. : fahr <= upper. , , while .
? , fahr
, . while fahr = lower;. (=
, ) fahr. while: cels
,
(. . ) , fahr
, while. , fahr upper. , while.
(, fahr . ,
fahr), , while.
, ,
: , . . , , 0 .
.

Console.WriteLine("{0:f}

{1:f}",fahr,cels);

WriteLine(), Console, fahr cels , -

, () .

3. ,

49


"{0:f}

{1:f}"

, .
, 0 1,
,
.
( ) fahr, cels. cels, fahr, 0 1, 1 0.
. f . , , .
:
. . 3.2.


, . 3.3.
. : True () False ().
. ? , /++.
: 1 0.
. ?
. 3.3. while , ,
while, .
, . ,
. 3.3. , , while, ? , , . while ,
. . 3.3 ,
while b, (
""). ( )
, 29,
b. b .
True. , .

50

I. C#

. 3.3. bool

for
while, for.
( 3.3).
3.3

/* Created by SharpDevelop.
* User: user
* Date: 12.11.2012
* Time: 12:05
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;

3. ,

51

namespace app2
{
class Program
{
public static void Main()
{
Console.WriteLine("
:");
Console.WriteLine(" ");
int fahr;
for(fahr=0; fahr <= 300; fahr= fahr + 20)
Console.WriteLine("{0:f}
{1:f}", fahr,
(5.0/9.0)*(fahr-32.0));
Console.Write(" > ");
Console.Read();
}
}
}

, ,
for. , while, ().
for Console.WriteLine(...),
( while ,
).
, . for ,
, ,
for ( ,
). ,
" fahr": ,
( , fahr , 300),
.
: (. . ), . , (
Console.WriteLine(...)),

52

I. C#

for.
( ) . , , . .
, for
, , . . (
Main(), Main()).

Console.WriteLine(...).
, ,
. , : " , , ".
3.3 , 3.4.
3.4

/* Created by SharpDevelop.
* User: user
* Date: 12.11.2012
* Time: 12:41
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
namespace app3
{
class Program
{
const int upper = 300;
const int lower = 0;
const int step = 20;
public static void Main()
{
Console.WriteLine("
:");
Console.WriteLine(" ");

3. ,

53

int fahr;
for(fahr=lower; fahr <= upper; fahr= fahr + step)
Console.WriteLine("{0:f}
{1:f}", fahr,
(5.0/9.0)*(fahr-32.0));
Console.Write(" > ");
// Press any key to continue...
Console.Read();
}
}
}

? for
,
Main().
. ? . , , .
, , . ( ) . , (. .
), , - ,
, . ?
, .
. , ,
, (, ),
. const int
upper = 300; ,
. Program,
.
, while
do while. , while,
: while , ,
. : , . ,
while,
.
do while.

54

I. C#

:
do
{
//
}
while ();

, ,
, , while .


, , , .
.
. "":
, () , , ,
. .
.
128- . , . , 256 ( ,
128 , 256 ). , ,
ASCII ( ,
) 256 .
.
. 00000000 11111111. 128,
. ASCII
128 , , . IBM, ,
.
, 128- , .
. , , , . , .

3. ,

55

,
, , , .
: The Bat!
, .
, . , 8- () .
, , ,
(16 ). Unicode.
Unicode 16 ,
65 536 .
, , .
49 . .
C# :
. char, string. , ,
. , ,
.
.

char
char (,
Unicode). :
_

, char c;. (. .
),
, ( ):
char c='a';

,
. . ,
( ). , ,
.
.
char c='a'; () .

56

I. C#


( ), . -
(,
). Unicode . 3.4.

. 3.4. Unicode

.
32- .
: , . .
char , ,
, .
esc- (
). , , , .

3. ,

57

char MyChar = '\x0058'; , MyChar


( ) 0058
( X, . 3.5).

. 3.5. Unicode

, ,
.
, , (. 3.6).
char , char:
char MyChar = (char)88;

88 (, 88) char : (char). , ,

58

I. C#

. . ?
Unicode . 88 . ,
, Unicode.
88 58 (
, Windows).
, .

. 3.6.

char
: char MyChar = '\x0058';.
:
char MyChar = '\u0058';

u (\) Unicode.
char ushort, int, uint, long,
ulong, float, double, decimal. . 3.7.
.
.

3. ,

59

. 3.7. char

Unicode

, ,
. . 3.2.
3.2. Unicode

'\\'

'\0'

'\a'

()

'\b'

( )

'\f'

form feed ( )

'\n'

'\r'

'\t'

'\v'

'\u'

Unicode-

60

I. C#
3.2 ()

'\''

( ),

'\"'

( ),

string
() , . :
____

:
string s;

s (),
char, , , , , .
,
string s="";
string s="a";
char c='a';

s a , ,
-. .
, ,
s a . a
, , . s?
: -
( , ) :
string s="a";
int n=s.Length;

Length ( ) ,
s.
.
int
n=s.Length;. n .
n. ? ! ,

3. ,

61

n , s. , ++, . . , ,
char string.

, , , . ,
Unicode. ? "" " ".
string s=""; ( ), s "". , . , . , string
s="";. , n=0. , " ", string / . , .
,
. , . -.
. , ,
: ,
, .
( , ,
string)
, , , . , ,
, . . ,
, Unicode string,
, . . , (
, ), , , .
:
. :
, . , , , , , .
( ) char, .
: == (), != ( ), +
( ()).

62

I. C#

,
string a = "hello";
string b = "h";
b = b+"ello"; //
// b
Console.WriteLine( a == b ); //
//

True.
:
string s=" " + "";
bool b = (s == " ");

, , b True. , WordPad
SharpDevelop: .
, .
string :

@. ,
. ,
string a = "\\\u0066\n";

, . , @,
. :
string a = "\\\u0066\n ";
string b=@"\\\u0066\n ";

: a="\f\n ", b=\\\u0066\n .

string
string, string s;,
, C#
string ( String,
), . s
( / ). , s (. 3.8).

3. ,

63

. 3.8.



app4.cs . , , () Solution, File | New |
Solution | Console Application
,
. Create ()
. Main(),
. , 3.5.
3.5

/* Created by SharpDevelop.
* User: user
* Date: 14.11.2012
* Time: 10:51
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;

64

I. C#

namespace app4
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine ("=> string");
string firstName = "";
Console. WriteLine(": {0} ", firstName);
Console.WriteLine(" {0} .", firstName
.Length) ;
// firstName
Console. WriteLine(",
: firstName.ToUpper ());
// firstName
Console.WriteLine(",
:{0}", firstName.ToLower ());
// firstName
Console.WriteLine(" ? :
{0}", firstName.Contains(""));
//
Console.WriteLine(" :
{0}", firstName.Replace ("", ""));
//
Console. WriteLine("
>");
Console.Read();
}
}
}

.
(). ,
, , "",
"" "".
<F8>, <F5>.
. 3.9.
, ,
. , WriteLine() , , .

3. ,

65

. 3.9.


, ( ),
( ).
3.6. . 3.10.
3.6

/* Created by SharpDevelop.
* User: user
* Date: 14.11.2012
* Time: 12:28
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
namespace app5
{
class Program
{
public static void Main(string[] args)
{
//
Console.WriteLine(" .
<Enter> >");

66

I. C#
string s = Console.ReadLine();
Console.WriteLine("{0}",s);
Console.WriteLine("

>");
Console.Read();

//

}
}
}

. 3.10.

, ReadLine(). . - , s "" s. <Enter>, . s .


. 3.10, . ,
ReadLine() string-.


. ?
, <Enter>,
<Enter> . . , .
?
, ,
, . 3.5. , . ++
( <Ctrl>+<Z>)
. -

3. ,

67

C#. :
ReadLine() <Ctrl>+<Z> null. , , . 3.7. . 3.11.
3.7

/* Created by SharpDevelop.
* User: user
* Date: 14.11.2012
* Time: 13:20
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
namespace app6
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" .
<Enter>");
Console.WriteLine(" <Enter> <Ctrl+z> ");
string s="";
while(s != null)
{
s=Console.ReadLine();
//
Console.WriteLine("{0}",s);
}
Console.Write(" > ");
Console.Read();
}
}
}

, , :
.

68

I. C#

, . ,
. ,
. .
,
^z ( <Ctrl>+<Z>).
ReadLine() null ,
while .

. 3.11.


.
3.8.
3.8

/* Created by SharpDevelop.
* User: user
* Date: 14.11.2012
* Time: 18:12
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
namespace app7
{
class Program

3. ,

69

{
public static void Main(string[] args)
{
//
Console.WriteLine(" , <Enter>");
Console.WriteLine("
<Enter> <Ctrl+z> >");
string s="";
int kol=0;
while(s != null)
{
s=Console.ReadLine();
kol++;
}
Console.WriteLine(" ={0}",--kol);
Console.Write(" >");
Console.Read(); //
}
}
}

.
kol.
? .
. . kol,
. kol++. .
: ++kol. :
. , . , . , . .
<Ctrl>+<Z>.
, . .
,
. kol.
kol--. , , ( ) -. , - , .

70

I. C#

,
, kol . kol. kol , . kol--, kol, . . 3.12.

. 3.12.



3.9. . 3.13.
3.9

/* Created by SharpDevelop.
* User: user
* Date: 14.11.2012
* Time: 19:17
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app8
{
class Program
{
public static void Main(string[] args)

3. ,

71

{
//
Console.WriteLine(" \n");
Console.WriteLine(" , <Enter>");
Console.WriteLine("
<Enter> <Ctrl+z> >\n");
string s="";
int w=0;
int ind=-1;
int ind1;
while(s != null)
{ s=Console.ReadLine();
// ,
// .
//
//
while((s!=null) && (ind != (ind1=s.IndexOf(" "))))
{ w++;
s=s.Substring(ind1 +1);
}
w++; //
}
Console.WriteLine(" {0}", --w);
Console.Write(" >");
Console.Read(); //
}
}
}

. 3.13.

72

I. C#

. ,
. :
, .
s.IndexOf(" "),
.
, 1.
s.IndexOf(" ") 1 int ind=-1;.
, , , s.
s ,
. . ,
w . ,
, w ,
, .
, .
&& " ". , . . , while
, : "
<Ctrl>+<Z> ,
while". . ,
WriteLine() '\n' .

, .
"":
,
. . ,
, .

var
Visual C# 3.0, var.
, , . i :

3. ,

73

var i = 10; //
int i = 10; //

, var i;,
i=10;, i int. i="";, i string.
var i = DateTime.Now;, i DateTime (-, ).





C# .
int n, , n+1 int. 1?
,
, 5 , : 5.0.
, ( )
. .
, ,
int. ,
, long.
double.
C# () . . 3.3 , . .
1u 1U, , .
3.3.

1.0

double

1.0F

float

decimal

74

I. C#
3.3 ()

true

bool

false

bool

''

char

'\n'

char ( )

'\xl231'

char ( 123)

"My_string"

string

""

string ( )

.
float, f
. , float d=1.2f;. ? f,
, . .
double, a double float , .



.
, ,
. , :
int a;
float b;
double c;
c=a+b;

,
.
,
, ,
. , ,
, . , .
(

3. ,

75

).
, . , ,
.
int
long. , . . int long, . C# .
.
, long,
int ( ). , ,
, int long, . ,
,
,
( ), : (), , , . , : int a;
long b;. a=b; . a=(int)b;
. (int) int
long.
.
float double. ,
, long. , float
aa=(float)1.2; , float aa=1.2; , 1.2
double.

,
. , double b=1.2; long a=12;
a=(long)b; , a=b; . , , , .
.
decimal .
.

76

I. C#

C# ,
"". ,
True bool "True".
: string int double Convert, , (
, ). .


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


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

+ ()

- ()

+ ()

- ()

3. ,

77
3.4 ()

:
int a=1;
int b=-a;

: b=-1.
, ,
.
.
,
. . . , ,
, . , . 25/4 6. . ,
, ,
. ,
int a=1;
double b=a/2.0;

: b=0.5.
int a=1;
double b=a/2;

.

. 2 2,
10 10 . .
, . .
. , ,
float a=1.2f;
float b=0.5f;

float c=a%b; : =0.2. :


int a=12; int d=7; int c=a%d;

=5.

78

I. C#


, :
? # ,
, -
( ). ,
int a=2 + 3 * 4;

: a=14.
,
(*, /, %), .
- , .
, , .



. : . . , C#
. ,
int a; int b; int c;, a=b=c=2;. . C# :
< > <> < >
< >

. 3.5.
3.5.

a += b

a = a + b

a b . a

a -=

a = a b

a b. a

a *=

a = a * b

a b. a

a b. a

/= b

a %= b

= a / b

a = a % b

a b. a

3. ,

79


, , 1 . : int n; n=n+1;. n=n-1;.
, ,
: n+=1;. n-=1;. C# :
: ++n; n++; --n; n--;. n , n .
,
. , , . , n, ++n; n++; (
). int a=++n; a=n++;,
, . . n
. a=++n; n ,
n , a=n++; : n , .


: (==), (!=),
(>), (>=), (<), (<=).
char , . . . True False, bool. ,
int b; int c;
bool a = b < c;

b c,
a=True, a=False.
char:
char A='A'; char a='a';
bool b= A < a;

,
b=True. , Unicode .

80

I. C#


bool ,
. 3.6.
3.6.

True,
. False

!a

a=False

a & b

a=True b=True

a | b

a b True

a ^ b

a=True b=False a=Fale b=True

a && b

a=True b=True

a || b

a b True

.
bool r, a=true, d=true, c=false, e=false;
r=!a;
// r=False
r=a&d;
// r=True
r=a&c;
// r=False
r=c&e;
// r=False
r=a|d;
// r=True
r=a|c;
// r=True
r=c|e;
// r=False
r=a^d;
// r=False
r=a^c;
// r=True
r=c^e;
// r=False
r=d^c;
// r=True
r=a&&d;
// r=True
r=a||d;
// r=True
r=a&&c;
// r=False
r=a||c;
// r=True

. :
( "" (|, ||)), ( ""
(&, &&)) " " (^). ,
, , . , ,

3. ,

81

. , , .
(!) . : True False, False True.
&&, &, || |? ,
C# : ++, , , . ,
. ,
, . , ,
. ,
. , False,
, False.
: True, ,
. ?
.
- C# ?
, C++. , & ( "", ) . , , , . . :
, . , :
int a=5;
int d=3;
int r=a&d;
// 5 & 3 = 1

? 5=101 , . . .
3=011 . :
101
011
-----001=1

82

I. C#

| ( "", )
. , . , :
int a=5;
int d=3;
int r=a|d;
// 5 | 3 = 7 :
5=101
3=011
-----111=7

, &, | ,
. ? :
int i = 0;
bool d=true;
if (d & ++i == 1)
{
i++;
}

: i=2.

.


: (<<) (>>).
- -. -
, . . ,
, , 0, .
, ( , ). , -

3. ,

83

, , , .
(<<) a<<b
, . int , int.
int uint (32- ),
.
0 31 . long ulong
(64- ), . 0 63 . ,
, , .
.
:
int r, a=5, d=3;
r=a << d;

: r=40.
. a=5=101 .
3 . a=101000.

: 101000 = 125 + 024 + 123. .
. 32 + 8 = 40.
(>>) a>>b
, .
int uint (32- ),
:
_ & 0x1f . : & , 0 , , 1f 11111. long
ulong (64- ),
( & 0x3f = 111111 (3=11
f=1111)).
:
int r, a= 40, d=5;
r=a >> d;

: r=1.

84

I. C#

. .
. , 40 101000. 5 . "". 1.
r<<d; r>>d;.
, r=r<<d; r=r>>d;.
(
, ).
:
int i = -40;
Console.WriteLine(i >> 5);

: 2.
? , .
.
.
.
1. , , ,
( ) () , 0, .
2. , , , , , ( , ), 1. () , 1,
1.
. 5,
, . 5,
(. . ): 101. , : 010. 1.
011. .
1011. 5.
40 101000. : 010111.
1. 011000.
. : 1011000.
5 . : 10. .
2. "". 2.


. ,
. ,

. , - , . .
, , ,
, , ,
,
. ,
, .
.
y = f(x1, x2, ..., xN),
{x11, x21, ..., xN1} y1 = f(x11, x21, ..., xN1).
, x1, x2, ..., xN f(), a x11, x21, ..., xN1 . # :
( , int, float, long . .; ,
, , );
( ). ,
, . .

86

I. C#

# void,
. ( , ) , .

,
, .
, :
float salary(int TabNom, int Mes)
{
/*
*/
return( );
}

float, . .
, . salary. :
, . return(), . ,
, . :
float y; y=salary(1001,12);

float y=salary(1001,12);

int tn=1001; int ms=12;


float y=salary(tn,ms);


.

?

, .
, , ,

4.

87


,
.
, , - .
.
.
, ,
, ,
. , , , ,
(. .
"" , ). "",
. , "",
. ,
.
: (. . ), , ,
, . float
y=salary(tn,ms), TabNom
Mes tn ms. , tn
ms . ,
, , , .
, , (
). ,
,
.
. ref.
,
float func(x1, ref x2);

, , out:
static void func(double a, out string x1, out int x2);

88

I. C#


, .
C#
params . ,
, params,
.
( ).
params.
C# . ,
, . . . , ,
. . : ,
. . ,
(, ) , . , ""
" " (. . ) ", ", ,
. ,
, . , . , , -
. ?
: (
). Calculate().
(weight) ,
(height).
:
Console.WriteLine(Calculate(70, 164));

, , ,
, . , :
Console.WriteLine(Calculate(height: 164, weight: 70));

4.

89

, ,
:
(. . , , . .
):
Console.WriteLine(Calculate(70, height: 164));

:
static int Calculate(int weight, int height)
{
return (weight * 703) / (height * height);
}

C#
. ,
(
,
, , , ), ,
, . :
void func1(string val1 = "val", int val2 = 10,
double val3 = 12.2)

func1(,,25), , , : func1("val",10,25).
C# , , .
- . , Main() Program (
). "" . .
-
Program, static,
, , , ,
( static ,
C#

90

I. C#

: ,
,
).


,
, 4.1.
4.1

/* Created by SharpDevelop.
* User: user
* Date: 15.11.2012
* Time: 11:15
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app9_func
{
class Program
{
static string str;
// lim
//
// 0,
static int getline(ref string s,int lim)
{
int i; //
s=Console.ReadLine();
i=s.Length;
if(i > lim)
i=0;
return(i);
}

4.

91

public static void Main(string[] args)


{
Console.WriteLine(" " +
" \n");
int lim=10;
Console.WriteLine(" >\n");
int i = getline(ref str,lim);
Console.WriteLine(" : {0},
{1}", str, i);
Console.WriteLine(" " +
" > ");
Console.Read(); //
}
}
}

getline() : string
s, int lim. , , .
:
getline() getline(),
. Main(),
Main(), , , -,
. -
,
(. . ), ,
, , , .
, ,
lim. , -
? ,
, , ,
, -.
ref ,
,
,
ref,

92

I. C#

. , , ,
.
-
. str,
getline(), static. ,
, -
, . getline()
: ReadLine() str. i. , ,
lim. lim
( , , . . : Main(),
getline(); , ),
lim getline()
.

. 4.1.

4.

93

, lim, i ,
.
getline() . 4.1.

if
if.
.

, , .
if. , . if ,
while ,
, . , while,
, , ,
, . ,
if(-)
{

}

.
else. , if, if.
if: if ,
else . : " if , if, else".
if else.
if...else . ,
a, .
:
if (a == a1)
1
else if(a == a2)
2

94

I. C#

else if(a == a3)


3
...

- else if if, ,
, .

goto

. , if...else. , .
( ) , .
( ). : m:, N:, _12.
. ,
(), . :
goto m;
goto _12;

, . . ( ), if...else
(if() goto m1; else goto m2;). . goto for, switch, while. , break ( :
), goto ,
- .
,
: ""
. , . , .


substr(), ,
, ,
.

4.

substr() 4.2.
4.2

/* Created by SharpDevelop.
* User: user
* Date: 15.11.2012
* Time: 14:10
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app10_substr
{
class Program
{
static string substr(string s, int i, int count)
{
int j=0;
string r = s.Remove(j, i-1);
int par1=count;
int par2=(s.Length-i)-(count-1);
string r1=r.Remove(par1,par2);
return(r1);
}
public static void Main(string[] args)
{
string s="";
while(true)
{
Console.WriteLine(" >");
s=Console.ReadLine();
if(s == null)
break;
Console.WriteLine(" " +
" >");

95

96

I. C#
string r=Console.ReadLine();
int i=System.Convert.ToInt32(r);
Console.WriteLine(" " +
" >");
r=Console.ReadLine();
int j=System.Convert.ToInt32(r);

Console.WriteLine(" c {0} {1}


\n: {2}",i,j,substr(s,i,j));
Console.WriteLine(" " +
" > ");
// Console.Read();
} // while
}
}
}

substr() (
string), s
: ,
, (count).
Remove(), , substr(), . , : 0, 1 . .
, .
.
Main() .
, while, . while true.
, while ,
. :

<Ctrl>+<Z>, null.
, .
if(). if , while. break,
if. .
"" continue. , break,

4.

97

.
Convert(). ( ),
. ( int).
string int.
System.Convert.ToInt32().
. 4.2.

. 4.2. substr()


MyCopy() 4.3.
4.3

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 15.11.2012
Time: 17:22

98

I. C#

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
namespace app11_copy
{
class Program
{
// ------------------------ substr() --------------static string substr(string s, int i, int count)
{
int j=0;
string r = s.Remove(j, i-1);
int par1=count;
int par2=(s.Length-i)-(count-1);
string r1 = r.Remove(par1,par2);
return(r1);
}
// ------------------------------------------------static string inp,ou;
static string MyCopy(string inp, ref string ou,
int i, int count)
{
/* ou inp i
count :
inp count */
// :
int j=1;
inp=substr(inp,j,count);
string r=ou.Insert(i-1,inp);
return(r);
}
public static void Main(string[] args)
{
Console.WriteLine(" , " +
" >");

4.

99

ou=Console.ReadLine();
// ou="0123456789";
string s="";
while(true)
{
Console.WriteLine(" >");
s=Console.ReadLine();
if(s == null)
break;
Console.WriteLine(" " +
" >");
string r=Console.ReadLine();
int i=System.Convert.ToInt32(r);
Console.WriteLine(" " +
" >");
r=Console.ReadLine();
int j=System.Convert.ToInt32(r);
Console.WriteLine(" c {0} {1}
\n: {2}",i,j,MyCopy(s,ref ou,i,j));
// Console.WriteLine("
> ");
// Console.Read();
} // while
} // Main()
} // class
} // using

(substr()), , : i
count .
MyCopy() substr(), MyCopy() Program.
Insert(),
string. ,
,
string.
. 4.3.

100

I. C#

. 4.3.


, .
out. , ,
.
4.4,
. 4.4.
4.4

/* Created by SharpDevelop.
* User: user
* Date: 16.11.2012
* Time: 12:58
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;

4.

101

namespace app12_out
{
class Program
{
static void func1(double b, out double f, out int i)
{
f=b;
i=(int)b; //
}
public static void Main()
{
Console.WriteLine(" >");
string s=Console.ReadLine();
double f,b;
int i;
b=System.Convert.ToDouble(s); //
//
func1(b,out f, out i);
Console.WriteLine(" : f={0}, i={1}", f,
i);
Console.Write(" " +
" > ");
Console.Read(); //
}
}
}

. 4.4.

func1() , . .
void.
, out.

102

I. C#

double int (
, , ;
)
string double. , ,
. ,
( )
, ,
.

switch

if...else, , .

switch .
.
: a b. 4.5.
4.5

/* Created by SharpDevelop.
* User: user
* Date: 20.11.2012
* Time: 7:59
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app14_switch
{
class Program
{
/* , a b */
static void CountSimb(string c, out int v_a,
out int v_b)
{
int a=0,b=0;

4.
switch(c)
{
case "a":
a = 1; /* v_a
v_b :
*/
break;
case "b":
b = 1;
break;
default: /* -
( a b) */
break;
} // switch
v_a=a;
v_b=b;
}
public static void Main()
{
string s;
int v_a,v_b;
while(true)
{
Console.WriteLine(" , <Enter> >");
s=Console.ReadLine();
if(s==null) // <Ctrl>+<Z>
break;
CountSimb(s,out v_a,out v_b); //
//
// 'a', 'b'
Console.WriteLine(" = {0}, " +
" b = {1} ", v_a,v_b);
Console.WriteLine(" " +
" > ");
Console.ReadLine();
}
}
}
}

103

104

I. C#

switch CountSimb(), : v_a v_b. ,


( , ).
: ,
,
. .
,
case, , case. case,
,
, , case. . :
, , ( "a" "b"). , , , 'a' 'b'. , , , 1
2, 123. .
case ( ) , , ,
switch ,
case. , ,
case. case
break, switch
,
switch.
case,
, switch. , , ,
4 (. . , ), , ,
case "a":, case "b":, case "c":, case "d":
case . case
break, ""
case, . ? ,
, - , "", "b", ""? break
: case, ,
( case),
case ,
"" break.

4.

105

switch default, case.


switch-. , case.
" ".
:
( out) switch:
, , .
while. , . . while true ( ). break,
<Ctrl>+<Z>. . 4.5.

. 4.5. switch


, ,
"", "" .
, .

106

I. C#


, .
? ,
.


,
.
,
(. . ) . "" ( ) .
, ,
: n! = (n 1)! n, 0! = 1.
n, , n 1. , , 4.6.
4.6

int fact(int i)
{ if(i==0)
return(i+1);
else
{ i=i * fact(i-1);
return(i);
}
}

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


(
).
. . ( ).
,
. .
. ,
100 . 100. (. . ) 0 99.
,
, . -

108

I. C#

, ,
. ,
, .
. ,
, . .
, , . .
: ,
, . . ,
. . ,
, .
, ,
,
, . ,
: ( )
.
(. . ). , , . - . . . .
.
. ,
, , . ,
: -
, - (. .
).
? :
_

, ,
, . ,
int []m;

, , int
,
4 , m ,
.

5.

109

, , ,
, , : . ,
, . : . . , :
int []m = {1,2,3,4,5};

m :
. ( ) 1, 2, . . (), (
, . . ) m.
new ( ,
,
):
int []m = new int[5]

new , ,
int, m. , , .
- ,
-
. .
5.1,
. 5.1.
5.1

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 21.11.2012
Time: 12:32
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

110

I. C#

using System;
namespace app15_array
{
class Program
{
public static void Main(string[] args)
{
string []A = new string [10];
string s;
int i=0;
Console.WriteLine(" , " +
" <Enter>, <Enter> <Ctrl+z>");
while(true)
{
s=Console.ReadLine();
A[i]=s;
if(s==null || i > 10)
break;
i++;
}
Console.WriteLine(" {0}",i);
Console.Read();
}
}
}

. 5.1.

.
, new. , ,
,
<Ctrl>+<Z> (. || if)

5.

111

( i) ,
new.
, : ( ). A[i]=s; ,
i- A s.
, , int[]
u,v;. :
int [,] w = new int[3,5];

, , .

foreach
( " ") , . ,
for. . for. . ,

foreach(int item in m)
{

: " item m ".


m item ( ,
int).
5 int.
.
5.2. . 5.2.
5.2

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 21.11.2012
Time: 13:40

112

I. C#

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
namespace app16_foreach
{
class Program
{
public static void Main()
{
int []A = new int [5];
string s;
int i=0;
Console.WriteLine(" , " +
" <Enter>, <Enter> <Ctrl+z> ");
while(true)
{
s=Console.ReadLine();
if(s==null || i > (A.Length-1))
break;
A[i]=Convert.ToInt32(s);
i++;
}
Console.WriteLine(" {0}",i);
i=0;
foreach(int j in A)
i += j;
Console.WriteLine(" = {0}",
i);
Console.Read();
}
}
}

, .
. , .
if, ,
. ,
<Ctrl>+<Z>, ,

5.

113

. . , ,
, , (Length). . , foreach . ,
foreach (, ). , ,
, , .

. 5.2.


. :
<>[, ...,] < ( )>;

, ,
.
[,], [,,] . .

114

I. C#


( ):
int[,] m = {{1,2},{3,4}};

.
Array , , ,
, List<>, , .
.
, .


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

, (. . ),
< > = Console.ReadLine();

,
Convert.
 :
< > = Convert.ToInt32(<
>);
< > = Convert.ToInt64(<
>);
< > = Convert.ToByte(<
>);

 :
< > =
Convert.ToDouble(< >);

 :
< > = Convert.ToBoolean(<
>);

116

I. C#

 :
< > = Convert.ToChar(<
>);

:
int x;
double y;
string s;
s = Console.ReadLine();
x = Convert.ToInt32(s);

:
y = Convert.ToDouble(Console.ReadLine());

,
Console.Read();.

Console.Write() Console.
WriteLine(). , , , .
,
.
:

. ,
.
Console.WriteLine()
Console.Write(), .
6.1, . 6.1.
6.1

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 18.11.2012
Time: 13:37

6. -

117

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
namespace app13_for_all
{
class Program
{
public static void Main()
{
string s=" ";
int y=2;
int i=2;
Console.WriteLine(s);
//
Console.WriteLine(55.3); //
Console.WriteLine(y*3+7); //
Console.Write(s);
//
Console.Write(-5.3);
//
Console.WriteLine(i*3+7/i); //
Console.Write(" " +
" >");
Console.Read(); //
}
}
}

,
( ).

. 6.1. , 6.1

118

I. C#

-, (
)
: .

, '\n', .
,
Console.Write("aaaaaa\nbbbbbbb\nccc\n");

:
aaaaa
bbbbbbb
ccc

.
.
.
String.Format().
.
( Console.WriteLine(), Console.Write())
, Console.WriteLine():
Console.WriteLine(" ", 1, 2, ...,
n);

:
<>< ><><
>...<>< >

" ". :
{N,M:Axx}

N
( 0). {0}, ,
1,
. M , . ,
1500. =6,
1500. M , (
, , -

6. -

119

), . ,
, , .
, , 1
(
):
" 1 : {0,6}", 1
Axx ,
, ,
. .

. 6.1 .
: Axx, A
, xx . , ,
.
6.1.

C c

Console.Write("{0:C}", 2.5);
Console.Write("{0:C}", -2.5);
// $2.50 ($2.50)

D d

Console.Write("{0:D5}", 25);
// 00025

E e

Console.Write("{0:E}", 250000);
// 2.500000E+005

F f

Console.Write("{0:F2}", 25);
Console.Write("{0:F0}", 25);
// 25.00 25

G g

Console.Write("{0:G}", 2.5);
// 2.5

N n

Console.Write("{0:N}", 2500000);
// 2,500,000.00

120

I. C#
6.1 ()

X x

Console.Write("{0:X}", 250);
Console.Write("{0:X}", 0xffff);
// FA FFFF

C# , "-"
(DateTime). ,
. d
/: DateTime d;. d ,

(. 7.1).

. 7.1. SharpDevelop DateTime

,
. , . . . .
DateTime .
DateTime - ,

122

I. C#

. C#
, . ,
new
. , new
, , .
. DateTime
,
int year, int month, int day, . . , .
,
DateTime (- , - , . .). ,
DateTime dt = new DateTime(2012,11,22);

dt, 22 2012 .
DateTime : DateTime c
Now, .
:
DateTime MyDate = DateTime.Now;

, MyDate , ,
: 22.11.2012 14:35:22. , , "::".


7.1 , .
. 7.2.
7.1

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 22.11.2012
Time: 14:46

7.
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app17_DateTime
{
class Program
{
public static void Main()
{
DateTime data = DateTime.Now;

//
//
int i=30; //
// ( )
int j=20; //
Console.SetWindowSize (i,j); //
//
Console.Clear();
//
Console.WriteLine("d: " + data.ToString("d"));
Console.WriteLine("D: " + data.ToString("D"));
Console.WriteLine("f: " + data.ToString("f"));
Console.WriteLine("F: " + data.ToString("F"));
Console.WriteLine("g: " + data.ToString("g"));
Console.WriteLine("G: " + data.ToString("G"));
Console.WriteLine("m: " + data.ToString("m"));
Console.WriteLine("r: " + data.ToString("r"));
Console.WriteLine("s: " + data.ToString("s"));
Console.WriteLine("u: " + data.ToString("u"));
Console.WriteLine("U: " + data.ToString("U"));
Console.WriteLine("y: " + data.ToString("y"));
Console.WriteLine("H:mm: " + data.ToString("H:mm"));
Console.WriteLine("HH:mm: "+data.ToString("HH:mm"));
Console.WriteLine("HH:mm:ss: " +
data.ToString("HH:mm:ss"));

123

124

I. C#

Console.WriteLine("h:mm tt: " +


data.ToString("h:mm tt"));
Console.WriteLine("hh:mm tt: " +
data.ToString("hh:mm tt"));
Console.WriteLine("MMMM dd: " +
data.ToString("MMMM-dd"));
Console.WriteLine("MM/dd/yyyy: " +
data.ToString("MM/dd/yyyy"));
Console.WriteLine("MM/dd/yyyy HH:mm: " +
data.ToString("MM/dd/yyyy HH:mm"));
Console.WriteLine("MM/dd/yyyy hh:mm: tt: " +
data.ToString("MM/dd/yyyy hh:mm tt"));
Console.WriteLine("MM/dd/yyyy H:mm: " +
data.ToString("MM/dd/yyyy H:mm"));
Console.WriteLine("MM/dd/yyyy HH:mm:ss: " +
data.ToString("MM/dd/yyyy HH:mm:ss"));
Console.WriteLine("dddd, dd MMMM yyyy: " +
data.ToString("dddd, dd MMMM yyyy"));
Console.WriteLine("dddd, dd MMMM yyyy HH:mm:ss: " +
data.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
Console.WriteLine("ddd, dd MMM yyyy HH':'mm':'ss'GMT': " +
data.ToString("ddd, dd MMM yyyy HH':'mm':'ss'GMT'"));
Console.WriteLine("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK: "
+ data.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"));
Console.Write(" " +
" >");
Console.Read();
}
}
}

ToString(string format)
data : data.ToString("D")
(22 2012 .), data.ToString("d")
(22.11.2012). ,
. 7.2.
Console.WriteLine() (+).

7.

. 7.2.


7.2.
7.2

/* Created by SharpDevelop.
* User: user
* Date: 22.11.2012
* Time: 17:28
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app18_datetime_operations
{
class Program
{

125

126

I. C#
public static void Main(string[] args)
{
const int Nov = 11; //
// 11-
DateTime d=DateTime.Now; //
//
DateTime d_1 =d.AddDays(-1);
//
DateTime d_tomor = d.AddDays(1);
//
int dm=DateTime.DaysInMonth(2012,Nov);
//
int to_end=dm d.Day; //
// i-
int i=12;
DateTime d_back=d.AddDays(-i);
//
//
//
//

, .
var .

var
int
int
int

now = DateTime.Now;
y=now.Year;
m=now.Month;
day=now.Day;

// :
// "--",
//
DateTime dt1 = DateTime.Now;
DateTime dt2 = new System.DateTime(2012, 11, 2);
TimeSpan diffResult = dt1.Subtract(dt2);
Console.WriteLine(" = " +
dt1.ToString());
Console.WriteLine(" = " +
dt2.ToString());

7.
Console.WriteLine(" = " +
diffResult.Days); //
Console.WriteLine(" = " +
diffResult.TotalDays); //
//
//
var today = DateTime.Today;
Console.WriteLine(" = " +
today.ToString());
// 5 , 30 , 10
var interval = new TimeSpan(5, 30, 10);
Console.WriteLine(" = " +
interval.ToString());
// 05:30:10
var newTime = today + interval; //
//
Console.WriteLine(" " +
" = " + newTime.ToString());
// 05:30:10
var tomorrowNewTime = newTime.AddDays(1);
//
Console.WriteLine(" 5_30 = " +
tomorrowNewTime.ToString());
// 05:30:10
var yesterdayNewTime = newTime.AddDays(-1);
//
Console.WriteLine(" 5_30 = " +
yesterdayNewTime.ToString());
// 10
var seeYouNextDecade = today.AddYears(10);
// 10
Console.WriteLine("10 " +
= " + seeYouNextDecade.ToString());
Console.Write(" " +
" >");
Console.Read();
}
}
}

127

128

I. C#

. 7.3.

. 7.3.
.

, "", (, ,
, ), . , ,
, . , .
, enum. ( )
. , ,
.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, Dec };

, ,
, "" :
, .
"". , Days d;
Months m;.

7.

129

: Days.Sunday, Months.Feb . .
d Days.Sunday,
Days.Monday . .

int. , ,
Months.
, , . 0,
1. , Sat 0, Sun 1, Mon 2 . .:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};


, :
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};


1, 0. ,
.
, , char. , int. , ,
, ,
:
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

: byte, sbyte, short,


ushort, int, uint, long ulong.
Days ,
. .
.
, . enum
. ,

130

I. C#

Sun int, enum int.


int x = (int)Days.Sun;

,

.
switch.
.
 Days.

public class EnumTest


{
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
/* :
Sun = 0
Fri = 5
*/

 enum,
long, .

public class EnumTest2


{
enum Range : long { Max = 2147483648L, Min = 255L };
static void Main()
{
long x = (long)Range.Max;
long y = (long)Range.Min;
Console.WriteLine("Max = {0}", x);

7.

131

Console.WriteLine("Min = {0}", y);


}
}
/* :
Max = 2147483648
Min = 255
*/

 , -

switch, 7.3.

7.3

/* Created by SharpDevelop.
* User: user
* Date: 23.11.2012
* Time: 15:13
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app19_enum
{
class Program
{
public enum DaysOfWeek

//
// ""

{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6
}
static void Main()
{
WriteText(DaysOfWeek.Sunday);
Console.ReadLine();
}

//
//

132

I. C#
// days
// ""
static void WriteText(DaysOfWeek days)
{
switch (days) // days
{
case DaysOfWeek.Monday:
Console.WriteLine("");
break;
case DaysOfWeek.Tuesday:
Console.WriteLine("");
break;
case DaysOfWeek.Wednesday:
Console.WriteLine("!");
break;
case DaysOfWeek.Thursday:
Console.WriteLine("");
break;
case DaysOfWeek.Friday:
Console.WriteLine("");
break;
case DaysOfWeek.Saturday:
Console.WriteLine("");
break;
case DaysOfWeek.Sunday:
Console.WriteLine(" ");
break;
} // switch
} // WriteText

}
}

. 7.4.
, , .

. 7.4. switch

7.

133


int ( :
). , . , ,
, , . , , . , ,
. , , -,
8- - . . .
, .
""
, .
[Flags()],
. ,
. , , 7.4.
7.4

/* Created by SharpDevelop.
* User: user
* Date: 23.11.2012
* Time: 16:43
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app20_flags
{
class Program
{
[Flags()]
public enum MilitaryType
{
Marine = 1,

//
//

134

I. C#
Land = 2,
Cosmic = 4,
AllType = Marine | Land | Cosmic
}
public static void Main(string[] args)
{
// Land Cosmic type0:
MilitaryType type0 = MilitaryType.Land |
MilitaryType.Cosmic;
// Console.WriteLine(type0);
// "Land, Cosmic"
Console.WriteLine(" {0}",type0);
// Marine type0:
type0 |= MilitaryType.Marine;
// Land type0:
//
bool b=System.Convert.ToBoolean(type0 &
MilitaryType.Land);
if(b)
Console.WriteLine(" Land type0 " +
""); // "Land, Cosmic"
Console.Read();
}

}
}

. 7.5.

. 7.5.

II

8.

9.

10.

11.

, , .
IL DASM

12.

13.

14.

LINQ

15.

Windows

16.

17.

18.

Windows Forms


5060 :
, .
-
, , , .
, ,
, , ,
. , . ,
, , , . .
, ,
.
, .
. .
. , , , ,
" ", -

138

II. -

. ,
, !
. ( break)!
! if...else !
goto! ,

begin end, if, then, else, (while) , , (). . .
, .
, "" 1024 (1 ), 64 , !
3 . .
, --
, ,
. -, ( ) . , . , - . ,
"". , , ""
, . , ,
"" . -, "" ,
. .
, "". -,
, , "", , ,
, . ,
, ,
, ""
. . . .
--, ,
, (),
(,
, , ),

8.

139

,
. ,
, , , - ?
. -
(), , . , , , .
, , ,
, , .
: , , , , , , .
, . , "" "" ( ) , .
. ,
. ,
[] ,
, () : M[i].
.
"" : (),
(<_> <_>),
, . .
. :
( ""), ,
, .
,
, . . , .
. . ,
- , , , . , , i. :
4 . . , , 5, -

140

II. -

, . i . . , , int i, 5,
. i , 6,
, int i ()
: 6.
: , ,
. .
, ,
. , .
, . () .
. new.
? , , (, - ). , ,
: . .
, ,
( ) ,
, , .
, , , . .
. , , ,
. ( ) ,
, . , .
, MyCar. , . . , car ():
MyCar car;. : . . , ,
, (): (Type), (Name) (Speed). , ,
(string Type, string Name, float Speed).
? . -

8.

141

. , .
,

MyCar(string Type, string Name, float Speed)

? , . string
type, string name, float speed, :
Type=Type; name=Name; speed=Speed;

MyCar :
MyCar(string Type, string Name, float Speed)
{
type=Type;
name=Name;
speed=Speed;
}

,
, :
MyCar Ch_nor_car = new MyCar("Porshe", "Chuck Norris", 250.0);

Ch_nor_car,
new ( MyCar) .
Ch_nor_car.
, () .
:
lass Car
{
}

class , Car . ? . . ,
,
Object ,
. , , Object. , . -
. ? (. . ), - . , , -

142

II. -

. ,
,
. , . : (,
, )
( ).
public, () private. , .
protected ().
( ).
, public. ,
- , , , protected.

.
,
, 8.1.
8.1

/* Created by SharpDevelop.
* User: user
* Date: 24.11.2012
* Time: 19:51
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app21_class
{
class MyCar
{
private string name;
private int speed;
private string owner_name;
//
public MyCar(string Name,int Speed,string Owner_name)

8.
{
name=Name;
speed=Speed;
owner_name=Owner_name;
}
//
public MyCar(string Name,int Speed)
{
name=Name;
speed=Speed;
}
// 1
public int M1()
{
speed=speed*2;
return(0);
}
} // class
class Program
{
public static void Main()
{
// ( ),
// ,
// Main(), .
// public.
// M1()
MyCar car = new MyCar("",120,"");
car.M1();
// car MyCar
car = new MyCar("",120);
car.M1();
Console.WriteLine("Press any key to continue... ");
Console.Read();
}
}
}

143

144

II. -

, MyCar ( , ).
private string name;
private int speed;
private string owner_name;

, ,
Main(), . M1(),
public (). ,
- , , . M1(). . ,
. ,
. ,
. public. (M1())
. Main() ,
1(). , ,
. , ,
car . ,

1(), . 8.1 8.2.
,
. ,
, ,
, ,
, .
1(). ,
(MyCar car = new MyCar("",
120,"");), : (MyCar car;), ():
car = new MyCar("",120,"");

,
. , ,
: int, double,
void . C# , . ,

8.

145

. 8.1. 1()

. 8.2. 1()

146

II. -

. , (
, ), , ,
MyCar car = new MyCar();

, . ,
(. . ), , , . ,
:
public MyCar()
{
name="";
speed=120;
owner_name="";
}

.
, .
, , .
, . , MyCar ,
.

this
, . .
, .
, ,
, ,
. , . , , . ,

public MyCar(string name, int Speed, string Owner_name)

8.

147

{
name=name;
...
}

, ,
name . this, , name
, , , . :
public MyCar(string name, int Speed, string Owner_name)
{
this.name=Name;
speed=Speed;
owner_name=Owner_name;
}

static ( ). this ,
, ( , ), this .

static
static.
, , ,
. , . .
,
, . , . , , ,
. , , . , .
, .
: ,
, .

148

II. -

WriteLine(). , (Console.WriteLine()).
, Console,
static. (
Console con = new Console(), ,
con.WriteLine(); ),
Console. , . Console. , , Math, .
,
.

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

8.

149


,
() . ,
static Rate=0.12;. ,
, , ,
, , ?
.
static. , , . ,
.
. :
class SimpleClass
{
// ,
// :
static long dt;
//
//
//
//

,
,
,
dt:

static SimpleClass()
{
dt = DateTime.Now.Ticks;
}
}

SimpleClass dt.


, static " " . ,
static class MyClass {} .

150

II. -

: , .
,
. .

"", "" "".


" ".
, ,
,
, .
, "" () , , . , . . , -, , .
, , , Console,
( ) Read(), ReadLines(),
, ,
-. Console. string s = ReadLines();, .
,
. ,
private. , , ( get
( ) set ( )).
,
, . ,
,
.
, ? public, private, protected ( -

8.

151

) internal. .
,
( ), private,
. , .
( public) ,
, ,
.
readonly. "
"? , . ,
,
" ". C#
readonly. readonly , const (, ), , " ".
, ( , ). ,
, , ( static , . .
).
" " .
readonly ,
, const.
. supp(). , , - , .
" ", NumSupp, .
:
public class A
{
public static readonly uint NumSupp;
static A() //

152

II. -

{
NumSupp

supp (Data);

}
}



. supp(Data)
, NumSupp
, .
, get set.
: . get set.

get set
Employee, . " ". ,
. private.
private string empName; ( , . .
string). , , . Get (). , , GetName(). ?
, . , . .
, . , public. . ,
string (
). empName
:
public string GetName()
{
return empName;
}

, return
( ).
, , :
string s = GetName();

8.

153

.
(. . emp Employee).

:
Employee emp = new Employee(" . .",
);
string s = emp.GetName();

s " . .".
, . SetName() ( Name).
,
, . : , ,
. , ,
. - . ,
, . .
public. return ,
void.
string, . .
, . ,
:
public void SetName(string Name)
{
if(Name.Length > 9)
WriteLine(": 9 ");
else
empName = Name;
}

, , empName .
Employee
, 8.2.
8.2

/* Created by SharpDevelop.
* User: user
* Date: 27.11.2012

154

II. -

* Time: 16:39
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app23_set_get
{
class Employee
{
private string empName;
//
// : public,
//
//
public Employee(string name)
{
empName=name;
}
// :
public string GetName()
{
return empName;
}
public int SetName(string Name)
{
if(Name.Length > 9)
{
Console.WriteLine(": " +
" 9, = {0}", Name);
return(0);
}
else
{
empName = Name;
return(1);
}
} // if
} //
class Program
{
public static void Main()

8.

155

{
// :
Employee emp = new Employee(" ..");
// name (
// static,
// ):
string s=emp.GetName();
Console.WriteLine(" name = {0}",s);
Console.Write(": <Enter> >");
// name:
if(emp.SetName(" ..") == 0)
emp.SetName(" .");
// , , ,
//
s=emp.GetName();
Console.WriteLine(" name = {0}",s);
Console.Write(": <Enter> >");
Console.ReadKey(true);
}
}
}

. 8.3.

. 8.3. get, set


# , .
.
Employee : .
8.3.

156

II. -

8.3

/* Created by SharpDevelop.
* User: user
* Date: 27.11.2012
* Time: 18:12
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app24_properties
{
class Employee
{
private string empName;
private int empID;
private float empPay;
//
public Employee(string Name, int ID, float Pay)
{
empName=Name; empID=ID; empPay=Pay;
}
//
/*
, Pay
. empPay float,

Pay float. this -

*/
public Employee(string Name,int ID, double Pay)
{
this.Name=Name; this.ID=ID; this.Pay=(float)Pay;
}
// Name, ID, Pay:
public string Name
{
get { return empName; }

8.

157

set
{
if (value.Length > 9)
Console.WriteLine (": > 9. "+
" = {0}", value);
else
empName = value;
} // set
} // Name
public int ID
{
get { return empID; }
set { empID = value; }
} // ID
public float Pay
{
get {return empPay;}
set { empPay = value;}
}
} // Employee
class Program
{
public static void Main(string[] args)
{
Employee emp = new Employee("", 411, 15000);
// :
Console.WriteLine("empName = {0}",emp.Name);
Console.WriteLine("empID = {0}",emp.ID);
Console.WriteLine("empPay = {0}",emp.Pay);

Pay

// emp.SetPay(emp.GetPay() + 1000);
//
emp.Pay += 1000; // emp.Pay 16000
Console.WriteLine("empPay 1000
= {0}",emp.Pay);
//
//
Console.WriteLine(" :");
Employee emp1 = new Employee("",001,25000);

158

II. -
// :
Console.WriteLine("empName = {0}",emp1.Name);
Console.WriteLine("empID = {0}",emp1.ID);
Console.WriteLine("empPay = {0}",emp1.Pay);
Console.Write("Press any key to continue... ");
Console.Read();
}

}
}

, ,
, . public, . . , , .
, ,
. get ( ) set ( ). get()
, set() value, , set(). value
. ,
, .
, private float empPay (),
,
public float Pay
{
get {return empPay;}
set { empPay = value;}
}

(
-), , ,
1000, :
Employee emp = new Employee("");
emp.SetPay(emp.GetPay() + 1000);

Pay
emp.Pay += 1000;

8.

159

, ?

emp.Pay += 1000;

.

get(), .
( Get())
: emp.Pay. ! , ,
, - get set,
, , SetName(), GetName() . .
:
, .
, , :
public Employee(string name)
{
empName=name;
}

:
public Employee(string name)
{
Name=name;
}

Name , empName, .
, ( ). -

. 8.4.

160

II. -

8.3. . 8.4.


get, set,
, ().
- , ( get),
( set).
static, ,
.


,
get-set, ( ) . getset . ,
. , . ,
, ( ),
.
. 8.3. empPay Pay :
private float empPay; //
public float Pay
//
{
get { return empPay; }
set { empPay = value; }
}

, :
public float Pay {get; set;}

( ). , , ,
. !
.

8.

161


, ,
. , / (
), . , ,
class p
{
// ()
public int x {get; set;}
public int y {get; set;}
//
public p()
{
}
public p(int v1, int v2)
{
x=v1;
y=v2;
}
}

C :
p ob1=new p(); ob1.x=10; ob1.y=20;

p ob2=new p(10,20);

:
p ob=new p {x=10, y=20};

. ,
p ob=new p() {x=10, y=20};


, .
, :
p ob2=new p(10,20) {x=30, y=40};

, , (30, 40).

162

II. -


,
. ,
: /
. 8.4. . 8.5.
8.4

/* Created by SharpDevelop.
* User: user
* Date: 30.11.2012
* Time: 13:27
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app25_obj_ini
{
class p
{
// ()
public int x {get; set;}
public int y {get; set;}
//
public p()
{
}
public p(int v1, int v2)
{
x=v1;
y=v2;
}
}
class Program
{
public static void Main()
{
p ob1=new p(); ob1.x=10; ob1.y=20;

8.

163

Console.WriteLine(" "+
" : x={0} y={1}",
ob1.x, ob1.y);
p ob2=new p(10,20);
Console.WriteLine(" " +
" : x={0} y={1}",
ob2.x, ob2.y);
p ob=new p {x=10, y=20};
Console.WriteLine(" "+
" : x={0} y={1}",
ob.x, ob.y);
Console.Write("Press any key to continue... ");
Console.Read();
}
}
}

. 8.5.

.
partial
, ( - ), , . , , , , , ,
, .
,
partial ().
, , .
(
) .
: () cs
, -

164

II. -

(, , ).
partial.
( Main()). cs WordPad ( cs). ,
: Project | Add | Existing Item.
. cs- .
8.58.7.
. 8.6.
8.5

//
partial class Employee
{
//
private string empName;
//
private int empID;
//
private float currPay;
//
private int empAge;
//
private string empSSN;
//
private static string companyName; //
//
public Employee() { }
public Employee(string name, int age, int id,
float pay, string ssn)
{
//
Name = name;
Age = age;
ID = id;
Pay = pay;
SocialSecurityNumber = ssn;
}
static Employee() //
{
companyName = "Union Fenosa";
}
}

8.
8.6

//
partial class Employee
{
//
public static string Company
{
get { return companyName; }
set { companyName = value; }
}
public string Name
{
get { return empName; }
set
{
if (value.Length > 9)
; // Console.WriteLine(" 9 ");
else
empName = value;
}
}
public int ID
{
get { return empID; }
set { empID = value; }
}
public float Pay
{
get { return currPay; }
set { currPay = value; }
}
public int Age
{
get { return empAge; }
set { empAge = value; }
}
public string SocialSecurityNumber
{
get { return empSSN; }
set { empSSN = value; }
}
} // class

165

166

II. -

8.7

/*
* Created by SharpDevelop.
* User: user
* Date: 30.11.2012
* Time: 15:43
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app22_employee_all
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" "+
"");
Employee emp = new Employee {Name=""};
//
//
Console.WriteLine("C : {0}",
emp.Name);
Console.Write("Press any key to continue... ");
Console.ReadKey(true);
}
}
}

. 8.6. ,

8.

167

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

public protected.
, 8.8.
8.8

class car
//
{
const int maxSpeed = 90; // .
int carSpeed;
//
public int Speed
// (
// )
{
get {return carSpeed;}
set
{
carSpeed = value; //
//
if(carSpeed > maxSpeed) //
//
carSpeed = maxSpeed;
}
} // Speed
} // car

car ()
(carSpeed). Speed,
(set) , , maxSpeed. , get -

168

II. -

. , (My_car) , , car, . carName. , ,


, .
, .

. , C#.
, . , 8.9.
8.9

class My_car : car


{
const int maxName = 20;
string carName;
//
public string Name // (
// )
{
get {return carName;}
set
{
carName = value;
if(carName.Length > maxName)
carName=": " +
" 20- ";
}
}

, 8.8, : -
-.
8.8 8.9 ,
Main(), ,
My_car. ,
Speed -,
. 8.10,
. 8.7.

8.

169

8.10

/* Created by SharpDevelop.
* User: user
* Date: 02.12.2012
* Time: 12:42
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app27_inherit
{
class car
{
const int maxSpeed = 90;
int carSpeed;
public int Speed
{
get {return carSpeed;}
set
{
carSpeed = value;

//
// .
//
//

//
//
if(carSpeed > maxSpeed)
//
//
carSpeed = maxSpeed;

}
} // Speed
} // car
class My_car : car
{
// :
const int maxName = 20;
string carName;
//
public string Name
//
{
get {return carName;}
set
{
carName = value;

170

II. -
if(carName.Length > maxName)
carName=": " +
" 20- ";
}
}

}
class Program
{
public static void Main()
{
Console.WriteLine(" -:");
car obj_car = new car {Speed = 85}; //
//
Console.WriteLine(" " +
" : {0}",
obj_car.Speed);
My_car cr = new My_car {Name = "Volvo"};
//
cr.Speed=88;
Console.WriteLine(" : " +
"{0}\nC : {1}",
cr.Name, cr.Speed);
Console.Write("Press any key to continue... ");
Console.Read();
}
}
}

. 8.7.

8.

171

-, , , public, . . .
public , private. ,
public . , , , .
-, ,
, , , ,
,
(. cr.Speed=88;).


C# . ,
. sealed (). sealed class car { },
class My_car : car { }
. , , . . .
My_string : strring {}

, . . string :
, .


, . : : ,
? , , .
,
, ,
.
( , . . ),
: ,

172

II. -

, ( ,
, , ). , , ,
. .
?
base,
. , , :
_(_) : base
(_)
{
//
}

base (_) ,
.
,
, ( ) base.
.
8.11. . 8.8.
8.11

/* Created by SharpDevelop.
* User: user
* Date: 02.12.2012
* Time: 16:42
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app28_base
{
class MyClass
{
public int x, y, z;

//

8.
//
public MyClass(int x, int y, int z)
{
/* this , . .
.
this.x ,
*/
this.x = x;
this.y = y;
this.z = z;
}
}
class inherite_class : MyClass
{
int point; //
// base:
//
// x, y, z, . .
//
// ,
//
public inherite_class(int point, int x, int y, int z)
: base(x, y, z)
{
this.point = point; //
//
}
// -
public void Pointer(inherite_class new_point)
{
// :
new_point.x += new_point.point;
new_point.y += new_point.point;
new_point.z += new_point.point;
Console.WriteLine(" " +
" : {0} {1} {2}",
new_point.x, new_point.y, new_point.z);
}
}

173

174

II. -

class Program
{
static void Main()
{
Console.WriteLine(" " +
" base\n");
inherite_class obj = new inherite_class(5, 2, 3, 4);
Console.WriteLine(" " +
": {0} {1} {2}", obj.x, obj.y, obj.z);
obj.Pointer(obj);
Console.ReadLine();
}
}
}

. 8.8. base

, base , , ,
.

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

8.

175


, .
- -
. ? , .
, .
, , 8.12, . 8.9.
8.12

/* Created by SharpDevelop.
* User: user
* Date: 02.12.2012
* Time: 19:03
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app29_include_sealed
{
sealed public class A
{
int a; //
int b;
//
public int A_a
{
get { return a; }
set { a=value; }
}
public int A_b
{
get { return b; }
set { b=value; }
}
//
public A(int a,int b)
{this.a=a; this.b=b;}

176

II. -
//
public int M_A()
{
return (a + b);
}

}
class B
{
public int c;
public A ab = new A(15,20);
public B(int cc)
{
c=cc;
}
}
class Program
{
public static void Main()
{
B ba = new B(5);
int sum=ba.c + ba.ab.M_A();
Console.WriteLine(" " +
"\n ");
Console.WriteLine(" = {0}", ba.c);
Console.WriteLine(" " +
" {0}, {1}",ba.ab.A_a, ba.ab.A_b);
Console.WriteLine(" " +
" : {0}", sum);
// TODO: Implement Functionality Here
Console.Write("Press any key to continue... ");
Console.Read();
}
}
}

, ,
-

8.

177

_b. M_A(), . ab, . ,


( ,
M_A()), , . . -
. ,
,
( ), ,
,
. ,
- , ba.ab.A_a.

. 8.9.


:
C# . (
. .)

. ,
. :
public class OuterClass
{
public class InnerClass1 {}
private class InnerClass2 {}
}

,
, , , (
). , :

178

II. -

static void Main()


{
OuterClass.InnerClass1 obj1 =
new OuterClass.InnerClass1();
}

( , ),
( SharpDevelop): (
obj1), , . ,
, .
. . . .
( ,
. .), , , . ,
public. -
, .
. ,
. , ,
.

"". - ,
,
. :
"" "".
Object, Draw() .
, .
Draw(). "" Draw(), . (,
). , , ?
, ,
"" - "".
Draw()
"". : .

8.

179

(method overriding).
- . : , virtual. , . . , Draw()
, , - virtual. . ,
virtual, - .
virtual , , , ,
-, . . . , , virtual,
, . , ,
.
.
, -
( Draw()) . , ? override. . . "" "" Draw() override.

, - ,
, base. , , Draw() base.Draw();, . . -, -
, , ,
.
8.13. . 8.10.
8.13

/* Created by SharpDevelop.
* User: user
* Date: 04.12.2012

180

II. -

* Time: 12:30
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app30_overriding
{
public class A
{
int a; //
int b;
//
public int A_a
{
get {return a;}
set {a=value;}
}
public int A_b
{
get {return b;}
set {b=value;}
}
//
public A() {}
public A(int a,int b)
{ this.a=a; this.b=b; }
//
public virtual int M_A()
{ return (a + b); }
}
class
{ int
int
int

B : A
a;
b;
c;

8.

181

//
public int C_c
{
get {return c;}
set {c=value;}
}
// (,
// )
public B(int aa, int bb, int cc):base(aa, bb)
{
a=aa; b=bb; c=cc;
}
// :
// ""
// ( )
public override int M_A()
{
return (base.M_A() + c*c);
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" " +
" ");
B b_b = new B(5,6,7);
Console.WriteLine("1- - {0}\n2-
- {1}", b_b.A_a, b_b.A_b);
Console.WriteLine("
{0}\n {1}",b_b.C_c,b_b.M_A());
Console.Write("Press any key to continue... ");
Console.ReadKey(true);
}
}
}

182

II. -

. 8.10. -


, ,
, . .
(), . ,
,
. ,
.
abstract. .
(, ?).
, ,
virtual, ( )
. , , . .
, - . , Draw()
- . , "!
". .
: . -
"" .
. ,
- .
abstract ( ).

8.

183

, -
-.
abstract . :
abstract class Shape
{
...
public abstract void Draw()
{
...
}
}


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

override ( , ) new (,
). , ,
new. , :
public new int indecs;

, indecs
, . C#. , ,
, . 8.13 M_A()
override, ,
, M_A(). , . ,
. , ,
, . 8.10. ,
.
-,
.

184

II. -




,
( () ()). ,
Object,
, . ,
Object. object.
, C# - - (
) , , -
- ( ). 8.14
, . . 8.11.
8.14

/* Created by SharpDevelop.
* User: user
* Date: 05.12.2012
* Time: 14:03
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app32_class_casting
{
public class Base
{
public virtual void WhoAmI()
{
Console.WriteLine("I'm Base");
}
}
public class Derived: Base
{

8.

185

public override void WhoAmI()


{
Console.WriteLine("I'm Derived");
}
}
public class Test
{
public static void Main()
{
Derived d = new Derived();
Base b = d;
//
//
b.WhoAmI();
// ,
//
Derived d1 = (Derived) b; //
// (
// )
object o = d;
//
// object
Derived d2 = (Derived) o; //
// (
// )
d.WhoAmI(); // :
//
Console.Read();
}
}
}

. 8.11.

as is
object ,
object, object
. "-

186

II. -

" , (
) , . . . "" .
, .
as is. , ,
, , , int. is,
, 8.15.
8.15

/* Created by SharpDevelop.
* User: user
* Date: 05.12.2012
* Time: 15:04
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app33_as_and_is
{
public class test
{
static void Main()
{
String derived_Obj = "Dummy"; //
// String (
// )
Object base_Objl = new Object (); //
Object base_Obj2 = derived_Obj;
//
// :
//
Console.WriteLine ("base_Obj2 {0} String",
base_Obj2 is String ? "" : " ");
Console.WriteLine ("base_Objl {0} String",
base_Objl is String ? "" : " ");
Console.WriteLine ("derived_Obj {0} Object",
derived_Obj is Object ? "" : " ");
int j = 123;
object b = j;

8.

187

object obj = new Object () ;


Console.WriteLine ("b {0} int",
b is int ? "" : " ");
Console.WriteLine ("obj {0} int",
obj is int ? "" : " ");
Console.WriteLine("b {0} System.ValueType",
b is ValueType ? "" : " ");
float f=12.3f;
Console.WriteLine ("f {0} int",
f is int ? "" : " ");
Console.Read();
}
}
}

. 8.12.

. 8.12. is

String. . , derived_Obj .
, , . . ,
String, Object.
. base_Objl base_Obj2.
derived_Obj.
is
. Console.WriteLine(),
base_Obj2 is String ? "" : " ".

188

II. -

.
(?). ( ) ( )
if...else. :
1 ? 2 : 3;

1 bool ( ), 2 3 .
?. .
1. (True), 2, . 1
( False), 3,
.

base_Obj2 is String ? "" : " "

1 base_Obj2 is String (:
base_Obj2 String).

bool bl= base_Obj2 is String;


base_Obj2 is String ? "" : " "

:
bl ? "" : " "


Console.WriteLine("base_Obj2 {0} String", bl ? "" :
" ");

: base_Obj2 (, , ), , . .
( ).
-.
. {0} (String). .
is ,
8.16. . 8.13.

8.
8.16

/* Created by SharpDevelop.
* User: user
* Date: 05.12.2012
* Time: 16:02
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace App33_as_and_is2
{
public class BaseType {}
public class DerivedType : BaseType {}
public class Program
{
static void Main()
{
Console.WriteLine (" as");
DerivedType derived_Obj = new DerivedType ();
//
BaseType base_Objl = new BaseType (); //
//
BaseType base_Obj2 = derived_Obj;
//
//
// ,
//
// . , as
// null
DerivedType derived_Obj2 = base_Obj2 as DerivedType;
if(derived_Obj2 != null)
{ Console.WriteLine(" " +
" ");
}
else
{ Console.WriteLine(" "+
" ");
}

189

190

II. -
// :
derived_Obj2 = base_Objl as DerivedType;
if(derived_Obj2 != null)
{ Console.WriteLine(" "+
" ");
}
else
{ Console.WriteLine(" "+
" ");
}
// :
BaseType base_Obj3 = derived_Obj as BaseType;
if (base_Obj3 != null)
{ Console.WriteLine(" " +
" ");
}
else
{ Console.WriteLine(" "+
"");
}
Console.Read();
}

}
}

as is null.

. 8.13. as

8.

191

, , , . ,
,
, . , ,
. C#,
, , , , .
. (
):
public struct Person
{
public int x, y;
public Person(int p1, int p2)
{
x = p1;
y = p2;
}
}

struct .
(Person). : , .
.
 .


, .
 -

( ).
 . -

,
. , , . , , .

192

II. -

new (. . ).
 , .

, , 8.17.
8.17

/* Created by SharpDevelop.
* User: user
* Date: 07.12.2012
* Time: 12:34
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app35_struct
{
public struct Person
{
public int x, y;
int c; // private
public Person(int p1, int p2, int p3)
{
x = p1;
y = p2;
c = p3;
}
public int M(int a)
{
c=a;
return c;
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" ");

8.

193

Person p = new Person(1,2,3);


int sum = p.x + p.y;
sum += p.M(4); // M() ""
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

- , , . ?
, . ,

, , : , . .
:
: , (, , ) new ,
. . , , (, ) . , ,
,
( ) , , . . ,
, , , .
. , , , .

194

II. -


try catch
, , . ,
, .
.
, , , ,
.
, , ,
, . ,
. ,

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

196

II. -

, ,

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

, . .

 ,

(. . ) .

 ,

,
try ().

 ,

, catch (, ).

 ,
finally ( ),

 throw (),

, ( ()),
throw .

Object,

System.Exception, , ( ),
Object.
, , . . , 9.1, . 9.1.

9.

197

9.1

/* Created by SharpDevelop.
* User: user
* Date: 06.12.2012
* Time: 12:32
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app34_exeption
{
class Program
{
static void Main()
{ Console.WriteLine(" " +
" 5 ");
int i = (Console.ReadLine().Length);
try
{
if (i > 5)
//
throw new Exception(); // OverflowException();
}
catch (Exception ex)
// OverflowException
{
Console.WriteLine(" 5 " +
"");
}
Console.ReadLine();
}
}
}

. 9.1. , 5

198

II. -

,
try catch. , .
: , , try.
. . try
(
), try
trow. .
Exception() , ,
( ). ,
-. OverflowException, throw.
-, ( , ,
).
Exception,
.
try catch. .
. try
, catch (, if...else).
: . catch
-.
, throw.
catch
Exception. , 9.2, .
. 9.2.
9.2

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 06.12.2012
Time: 12:32

9.

199

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
namespace app34_exeption
{
class Program
{
static void Main()
{
Console.WriteLine(" 5 " +
"");
int i = (Console.ReadLine().Length);
try
{
if (i > 5)
//
throw new Exception(); // OverflowException();
}
catch (Exception ex) // OverflowException
{
Console.WriteLine(" 5 " +
"");
Console.WriteLine("Message = {0}", ex.Message);
Console.WriteLine("Source = {0}", ex.Source);
Console.WriteLine("StackTrace = {0}",
ex.StackTrace);
Console.WriteLine("TargetSite = {0}",
ex.TargetSite);
Console.WriteLine("HelpLink = {0}", ex.HelpLink);
}
Console.ReadLine();
}
}
}

. 9.2 ,

Exception.
 Message , .
 Source .

200

II. -

. 9.2.
Exception

 StackTrace :

,
" ", . "" ( )
, .
 TargetSite - . Main().
 HelpLink URL-,
. .
.
catch ex.HelpLink = "URL-";.
Exception
HelpLink.

finally
, try...catch. , , .
, , ,
. ,
C# : finally.
finally , , , ( ) . ,

9.

201

try...catch,
finally
try...catch.
try...catch finally:
try
{
// ,
}
catch ()
{
//
}
finally {
// :
// , . .
}

finally ,
try...catch, , .
, try
, , finally. 9.2
catch :
finally
{Console.WriteLine(" ");}

9.3.
. 9.3.
9.3

/* Created by SharpDevelop.
* User: user
* Date: 06.12.2012
* Time: 12:32
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app34_exeption
{
class Program
{
static void Main()

202

II. -
{
Console.WriteLine(" 5 " +
"");
int i = (Console.ReadLine().Length);
try
{
if (i > 5)
//
throw new Exception(); // OverflowException ();
}
catch (Exception ex) // ExceptionOverflow
{
ex.HelpLink="Micrisoft.com";
Console.WriteLine(" 5 " +
"");
Console.WriteLine("Message = {0}", ex.Message);
Console.WriteLine("Source = {0}", ex.Source);
Console.WriteLine("StackTrace = {0}",
ex.StackTrace);
Console.WriteLine("TargetSite = {0}",
ex.TargetSite);
Console.WriteLine("HelpLink = {0}", ex.HelpLink);
}
finally
{
Console.WriteLine(" ");
}
Console.ReadLine();
}

}
}

. 9.3.

10

"".
, . # -
, . , . , , ,
( ). .
? , - ().

, ,
, - (
: , ),
( ), "". (
: ,
, ). C# , . .
, , ""
. ,
, . , IFILE
Fileopen(), FileClose() .

204

II. -

:
1(), 2(), 3(),
. . , , 2() Inh?
.
2(), Inh .
.
,
, . , Triangles () Shapes (). Triangles IPointy, . Triangles
:
Class Triangles : Shapes, IPointy
{
//
//
//
//
public override void Draw();
// iPointy:
public byte Points //
{
get { return 3; } //
//
}
} //

Hexagon () iPointy, Hexagon:


Class Hexagon : Shapes, IPointy
{
//
//
//
//
public override void Draw();
// iPointy:
public byte Points //

10.

205

{
get { return 6; }

//
//

}
//

.
Hexagon hex = new Hexagon();
int i = hex.Points;

( ).
,
10.1.
10.1

/* Created by SharpDevelop.
* User: user
* Date: 07.12.2012
* Time: 15:55
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app37_interface
{
interface ICar
{
int Speed{get; set;}
void GetInfo();
}
interface IPrice
{
double Price();
}
public class Ferrari: ICar,IPrice
{
private int spd; // ()

206

II. -
public int Speed // ()
{
get { return spd; }
set { spd = value; }
}
// :
public void GetInfo()
{
Speed=250;
Console.WriteLine(" Ferrari @ +
" . {0}", Speed);
}
// :
public double IPrice()
{
Console.WriteLine("\n 20000");
}

}
class Program
{
public static void Main()
{
Console.WriteLine(" " +
"");
Ferrari fr = new Ferrari();
fr.GetInfo();
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

ICar Speed ( ) GetInfo(). ,


,
. Ferrari ( ), spd () Speed.
ICar:
. . 10.1.

10.

207

. 10.1.

( ). 10.2: ,
.
10.2

/* Created by SharpDevelop.
* User: user
* Date: 07.12.2012
* Time: 15:55
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app37_interface2
{
public interface IPrice
{
double Price();
}
public interface ICar
{
int Speed {get; set;}
void GetInfo();
}
public class Ferrari : ICar,IPrice
{
private int spd; // ()
public int Speed // ()
{
get { return spd; }

208

II. -
set { spd = value; }
}
// :
public void GetInfo()
{
Speed=250;
Console.WriteLine(" Ferrari " +
" . {0}", Speed);
}
// :
public double Price()
{
return 20000;
}

}
class Program
{
public static void Main()
{
Console.WriteLine(" " +
" ");
Ferrari fr = new Ferrari();
fr.GetInfo();
Console.WriteLine(" {0}",
fr.Price());
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

. 10.2.

. 10.2.

10.

209

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

. , price() : double
interf1.price() {}, double interf2.price() {}.
. ( ).
, , , , .

210

II. -

11

, ,
.
IL DASM

.
 Common Intermediate Language( CIL)

, Microsoft .NET
Framework. ,
.NET, CIL. . 11.1. CIL .
CIL ,

,
CIL , .
" ". CIL IL (Intermediate
Language), . . " ".
 Common Language Runtime (CLR) -

.NET.
 Just in Time (JIT) c CIL. -

CLR.
.
 .
 .NET ,

CIL. , , -

212

II. -

.
,
( , ),
.
, , , , .
 Dinamic Link Library (dll) , -

.
exe ( ) .
.

. 11.1. .NET

exe- dll-. , . , ( ).
. , ,
, . , , , . . ,

11. , ,

213

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

IL DASM, Tools (. 11.2).

. 11.2. IL Dasm

IL DASM
. , .
. 11.3.
.
View (
,
. .). Main(), CIL, , .NET.
,
.

214

II. -

. 11.3. 10


(namespace) ,
C++ ,
.
, , ,
, , , , ,
.
,
. -

11. , ,

215

, -
, - .

.
C#.
(
: , Timer .NET Framework ). :
,
System.
90 , .NET Framework, System.
? :
namespace
{
class
{
...
}
...
}

:
 ;
 ;
 ;
 .

-
,
, . . .
using () ,
, .
.NET . 11.1.

216

II. -
11.1. .NET

System

,

, ,
,
, , , , . http://msdn.
microsoft.com/en-us/library/system.aspx

System.Collections

,
: ,
, , .

http://msdn.microsoft.com/enUS/library/system.collections(v=VS.80).aspx

System.Collections.Generic

System.Data

.
http://msdn.microsoft.com/enus/library/system.data.aspx

System.IO


-.
http://msdn.
microsoft.com/en-us/library/29kt2zfk.aspx

System.Drawing



Windows Forms.
:

System.Windows.Forms

System.Windows
System.Windows.Controls
System.Windows.Shapes

http://msdn.microsoft.com/enus/library/system.drawing(v=VS.85).aspx

http://msdn.microsoft.com/enus/library/system.windows.forms.aspx

System.Windows
,
Windows Presentation Foundation (WPF).
:

http://msdn.microsoft.com/enus/library/system.windows.aspx

http://msdn.microsoft.com/en-us/library/
system.windows.controls(v=VS.95).aspx

http://msdn.microsoft.com/enus/library/system.windows.shapes.aspx

11. , ,

217

11.1 ()

System.ServiceModel

Windows
Communication Foundation (WCF).

http://msdn.microsoft.com/enus/library/system.servicemodel.aspx

System.Security

,

. .
http://msdn.microsoft.com/
en-us/library/windows/apps/hh454038.aspx


using. ,
.
, ?
.
, , .
- , - .
?
Add Reference ( ) Project () . ,
(
Net Assembly Browser NET-).
Browse, .
,
, OK
. using
,
, ,
using app39_namespace.pbi.MyModul;

app39_namespace ( exe ),
pbi.MyModul , .
,
(alias) :
using alias = _


. ,

218

II. -

11.1,
. 11.4. , , , .
11.1

//
/* Created by SharpDevelop.
* User: user
* Date: 08.12.2012
* Time: 15:49
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app39_namespace
{
namespace pbi.MyModul
{
public class A
{
public int A_a {get; set;}
}
} // MyModul
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

11. , ,
//
/* Created by SharpDevelop.
* User: user
* Date: 09.12.2012
* Time: 11:17
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app40_namespace_2
{
namespace pbi.MyModul2
{
public class B
{
public int B_b {get; set;}
}
} // MyModul2
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}
//
/*
*
*
*
*

,
Created by SharpDevelop.
User: user
Date: 09.12.2012
Time: 11:21

219

220

II. -

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
//
// Project
//
//
//
//

,
:
using app39_namespace.pbi.MyModul;
using app40_namespace_2.pbi.MyModul2;

//
using MyModul = app39_namespace.pbi.MyModul;
using MyModul2 = app40_namespace_2.pbi.MyModul2;
namespace app41_namespace_main
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" , " +
" \n");
// app39_namespace.pbi.MyModul.A a = new
app39_namespace.pbi.MyModul.A();
MyModul.A a = new MyModul.A();
a.A_a=5;
// app40_namespace_2.pbi.MyModul2.B b =
new app40_namespace_2.pbi.MyModul2.B();
MyModul2.B b =
new app40_namespace_2.pbi.MyModul2.B();
b.B_b=6;
Console.Write(" +
" \n");
Console.Write(" _ = {0}, B_b = {1}\n",
a.A_a, b.B_b);

11. , ,

221

Console.Write("Press any key to continue...");


Console.ReadKey(true);
}
}
}

. 11.4. :
, ;

222

II. -

, namespace
<_>:
. ,
, .

12

C#
, .

: , . : , . ,
, , , . System.Array, .
System.Array .
, . C#-
, .
System.Collections.

:
 IEnumerable -

 ICollection -

 IList -

. ;

224

II. -

 IDictionary IList, ,

animalArray animalArrayList
12.1.
. 12.1.
12.1

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 10.12.2012
Time: 18:50
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

namespace app43_collections_2
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace app42_collections_1
{
public abstract class Animal
{
protected string name; //
public string Name
//
{
get {return name;}
set {name = value;}
}
public Animal() //
{
name = " ";
}
public Animal(string newName) //
//

12. .
{
name = newName;
}
public void Feed() //
{
Console.WriteLine ("{0} ", name);
}
} // Animal
public class Cow : Animal
//
{
public void Milk() //
{
Console.WriteLine("{0} ", name);
}
public Cow(string newName) : base(newName)
// (
// )
{
}
} // Cow
public class Chicken : Animal //
{
public void LayEgg() //
{
Console.WriteLine ("{0} ", name);
}
public Chicken(string newName) : base(newName)
// (
// )
{
}
} // Chicken
class Program
{
static void Main()
{
Console.WriteLine(" " +
"Array Animal " +
" ");

225

226

II. -
// animalArray
// .
//
// Array,
//
Animal [] animalArray = new Animal [2];
Cow myCowl = new Cow(""); //
//
// :
animalArray [0] = myCowl; //
// ( )
animalArray [1] = new Chicken(""); //
//
//( )
//
//
//
//
//
//


.
myAnimal ,
:
,

foreach (Animal myAnimal in animalArray)


{
Console.WriteLine(" Array "+
" , = {0}",
myAnimal.Name);
}
//
Console. WriteLine(" Array "+
" {0}",
animalArray.Length);
animalArray[0].Feed(); //
//
((Chicken)animalArray[1]).LayEgg(); //
//
// animalArray ,
// Chicken,
// LayEgg().
// .

12. .
// :
Console.WriteLine();
Console.WriteLine(" " +
"ArrayList Animal " +
" :");
ArrayList animalArrayList = new ArrayList();
Cow myCow2 = new Cow("");
animalArrayList.Add(myCow2); //
// : ,
// . :
// ,
// Array ,
// (Add() . .)
animalArrayList.Add(new Chicken(""));
// :
foreach (Animal myAnimal in animalArrayList)
{
Console. WriteLine(" " +
" ArrayList," +
" = {0}", myAnimal.Name);
}
Console.WriteLine(" ArrayList "+
" {0} ",
animalArrayList.Count); //
// Count
((Animal)animalArrayList[0]).Feed(); //
// Feed(),
// Animal,
// Feed()
((Chicken)animalArrayList[1]).LayEgg();
Console.WriteLine();
Console. WriteLine(" " +
" ArrayList:");
// : .
// .
//
animalArrayList.RemoveAt(0);

227

228

II. -
Console.WriteLine(" " +
" :");
foreach (Animal myAnimal in animalArrayList)
{ Console.WriteLine ("{0}", myAnimal.Name); }
// :
//
((Animal)animalArrayList[0]).Feed();
// :
//
animalArrayList.AddRange (animalArray);
Console.WriteLine(" " +
"animalArray " +
"animalArrayList :");
foreach (Animal myAnimal in animalArrayList)
{ Console.WriteLine ("{0}", myAnimal.Name); }
// ,
((Chicken)animalArrayList[2]).LayEgg();
Console.WriteLine(" {0} " +
" {1}",
// : ()
//
myCowl.Name, animalArrayList.IndexOf(myCowl));
myCowl.Name = "";
Console.WriteLine(" "+
" {0}", ((Animal) animalArrayList[1]).Name);
Console.ReadKey();
}
}

}
}

,
ArrayList. ,
. . 12.1.

12. .

229

. 12.1. :
animalArray animalArray List

IEnumerable IEnumerator
IEnumerable IEnumerator ,
foreach.
IEnumerator ,
. IEnumerator :
 MoveNext(), 1

, ,
;

 Reset(), -

1. ;

 Current(), .

IEnumerable IEnumerator.
foreach, , .

230

II. -

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

/* Created by SharpDevelop.
* User: user
* Date: 13.12.2012
* Time: 14:34
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections;
namespace app46_Ienum_Ienumble
{
public class car
{
//
private int year;
//
private string brand; //
//
public car(string Brand,int Year)
{
brand=Brand;
year=Year;
}
//
public int Year
{
get {return year;}
set {year=value;}
}
public string Brand
{
get {return brand;}

12. .
set {brand=value;}
}
} // end class
public class cars : IEnumerator,IEnumerable
{
// car
// (: " ")
private car[] carlist; //
int position = -1;
//
//
// : carlist
//
public cars()
{
carlist = new car[6]
{
new car("Ford",1992),
new car("Fiat",1988),
new car("Buick",1932),
new car("Ford",1932),
new car("Dodge",1999),
new car("Honda",1977)
};
}
// ,
// ( C#)
// IEnumerable
public IEnumerator GetEnumerator() //
//
{ // ,
// IEnumerator
return (IEnumerator)this;
}
// IEnumerator
public bool MoveNext() //

231

232

II. -
{
position++;
return (position < carlist.Length);
}
public void Reset()

// :
//

{position = 0;}
public object Current //
{
get { return carlist[position];}
}
}
class Program
{
public static void Main()
{
Console.WriteLine(" INumerator,
INumarable\n foreach");
cars C = new cars();
Console.WriteLine(" \n");
foreach(car c in C)
//
// ,
Console.WriteLine(c.Brand + "\t\t" + c.Year);
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

foreach,
MoveNext(), ,
cars 1, 1, 1- .
Current(), (

12. .

233

). , foreach.
, MoveNext(), . Current(), ,
. . , ,
MoveNext() , .

. 12.2. foreach

foreach ,
,
.



System.Collections.CollectionBase.
protected: List InnerList.List
, InnerList, ArrayList,
. . 12.1, . 12.2.

234

II. -
12.1. CollectionBase

Capacity

, CollectionBase

Count

,
CollectionBase.

InnerList

ArrayList,
CollectionBase

List

IList, CollectionBase

12.2. CollectionBase

Clear


CollectionBase.

Equals(Object)

,
. Object

GetEnumerator

,

CollectionBase

OnClear



CollectionBase

OnClearComplete



CollectionBase

OnInsert


CollectionBase

OnInsertComplete


CollectionBase

OnRemove



CollectionBase

12. .

235
12.2 ()

OnRemoveComplete



CollectionBase

OnSet



CollectionBase

OnSetComplete



CollectionBase

OnValidate

RemoveAt

CollectionBase.

ToString

,
. ( Object.)

ICollection.CopyTo

CollectionBase Array,

IList.Add


CollectionBase

IList.Contains

,
CollectionBase

IList.IndexOf

Object
( )
CollectionBase

IList.Insert

CollectionBase

IList.IsFixedSize

, ,
CollectionBase

IList.IsReadOnly

, ,
CollectionBase

IList.Item

IList.Remove


CollectionBase

236

II. -

, "On" .
, . . ( ) . "On"
, List, , InnerList.
CollectionBase , 12.3,
. 12.3. .
12.3

/* Created by SharpDevelop.
* User: user
* Date: 11.12.2012
* Time: 14:30
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections;
namespace app44_collections_CollectionBase_class
{
public class Int16Collection : CollectionBase
{
public Int16 this[ int index ] //
//
// ( . )
{ get { return((Int16) List[index]); }
set { List[index] = value; }
}
//
//
//
//

, .
, , ,
,

public int Add(Int16 value)


{ return(List.Add(value)); }

12. .
public int IndexOf(Int16 value)
{ return(List.IndexOf(value)); }
public void Insert(int index, Int16 value)
{ List.Insert(index, value); }
public void Remove(Int16 value)
{ List.Remove(value); }
public bool Contains(Int16 value)
{ // value Int16, false
return(List.Contains(value));
}
// (
// )
protected override void OnInsert(int index,
Object value)
{ /* ,
,
values */
}
protected override void OnRemove(int index,
Object value)
{ /* ,
,
values */
}
protected override void OnSet(int index,
Object oldValue, Object newValue)
{ /* ,
,
values */
}
/* value
Int16.
Int16,
*/

237

238

II. -

protected override void OnValidate(Object value)


{
if (value.GetType() != typeof(System.Int16))
throw new ArgumentException("value must be of type
Int16.", "value");
}
} //
public class Program
{
public static void Main()
{
//
Int16Collection myI16 = new Int16Collection();
//
// (1, 2, ...) Int16
myI16.Add((Int16) 1);
myI16.Add((Int16) 2);
myI16.Add((Int16) 3);
myI16.Add((Int16) 5);
myI16.Add((Int16) 7);
//
Console.WriteLine(" " +
" foreach:");
PrintValues1(myI16);
Console.WriteLine(" " +
" enumerator:");
PrintValues2(myI16);
Console.WriteLine(" " +
" Count Item:");
PrintIndexAndValues(myI16);
// 3
// Contains IndexOf
Console.WriteLine("Contains 3: {0}",
myI16.Contains(3));
Console.WriteLine("2 {0}.",
myI16.IndexOf(2));
Console.WriteLine();

12. .

239

// ,
// 3
myI16.Insert(3, (Int16) 13);
Console.WriteLine(" " +
" 13, 3:");
PrintIndexAndValues(myI16);
//
// : myI16[4] = 123;
myI16[4] = 123;
Console.WriteLine(" " +
" 4 123:");
PrintIndexAndValues(myI16);
// 2
myI16.Remove((Int16) 2); // RemoveA()
// ,
Console.WriteLine(" " +
" 2:");
PrintIndexAndValues(myI16);
Console.Read();
}
//
// Count Item
public static void PrintIndexAndValues(Int16Collection myCol)
{
for (int i = 0; i < myCol.Count; i++)
Console.WriteLine("
[{0}]:
{1}", i, myCol[i]);
Console.WriteLine();
}
// foreach,
// enumerator
public static void PrintValues1(Int16Collection myCol)
{
foreach (Int16 i16 in myCol)
Console.WriteLine("
{0}", i16);
Console.WriteLine();
}
// enumerator
public static void PrintValues2(Int16Collection myCol)

240

II. -
{
System.Collections.IEnumerator myEnumerator =
myCol.GetEnumerator();
while (myEnumerator.MoveNext()) //
//
Console.WriteLine("
{0}", myEnumerator.Current);
//
Console.WriteLine();
}

}
}

, 12.1 Animal .
System.Collections.CollectionBase,
Clear(), RemoveAt(), Remove() Count.
Animal:
public class Animals : CollectionBase
{
public void Add(Animal newAnimal)
{ List.Add(newAnimal); }
public void Remove(Animal oldAnimal)
{ List.Remove(oldAnimal); }
public Animals()
{} //
}

Add() Remove() , . ., ,
( )
Add() Remove().
Animals .
,
12.3.
, .
:
public Int16 this[ int index ]
{ get { return((Int16) List[index]); }
set { List[index] = value; }
}

12. .

. 12.3. CollectionBase

241

242

II. -

,
.
. 12.3 :
myI16[4] = 123;

. ,
.

IDictionary
, CollectionBase,
IList,
.
( ) , , , . ,
DictionaryBase,
, . CollectionBase,
, .
DictionaryBase, IDictionary,
. 12.312.5.
12.3. DictionaryBase

Count


DictionaryBase

Dictionary


DictionaryBase

12.4. DictionaryBase

Clear

DictionaryBase

CopyTo

DictionaryBase
Array

Equals(Object)

12. .

243
12.4 ()

Finalize

try to

GetEnumerator

IDictionaryEnumerator,
DictionaryBase

GetType

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

OnClear

"
DictionaryBase". .

OnClearComplete

, OnClear,

OnGet

" ". .

. ,

OnInsert

"
DictionaryBase ". .

OnInsertComplete

, OnInsert,

OnRemove

, OnInsert,

OnRemoveComplete

, OnInsertComplete,

OnSet

, OnRemove,

OnSetComplete

, OnSet,

ToString

244

II. -
12.5.

IDictionary.Add

DictionaryBase

IDictionary.Contains

,
DictionaryBase

IDictionary.IsFixedSize

, ,
DictionaryBase

IDictionary.IsReadOnly

, ,
DictionaryBase "
" object

IDictionary.Item



DictionaryBase

IDictionary.Keys

ICollection,
DictionaryBase

IDictionary.Remove


DictionaryBase

IDictionary.Values

ICollection,
DictionaryBase

IEnumerable.GetEnumerator

IEnumerator,
DictionaryBase


, 12.4.
. 12.4.
12.4

/* Created by SharpDevelop.
* User: user
* Date: 11.12.2012
* Time: 18:20
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections;

12. .
namespace app45_IDictionary
{
public class SimpleDictionary : IDictionary
{ // (, )
private DictionaryEntry[] items;
private Int32 ItemsInUse = 0; //
// ,
//
public SimpleDictionary(Int32 numItems)
{
items = new DictionaryEntry[numItems]; //
//
}
#region IDictionary Members // ,
//
// ,
// ()
public bool IsReadOnly
{ get { return false; } }
//
// ,
//
public bool Contains(object key)
{
Int32 index;
return TryGetIndexOfKey(key, out index); //
// ,
//
}
// ,
//
public bool IsFixedSize { get { return false; } }
//
public void Remove(object key)
{
if (key == null)

245

246

II. -
throw new ArgumentNullException("key"); //
//
// DictionaryEntry
Int32 index;
if (TryGetIndexOfKey(key, out index))
{
// ,
Array.Copy(items, index + 1, items, index,
ItemsInUse index 1);
ItemsInUse--;
}
else
{ // }
}
// IDictionary
/* C#
.
: ,
: */
public void Clear() { ItemsInUse = 0; }

// . " ",
//
public void Add(object key, object value)
{
// " ",
//
if (ItemsInUse == items.Length)
throw new InvalidOperationException("
");
items[ItemsInUse++] = new DictionaryEntry(key,
value);
}
public ICollection Keys
{ get
{ // :
/* ItemsInUse
*/

12. .
Object[] keys = new Object[ItemsInUse];
for (Int32 n = 0; n < ItemsInUse; n++)
keys[n] = items[n].Key;
return keys;
}
}
// , Keys:
// , . .
//
public ICollection Values
{ get
{ //
Object[] values = new Object[ItemsInUse];
for (Int32 n = 0; n < ItemsInUse; n++)
values[n] = items[n].Value;
return values;
}
}
// ,
// :
// .
// ,
//
public object this[object key]
{ get
{ // ,
//
Int32 index;
if (TryGetIndexOfKey(key, out index))
{ // ,
//
return items[index].Value;
}
else
{ //
return null;
}
}

247

248

II. -
set
{ // ,
//
Int32 index;
if (TryGetIndexOfKey(key, out index))
{ // ,
//
items[index].Value = value;
}
else
{ // ,
// " "
Add(key, value);
}
}
}
private Boolean TryGetIndexOfKey(Object key,
out Int32 index)
{
for (index = 0; index < ItemsInUse; index++)
{ // , true (
// )
if (items[index].Key.Equals(key)) return true;
}
// , false (index
// ).
return false;
}
private class SimpleDictionaryEnumerator :
IDictionaryEnumerator
{
// SimpleDictionary
DictionaryEntry[] items;
Int32 index = -1;
public SimpleDictionaryEnumerator(SimpleDictionary sd)
{
// DictionaryEntry
items = new DictionaryEntry[sd.Count];
Array.Copy(sd.items, 0, items, 0, sd.Count);
}

12. .
//
public Object Current
{ get { ValidateIndex(); return items[index]; } }
//
public DictionaryEntry Entry
{ get { return(DictionaryEntry) Current; }
}
//
public Object Key
{ get { ValidateIndex(); return items[index].Key; }}
//
public Object Value
{ get { ValidateIndex(); return items[index].Value; }}
//
public Boolean MoveNext()
{
if (index < items.Length 1)
{ index++; return true; }
return false;
}
//
// ,
//
private void ValidateIndex()
{
if (index < 0 || index >= items.Length)
throw new InvalidOperationException(""+
" ");
}
//
//
public void Reset()
{ index = -1; }
}

249

250

II. -

public IDictionaryEnumerator GetEnumerator()


{ //
return new SimpleDictionaryEnumerator(this);
}
#endregion // ,
// ,
//
// ( )
//
//
//
//

ICollection:

( C#),

#region ICollection Members


public bool IsSynchronized
{ get { return false; } }
public object SyncRoot
{ get { throw new NotImplementedException(); } }
public int Count { get { return ItemsInUse; } }
public void CopyTo(Array array, int index)
{ throw new NotImplementedException(); }
#endregion
#region IEnumerable Members

//
// ""
IEnumerator IEnumerable.GetEnumerator()
{ //
return ((IDictionary)this).GetEnumerator();
}
#endregion
}
public sealed class App
{
static void Main()
{
// ,
IDictionary d = new SimpleDictionary(3);
// .
d.Add("", 40);

12. .
d.Add("", 34);
d.Add("", 1);
Console.WriteLine(" = {0}",
d.Count);
Console.WriteLine(" ''? {0}",
d.Contains(""));
/* :
(
d[""]), ,
.
(
)) */
Console.WriteLine(" : {0}", d[""]);
//
foreach (DictionaryEntry de in d)
{
Console.WriteLine("{0}:
{1} ",
de.Key, de.Value);
}
//
Console.WriteLine(" ''");
d.Remove("");
//
// .
Console.WriteLine(" " +
" ''");
d.Remove("");
// ( ) .
// Keys ,
//
Console.WriteLine(" ");
foreach (String s in d.Keys)
Console.WriteLine(s);

251

252

II. -
// ( )
Console.WriteLine(" ");
foreach (Int32 age in d.Values)
Console.WriteLine(age);
Console.Read();
}

}
}

. 12.4. ()

IDictionary.

SimpleDictionary

private DictionaryEntry[] items;


private Int32 ItemsInUse = 0;

items . . ItemsInUse . ()
IDictionary. C# ,
, , . , ,
. . SimpleDictionaryEnumerator -

12. .

253

IDictionaryEnumerator,
foreach.
ICollection, . .
IDictionary ICollection. , Keys ()
Values (). , ,
IEnumerable,
IEnumerator, foreach.
.
d , . " ".
. , . add() IDictionary.
, ,
"" ,
. ""
. "", :
TryGetIndexOfKey() ,
,
. . . IDictionary .

" ". foreach, IEnumerator IEnumerable.
. , . ,
<F10>,
( ) <F11>, <F10> <F11>,
<F5>.
: , .

254

II. -

12.4, , foreach, IENumerable IEnumerator.


,
yield.
"", . . , . , ,
foreach . .
, (
IEnumerable) , 12.5,
. 12.5.
foreach MyEnumerator() (
, ), .
12.5

/* Created by SharpDevelop.
* User: user
* Date: 15.12.2012
* Time: 13:08
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections;
namespace app48_yield
{
public class A
{
static int n;
public A(int N)
{ n=N; }
public IEnumerable MyEnumerator()
{ for(int i=0; i<n; i++)

12. .

255

yield return("String " +


System.Convert.ToString(i));
}
} // A
class Program
{
public static void Main()
{
Console.WriteLine("Hello World!");
A a = new A(5);
foreach (string item in a.MyEnumerator())
Console.WriteLine(item);
Console.ReadKey();
} // Main
} // Program
}

. 12.5. foreach

yield, c return
MyEnumerator(), .
MyEnumerator() foreach , .


ICloneable,
, .

256

II. -

Clone().
System.Object. 12.6, , ,
. 12.6.
12.6

/* Created by SharpDevelop.
* User: user
* Date: 16.12.2012
* Time: 11:42
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections;
namespace app49_Clone
{
public class A:System.ICloneable
{ // Array
//
public int [] numbers = { 1, 2, 3, 4, 5 };
//
public A()
{ }
// ICloneable
public Object Clone()
{ return new A(); }
// foreach
public IEnumerable MyNumerator_a()
{
A a = new A();
for(int i=0; i < a.numbers.Length; i++)
yield return a.numbers[i];
}
}
class Program
{
public static void Main()

12. .

257

{
Console.WriteLine(" ");
Console.WriteLine(" :");
A a = new A();
foreach(object o in a.MyNumerator_a())
Console.WriteLine("{0}",o);
Console.WriteLine(" :");
A b = (A)a.Clone();
for(int i=0; i < b.numbers.Length; i++)
Console.WriteLine("{0}", b.numbers[i]);
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}

. 12.6. ()

,
(numbers). Array
. (
). , ( ).

258

II. -

Clone().
object. Clone()
. , . . foreach. foreach . for
yield, foreach
. .
,
foreach , , , . . object,
b ( , b ). b
for.

Array List<T>
.

Array
, ,
, . . .
. ,
, . ,
, Array , CreateInstance(). . 12.612.8. , : , C#, (
MSDN ). .

12. .

259
12.6. Array

IsFixedSize

, , Array

IsReadOnly

, ,
Array

Length

32- ,

Array

LongLength

64- ,

Array

Rank

() Array

12.7. Array

BinarySearch(Array, Object)


Array,
IComparable, Array

BinarySearch(Array, Object,
IComparer)

Array,
IComparer

BinarySearch(Array, Int32,
Int32, Object)



Array, IComparable,
Array

BinarySearch(Array, Int32,
Int32, Object, IComparer)



Array, IComparer

Clear

Array
, false null

260

II. -
12.7 ()

ConstrainedCopy


Array, ,
Array, . ,

ConvertAll<TInput, TOutput>

Copy(Array, Array, Int32)


Array, ,
Array,
. 32-

Copy(Array, Array, Int64)


Array, ,
Array,
. 64-

Copy(Array, Int32,
Array, Int32, Int32)


Array, ,
Array, .
32-

Copy(Array, Int64,
Array, Int64, Int64)


Array, ,
Array, .
64-

CopyTo(Array, Int32)

Array Array,
Array.
32-

CopyTo(Array, Int64)

Array Array,
Array.
64-

12. .

261
12.7 ()

CreateInstance(Type, Int32)

Array Type ,

CreateInstance(Type, Int32[])

Array Type
,
.
32-

CreateInstance(Type, Int64[])

Array Type
,
.
64-

CreateInstance(Type, Int32,
Int32)

Array Type
,

CreateInstance(Type,
Int32[], Int32[])

Array Type

CreateInstance(Type, Int32,
Int32, Int32)

Array Type
,

Equals(Object)

,
(
Object)

Finalize


, ( Object)

Find<T>

, ,

Array

FindAll<T>

262

II. -
12.7 ()

FindLast<T>

, ,
Array

ForEach<T>

GetEnumerator

IEnumerator Array

GetLength

32- , Array

GetLongLength

64- , Array

GetLowerBound

Array

GetUpperBound

Array

GetValue(Int32)

, Array.
32-

GetValue(Int32[])

, Array.

32-

GetValue(Int64)

, Array.
64-

GetValue(Int64[])

, Array.

64-

IndexOf(Array, Object)


Array

12. .

263
12.7 ()

IndexOf(Array, Object, Int32)



Array,

IndexOf(Array, Object,
Int32, Int32)



Array,

IndexOf<T>(T[], T)



Array

Initialize


Array

LastIndexOf(Array, Object)


Array

LastIndexOf(Array, Object,
Int32)



Array,

LastIndexOf(Array,
Object, Int32, Int32)



Array,

Resize<T>

Reverse(Array)


Array

Reverse(Array, Int32, Int32)



Array

264

II. -
12.7 ()

SetValue(Object, Int32)

,
Array.
32-

Sort(Array)


Array, IComparable
Array

Sort(Array, Array)


Array ( ,
)
Array, IComparable

Sort(Array, IComparer)

Array,
IComparer

Sort(Array, Array,
IComparer)


Array ( ,
)
Array, IComparer

Sort(Array, Int32, Int32)

Array
IComparable Array

Sort(Array, Array, Int32,


Int32)


Array ( ,
)
Array,
IComparable

Sort(Array, Int32, Int32,


IComparer)

Array,
IComparer

Sort(Array, Array, Int32,


Int32, IComparer)

Array (
, ) Array,
IComparer

12. .

265
12.7 ()

Sort<T>(T[])


Array, IComparable<T>
Array

ToString

,
( Object)

12.8. IList

ICollection.Count

,
Array

IList.Add

IList

IList.Clear

IList

IList.Contains

,
IList

IList.IndexOf


IList

IList.Insert

IList

IList.IsFixedSize

, ,
Array

IList.IsReadOnly

, , Array

IList.Item

IList.Remove


IList

IList.RemoveAt

IList

IStructuralComparable.
CompareTo



(
,
)

266

II. -
12.8 ()

IStructuralEquatable.Equals

IStructuralEquatable.
GetHashCode

Array
12.7. . 12.7.
12.7

/* Created by SharpDevelop.
* User: user
* Date: 17.12.2012
* Time: 12:13
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app51_array
{
class Program
{
public static void Main()
{
Console.WriteLine("C "+
" int object");
int[] myInt = new int[5] {1, 2, 3, 4, 5};
Object[] myOb = new Object[5] {26, 27, 28, 29, 30};
//
Console.Write(": ");
PrintValues(myInt);
Console.Write(": ");
PrintValues(myOb);
// myInt
// myOb: Array
System.Array.Copy(myInt, myOb,2);

12. .
//
Console.WriteLine("\n "+
" 1- 2-");
Console.Write(": ");
PrintValues(myInt);
Console.Write(": ");
PrintValues(myOb);
//
// myOb myInt
System.Array.Copy(myOb, myOb.GetUpperBound(0) 1,
myInt, myInt.GetUpperBound(0) 1, 2);
//
Console.WriteLine("\n "+
" 2- 1-");
Console.Write(": ");
PrintValues(myInt);
Console.Write(": " );
PrintValues(myOb);
Console.Read();
} // Main
//
public static void PrintValues(Object[] myArr)
{
foreach (Object i in myArr)
{ Console.Write("\t{0}", i); }
Console.WriteLine();
}
public static void PrintValues(int[] myArr)
{
foreach (int i in myArr)
{ Console.Write("\t{0}", i); }
Console.WriteLine();
}
}
}

267

268

II. -

. 12.7. Array

Array
12.8, . 12.8.
12.8

/* Created by SharpDevelop.
* User: user
* Date: 17.12.2012
* Time: 13:10
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app52_array
{
class Program
{
public static void Main()
{
//
// Int32.
Array myArr = Array.CreateInstance(typeof(Int32), 2, 3, 4);
// 2, 3, 4
/* typeof
Type,
CreateInstance*/

12. .

269

// GetLowerBound(0)
// Array,
// GetLowerBound(Rank 1)
// Array.
for (int i = myArr.GetLowerBound(0); i <=
myArr.GetUpperBound(0); i++) // 1-
for (int j = myArr.GetLowerBound(1); j <=
myArr.GetUpperBound(1); j++) // 2-
for (int k = myArr.GetLowerBound(2); k <=
myArr.GetUpperBound(2); k++) // 3-
{
//
// :
myArr.SetValue((12*i)+(4*j)+k, i, j, k);
}
/* :
1,2; 1,2,3; 1,2,3,4,
:
1,1,1, 1,1,2, 1,1,3, 1,1,4
1,2,1, 1,2,2, 1,2,3, 1,2,4
1,3,1, 1,3,2, 1,3,3, 1,3,4
2,1,1, 2,1,2, 2,1,3, 2,1,4
2,2,1, 2,2,2, 2,2,3, 2,2,4
2,3,1
2,3,2, 2,3,3, 2,3,4
*/
// Array.
Console.WriteLine(" {0}
{1} ", myArr.Rank, myArr.Length);
Console.WriteLine("\t\t \t ");
for (int i = 0; i < myArr.Rank; i++) //
// 1
{
Console.Write("{0}:\t{1}", i, myArr.GetLength(i));
Console.WriteLine("\t\t{0}\t\t{1}",
myArr.GetLowerBound(i),
myArr.GetUpperBound(i));
}
//
Console.WriteLine(" :");

270

II. -
PrintValues(myArr);
Console.Read();

}
public static void PrintValues(Array myArr)
{
// IEnumerable Array,
//
// :
System.Collections.IEnumerator myEnumerator =
myArr.GetEnumerator();
int i = 0;
int cols = myArr.GetLength(myArr.Rank 1);
// : GetLength(0) -
// , Rank-1.
// ,
// false, :
while (myEnumerator.MoveNext()) //
// MoveNext ,
// i : 1, 2
{ if (i < cols)
{ i++; // 4-
}
else
{ Console.WriteLine();
i = 1; //
//
}
Console.Write("\t{0}", myEnumerator.Current); //
// ( )
} // while
Console.WriteLine();
}
}
}

12. .

271

. 12.8. Array

List<T>
(<> ), . , .
System.Collections.Generic.List<T>. IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>,
IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable,
. . 12.9
12.12. , :
C#, ( MSDN ).
.
12.9. List<T>

List<T>()


List<T>

List<T>(IEnumerable<T>)

List<T>,
, ,
,

272

II. -
12.9 ()

List<T>(Int32)


List<T>

12.10. List<T>

Capacity

Count

, List<T>

Item

12.11. List<T>

Add


List<T>

AddRange


List<T>

AsReadOnly


IList<T>,

BinarySearch(T)


List<T>,
, ,

BinarySearch(T, IComparer<T>)


List<T>,
,
,

BinarySearch(Int32, Int32, T,
IComparer<T>)



List<T>,
, ,

12. .

273
12.11 ()

Clear


List<T>

Contains

,
List<T>

ConvertAll<TOutput>


List<T>

CopyTo(T[])

List<T> ,

CopyTo(T[], Int32)

List<T>
,

CopyTo(Int32, T[], Int32,


Int32)


List<T> ,

Equals(Object)

,
(
Object)

Exists

, List<T> ,

Finalize

Find

, ,
List<T>

FindAll

FindIndex(Predicate<T>)

, ,


List<T>

274

II. -
12.11 ()

FindIndex(Int32,
Predicate<T>)

, ,


List<T>,

FindIndex(Int32, Int32,
Predicate<T>)

, ,


List<T>,

FindLast

, ,
List<T>

FindLastIndex(Predicate<T>)

, ,


List<T>

FindLastIndex(Int32,
Predicate<T>)

, ,


List<T>,

FindLastIndex(Int32, Int32,
Predicate<T>)

, ,


List<T>,

ForEach


List<T>

GetEnumerator

,
List<T>

12. .

275
12.11 ()

GetRange

List<T>

GetType

Type

IndexOf(T)



,
List<T>

IndexOf(T, Int32)


List<T>,

IndexOf(T, Int32, Int32)


List<T>,

Insert

List<T>

InsertRange


List<T>

LastIndexOf(T)



,
List<T>

LastIndexOf(T, Int32)



List<T>,

LastIndexOf(T, Int32, Int32)




List<T>,

276

II. -
12.11 ()

MemberwiseClone


Object

Remove


List<T>

RemoveAll

RemoveAt

List<T>

RemoveRange


List<T>

Reverse()


List<T>

Reverse(Int32, Int32)

Sort()


List<T>

Sort(IComparer<T>)


List<T>

Sort(Int32, Int32,
IComparer<T>)

List<T>

ToArray

List<T>

ToString

TrimExcess

,
List<T>,

TrueForAll

,
List<T>

12. .

277

12.12.

ICollection.CopyTo


ICollection Array,
Array

ICollection<T>.IsReadOnly

, ,
ICollection<T>

IEnumerable<T>.GetEnumerator

IEnumerable.GetEnumerator

IList.Add

IList (
)

IList.Contains

,
IList

IList.IndexOf


IList

IList.Insert

IList

IList.IsFixedSize

, ,
IList

IList.IsReadOnly

, , IList

IList.Item

IList.Remove


IList

IList
List<T>. ( ) , .
ICollection, IEnumerable.
. , . 12.13
12.14.

278

II. -
12.13. IList

Count

,
ICollection ( ICollection)

IsFixedSize

, ,
IList

IsReadOnly

, ,
IList

Item

12.14. IList

Add

IList

Clear

IList

Contains

,
IList

CopyTo

ICollection
Array, Array

GetEnumerator

,
( IEnumerable)

IndexOf

IList

Insert

IList

Remove


IList

RemoveAt

IList,

List<T> ArrayList,
. List<T> IList<T>, ,
.
List<T>
.

12. .

279

, Contains(), IndexOf(), LastIndexOf() Remove(),


.
, T, . T IEquatable<T>, Equals(T) ,
Object.Equals(Object). ,
BinarySearch() Sort(), . , T, . T
IComparable<T>,
CompareTo(T) . , T IComparable,
CompareTo(Object) .
T ,
. . , BinarySearch, List<T>.
List<T> . .
List<T> null
.
List<T> ArrayList,
, ,
List<T> .
12.9. . 12.9.
12.9

/* Created by SharpDevelop.
* User: user
* Date: 18.12.2012
* Time: 9:37
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections.Generic;

280

II. -

namespace app53_list
{
class Program
{
public static void Main()
{
Console.WriteLine(" LIst<T>");
List<string> d = new List<string>();
Console.WriteLine("\n " +
" : {0} ", d.Capacity);
d.Add("");
d.Add("");
d.Add("");
d.Add("");
d.Add("");
Console.WriteLine(" :");
Console.WriteLine();
foreach(string b in d)
{ Console.WriteLine(b); }
Console.WriteLine("\n " +
" : {0} ",
d.Capacity);
Console.WriteLine(" : {0} " +
"", d.Count);
Console.WriteLine("\n \"\"?: {0}",
d.Contains(""));
Console.WriteLine("\n \"\" 2-
");
d.Insert(2, "");
Console.WriteLine(" " +
":");
Console.WriteLine();
foreach(string b in d)
{ Console.WriteLine(b); }

12. .

281

Console.WriteLine("\n 3 " +
"( ): {0}", d[3]);
Console.WriteLine("\n \"\"");
d.Remove(""); //
Console.WriteLine(" " +
":");
Console.WriteLine();
foreach(string b in d)
{ Console.WriteLine(b); }
d.TrimExcess(); //
//
Console.WriteLine("\n " +
" ");
Console.WriteLine(": {0}", d.Capacity);
Console.WriteLine(": {0}", d.Count);
d.Clear(); //
// ,
Console.WriteLine("\n ");
Console.WriteLine(" (): {0}",
d.Capacity);
Console.WriteLine(" " +
" : {0}", d.Count);
Console.Read();
}
}
}

List<T> .
. Capacity, Add() . ,
Capacity
Count, ,
: Capacity ,
. Count , -

282

II. -

. Capacity
Count ( ).
(Capacity) 8.

. 12.9. List<T>

12. .

283

Contains() , Insert() , .
Item() ( C#)
, Remove() , ,
. Remove() . TrimExcess()

Capacity Count.
10% , .
Clear()
Capacity Count.
: foreach ,
, .


. , :
. is as. .
: "", ""
. . , . .
. IComparable System CompareTo().
, ,
.
int, : , ,
, , ( ) .
, , ,
, ( )
.
.

284

II. -

IComparable
12.10. . 12.10.
12.10

/* Created by SharpDevelop.
* User: user
* Date: 16.12.2012
* Time: 14:07
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Collections.Generic;
namespace app50_compare
{
public class Dictionary : IComparable<Dictionary>
{ // :
public string Name {get; set;}
public int Age {get; set;}
public Dictionary() {} //
// ( )
// IComparable
public int CompareTo(Dictionary ob)
{ // :
// Dictionary
Dictionary d = ob as Dictionary;
if(d != null)
return this.Age.CompareTo(ob.Age);
else
throw new ArgumentException(" "+
" Dictionary");
}
} // Dictionary
class Program
{
public static void Main()
{
Console.WriteLine(" " +
"IComparable");

12. .
/* List
( ),
.
, ,

.*/
// - ()
List<Dictionary> d = new List<Dictionary>();
// :
//
d.Add(new Dictionary() { Name = "", Age = 40 });
d.Add(new Dictionary() { Name = "", Age = 20 });
d.Add(new Dictionary() { Name = "", Age = 10 });
Console.WriteLine(" :");
foreach (var b in d)
Console.WriteLine("{0} {1}", b.Name,b.Age);
// IComparable.CompareTo():
//
d.Sort();
Console.WriteLine(" ");
foreach (var b in d)
Console.WriteLine("{0} {1}",b.Name,b.Age);
Console.Read();
}
}
}

. 12.10. IComparable

285

286

II. -

class Dictionary. IComparable<T> :


IComparable<Dictionary>.
IComparable - .
CompareTo(). ,
. ,
Dictionary. CompareTo() Dictionary. ,
Dictionary. , . Dictionary, . . Sort()
List<T>, =Dictionary.
. Add() , Sort() . , Sort()
CompareTo(),
, . Sort() CompareTo() , ,
, . CompareTo() , , . . ,
.
,
CompareTo() .
: List<T>
foreach
:
, foreach. foreach,
. , , IEnumerable
List<T>.

,
Object. ,
(

12. .

287

, object
. .) ,
. ,
/ ,
. (
,
; : , . .) , , ( ) .

. . , :
- ? ,
? ,
? C#,
. System.Collection.Generic,
. :
( ,
) , .
.NET Framework
( , )
. , List<T>.
<> " ".
"" .
, , List<T>, :
List<int> MyInt = new List<int>();

"". ,
.
,
K, Key, V
TValue.
, . -

288

II. -

List<T>: 12.10 " " ( ) :


List<Dictionary> d = new List<Dictionary>();

Dictionary.
()
.

(, ). , Array Sort<T>.
12.11, . 12.11.
12.11

/* Created by SharpDevelop.
* User: user
* Date: 19.12.2012
* Time: 14:34
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
using System.Collections;
namespace app54_generic1
{
class Program
{
public static void Main()
{
Console.WriteLine(" " +
" Sort<T>()");
int [] MyInt = {12,1,4,85,43,8}; // .
// Array
Console.WriteLine(" :");
foreach(int i in MyInt)
Console.WriteLine("{0}", i);

12. .

289

Array.Sort<int>(MyInt); //
//
Console.WriteLine(" :");
foreach(int i in MyInt)
Console.WriteLine(" {0}",i);
Console.Read();
}
}
}

. 12.11. Sort


12.12. . 12.12.
12.12

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 19.12.2012
Time: 15:43
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

290

II. -

using System;
namespace app55_generic_T
{
// Point
public class Point<T>
{
// :
private T xPos;
private T yPos;
// :
public Point(T xVal, T yVal)
{
xPos = xVal;
yPos = yVal;
}
//
public T X
{ get { return xPos; }
set { xPos = value; }
}
public T Y
{ get { return yPos; }
set { yPos = value; }
}
public override string ToString()
{ return string.Format (" [{0 }, {1}]", xPos, yPos);
}
// :
public void ResetPoint()
{ // # default .
//
//
// (0 , null )
xPos = default(T);
yPos = default(T);
}
} // Point<T>

12. .

291

class Program
{
public static void Main()
{
Console.WriteLine(" " +
" ");
Point<int> MyPoint = new Point<int>(100,25);
Point<double> MyPoint2 =
new Point<double>(2.5,3.85);
Console.WriteLine(" int: {0} {1}",
MyPoint.X, MyPoint.Y);
Console.WriteLine(" double: {0} {1}",
MyPoint2.X, MyPoint2.Y);
Console.Read();
} // Main()
}
}

. 12.12.


:
 ;
 -

,
, ,
, , ;

 - , -

292

II. -


.NET where
.
:
 where T : struct , <T>

System.ValueType, . . ( -);

 where T : class , <T>

System.ValueType, . . ;

 where T : new , <T>

, . .
. ,
;

 where T : __ ,

 where T : _ , -

. ,
.

.
. ,
public class A<K,T> where K : NameOfBaseClass, new() where T :
IComparable<T>

. , :
public T Add(T arg1, T arg2)
{return arg1 + arg2}

, , "" ,
: where T : operator +, operator . .

13


C#,
. . , (. .
) . ,
. ? ,
. . , .
:
public delegate
(____);

,
public delegate int MyDelegate(string a, double b);

( ),
int, string a,
double b. , ,
? ,
(, )
.
, ,
-. -, -

294

II. -

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

13.1, . 13.1.
13.1

/* Created by SharpDevelop.
* User: user
* Date: 20.12.2012
* Time: 14:55
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app56_delegate
{
// ,
//
public delegate int Ar(int x, int y) ;
// ,
// ,
// . . :
public class SimpleMath
{
public static int Add(int x, int y)
{ return x + y; }
public static int Subtract (int x, int y)
{ return x y; }
}
class Program
{

13.

295

static void Main()


{ Console.WriteLine (" \n");
// ,
//
Ar b = new Ar(SimpleMath.Add); //
// , . .
// Add()
Console.WriteLine("2+2 {0}", b(2, 2));
Ar = new Ar(SimpleMath.Subtract);
Console.WriteLine("4-2 {0}", (4, 2));
Console.Read();
}
}
}

. 13.1.

: , , . .
:
, ;
. .
: , ( ), , - . ,
. ,
- (, "").

296

II. -

, , -
, , .
, , , ,
. ,
( ), ,
, , , , . . - .
?
- ,
- , . . , , , Visual C++,
, ( ),
,
. ,
() . () ,
,
. , ,
( OnClick ) ,
, ,
.
, , :
( - ,
; ,
Button1 Button1_Click)
:
(Object

sender, EventArgs

e)

(
, ):
private: System::Void Form1_Click(System::Object
System::EventArgs e)
{
}

sender,

13.
private: System::Void button1_Click(System::Object
System::EventArgs e)
{
}

297
sender,

: ,
(sender ), , e EventArgs ( ).
object, ,
.
, - ?
(void, . . , ), .
,
. :
. (
) ,
, . ,
, ,
.NET Framework:
 EventArgs ( ) , -

EventArgs ( , );

 , ()

, ;

 ,

: public event EventHandler MyEvent.

, :
public delegate void MyEventHandler(object sender, MyEventArgs e);

, , (sender) ,
. (e) ,
. MyEventArgs
EventArgs. EventArgs ,
MouseEventArgs, ListChangedEventArgs . . GUI- (Graphic
User Interface, ) -

298

II. -

.
, , -.
, 13.2, . 13.2
13.2

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 21.12.2012
Time: 12:22
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

/* A
( , ).
.
A
B. , B
, . . A.
*/
using System;
namespace app57_event
{
//
public delegate void MyHandler1(object sender,
MyEventArgs e);
public delegate void MyHandler2(object sender,
MyEventArgs e);
// ()
class A
{
public const string m_id="Class A"; //
// 1- :
public void OnHandler1(object sender, MyEventArgs e)

13.
{
Console.WriteLine(" 1- " +
" : {0}", e.m_id);
}
// 2- :
public void OnHandler2(object sender,MyEventArgs e)
{
Console.WriteLine(" 2- " +
" : {0}", e.m_id);
}
//
// ( )
public A(B b)
{
// ,
// (
// ):
// .
// :
//
d1(1- , 2- );
MyHandler1 d1=new MyHandler1(OnHandler1);
//
// :
MyHandler2 d2=new MyHandler2(OnHandler2);
// Event1, Event2
// OnHandler1 OnHandler2.
// :
// Event1( , )
b.Event1 +=d1; //
b.Event2 +=d2;
}
}
//
class B
{
public event MyHandler1 Event1; // 1
// ( 1- )

299

300

II. -
public event MyHandler2 Event2; // 2. 2-
// . 2-
public void FireEvent1(MyEventArgs e) //
//
{
if(Event1 != null)
{
Event1(this, e); // Event1
//
}
}
public void FireEvent2(MyEventArgs e)
{
if(Event2 != null)
{ Event2(this,e); }
}

}
// ,
//
public class MyEventArgs : EventArgs
{ public string m_id; }
public class Program
{
public static void Main()
{
B b= new B();
A a= new A(b);
MyEventArgs e1=new MyEventArgs(); // ,
// 1-
MyEventArgs e2=new MyEventArgs(); // ,
// 2-
e1.m_id =" 1";
e2.m_id =" 2";
//
// :
b.FireEvent1(e1); // 1-
b.FireEvent2(e2); // 2-

13.

301

Console.Read();
}
}
}

. 13.2.

, , (
, )
public event MyHandler1 Event1;

MyHandler1 , Event1. event


. IL Dasm
(Tools | IL Dasm), ,
: Add_.() Remove_.().
, . ,
, , , . . . .

public void FireEvent1(MyEventArgs e)

( )
if(Event1 != null), :
? , .
+= -=.
Add_.Event1()
Remove_.Event1(). .
,
.
, ,
. . . d1 ,

302

II. -

d2 .
+= .
, .
:
MyHandler1 d1=new MyHandler1(OnHandler1);
MyHandler1 d2=new MyHandler1(OnHandler2);

,
, . , ,
, -=. ,
b.Event2 -=d2;


, . ,
, . . . 13.3,
. 13.3.
13.3

/* Created by SharpDevelop.
* User: user
* Date: 22.12.2012
* Time: 15:44
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app59_anonim1
{
static class A
{
//
public delegate void Anonim2(int start, int finish);
public static int Speed = 150;

13.
//
//
//
//
//
//
//

,

10 .
: ,
, ,

,

}
class Program
{
public static void Main()
{
Console.WriteLine(" \n " +
" ");
A.Anonim2 anonim2 = delegate(int a, int b)
{
for (int i = a; i <= b; i++)
Console.Write(" {0} " +
":{1}\n", i, A.Speed (b-i));
};
anonim2(1, 10);
Console.Read();
}
}
}

. 13.3.

303

304

II. -

delegate , ,
, ,
. ,
. , .
13.4, . 13.4.
13.4

/* Created by SharpDevelop.
* User: user
* Date: 22.12.2012
* Time: 18:52
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app61_anonim3
{
class Program
{
delegate void DelegateType();
static DelegateType GetMethod()
{ return delegate()
{ System.Console.WriteLine("Hello"); };
}
static void Main()
{ DelegateType delegateInstance = GetMethod();
delegateInstance();
Console.Read();
}
}
}

. 13.4.

13.

305

delegate ,
, .
.
, +=,
( ,
). 13.5, . 13.5.
13.5

/* Created by SharpDevelop.
* User: user
* Date: 22.12.2012
* Time: 19:51
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app62_anonim3
{
class Program
{
delegate void DelegateType();
static void Main()
{
DelegateType delegateInstance = delegate()
{ Console.WriteLine("Hello"); };
delegateInstance += delegate() //
//
{ Console.WriteLine("Bonjour"); };
delegateInstance();
Console.Read();
}
}
}

306

II. -

. 13.5.

-
.
13.6, . 13.6.
13.6

/* Created by SharpDevelop.
* User: user
* Date: 23.12.2012
* Time: 12:16
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app63_lambda1
{
class Program
{
public delegate int Ar(int x);
public static int Add(int x)
{ return -x; }
static void Main()
{
Console.WriteLine(" " +
" -\n");
// ,
//
Ar b = new Ar(Add);

13.

307

// Ar d = x => -x; // -
// ,
Func<int,int> d = x => -x; // -
// Add()
// -
Console.WriteLine(" " +
": {0}", b(2));
Console.WriteLine(" " +
"L-: {0}", d(2));
Console.Read();
}
}
}

. 13.6. -

. 13.6 , , : ,

Func<int,int> d = x => -x;

- x => -x;. " x


x".
. ,
. delegate
Func<T,T> ( ).
Func<> , System,
, . d,
, int int. ,
-
. - d,

308

II. -

, x int, int. - :
Ar d = x => -x;

13.6 - (). . , - :
(_) =>

- ,
( ),
. . ,
(x, y) => x == y


. ,
:
(int x, string s) => s.Length > x

(. . )
:
() => SomeMethod()

-
( ) . :
(_) => {()};

-
; . - 13.7,
. 13.7.
13.7

/* Created by SharpDevelop.
* User: user
* Date: 23.12.2012

13.
* Time: 14:08
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
namespace app64_lambda2
{
class Program
{
delegate int del(int i);
delegate void Test(string s);
delegate int Test2(int x, int y);
public static void Main()
{
Console.WriteLine("- " +
"-");
// -
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
Console.WriteLine("-: {0}",j);
//
// -
Test myDel = n =>
{
string s = n + " " + "World";
Console.WriteLine(s);
// return n;
// return ,
// void
};
Console.WriteLine("-: ");
myDel("Hello,");
// -
//
Console.WriteLine(" "+
" -");
Test2 myT = (x, y) =>

309

310

II. -
{
int z=x+y;
Console.Write("x+y=");
return z;
};
Console.WriteLine("{0}", myT(2,2));
Console.Read();
}

}
}

. 13.7. - -

14

LINQ
,
( ). :
, ,
, XML.
,
.
, . , SQL XQuery
XML. ,
, . LINQ ,

. LINQ
.
XML-, SQL, ADO.NET, .NET , LINQ,
.
LINQ (Language Integrated Query, )
Microsoft , SQL, .NET Framework.
, , SQL. LINQ
C#. LINQ ,
. , LINQ, :
 LINQ to Objects LINQ

312

II. -

 LINQ to XML LINQ

XML;
 LINQ to DataSet LINQ

DataSet ADO.NET;
 LINQ to Entities LINQ API-

ADO.NET Entitie Framework;


 Parallel LINQ -

, LINQ.
LINQ to Objects
System.Linq.


LINQ :
 ;
 ;
 .


.
. , . 14.1,
. 14.1.
14.1

/* Created by SharpDevelop.
* User: user
* Date: 24.12.2012
* Time: 14:12
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Linq; //
// LINQ to Objects
namespace app65_linq
{
class Program

14. LINQ
{
public static void Main(string[] args)
{
Console.WriteLine(" LINQ");
// LINQ-:
// 1. .
int[] n = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
Console.WriteLine(" :");
foreach (int num in n)
{ Console.WriteLine("{0} ", num); }
// 2. .
// Query IEnumerable<int>
var Query =
from num in n
where (num % 2) == 0 //
select num;
// 3.
Console.WriteLine("( " +
"):");
foreach (int num in Query)
{ Console.Write("{0} ", num); }
Console.Read();
}
}
}

. 14.1. LINQ

313

314

II. -

,
IEnumerable<T>.
, LINQ. foreach, foreach
IEnumerable IEnumerable<T>.
from, in, where, select. . LINQ:
 from, in .

n num;
 where ,

.
: " num ( , ) 2 ";
 select -

. "";
 join, on, equals, into -

, ;
 orderby, ascending, descending -

;
 group, by (),

.
( , , , ,
, ,
) ,
System.Linq.Enumerable. Revers<>(), ToList<>(),
ToArray<>() .

, from, in, where, select. where
. :
var () = from in select
_

;
var; , ; -

14. LINQ

315

, ; _

" " num (


, , ) , , select. , - " ",
, 14.2.
14.2

/* Created by SharpDevelop.
* User: user
* Date: 24.12.2012
* Time: 16:40
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Linq;
namespace app66_linq
{
class Program
{
public class dict
{
public int a
{get; set;}
public int b
{get; set;}
public dict(int A, int B)
{ a=A; b=B; }
static void Main()
{ Console.WriteLine(" LINQ");
// LINQ-:
// 1. .
dict [] n = new dict[4];

316

II. -
// ,
//
//
n[0] = new dict(1,1);
n[1] = new dict(2,2);
n[2] = new dict(3,3);
n[3] = new dict(4,4);;
Console.WriteLine(" " +
"( a,b):");
foreach (dict num in n)
{ Console.WriteLine("{0} {1} ", num.a, num.b); }
// 2. .
// Query IEnumerable<int>
var Query =
from num in n
where (num.a % 2) == 0 //
// a
select num.a;
// 3.
Console.WriteLine("( a- "+
"):");
foreach (int num in Query)
{
Console.WriteLine("{0} ", num.ToString());
}
Console.WriteLine(" " +
": {0}", Query.Count());
Console.Read();
}
}

}
}

14.1.
dict . , num
- , num.a, select, , .

14. LINQ

317

. 14.2. LINQ

. 14.2.
14.2, , LINQ.
,
. 14.3, . 14.3.
14.3

/* Created by SharpDevelop.
* User: user
* Date: 24.12.2012
* Time: 16:40
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
namespace app67_linq_sort
{
using System;
using System.Linq;
class Program
{
public class dict
{
public int a
{get; set;}

318

II. -
public
int b
{get; set;}
public dict(int A, int B)
{ a=A; b=B; }
static void Main()
{ Console.WriteLine(" LINQ. " +
"");
// LINQ-:
// 1. .
dict [] n = new dict[4];
// ,
//
//
n[0] = new dict(11,5);
n[1] = new dict(2,8);
n[2] = new dict(3,4);
n[3] = new dict(14,4);;
Console.WriteLine(" "+
"( a,b):");
foreach (dict num in n)
{ Console.WriteLine("{0} {1} ", num.a, num.b); }
// 2. .
// Query IEnumerable<int>
var Query =
from num in n
where (num.a % 2) == 0
// a-
orderby num.b
select num.b;

//

// 3.
Console.WriteLine(" ( " +
" b- ):");
foreach (int num in Query)
{ Console.WriteLine("{0} ", num.ToString()); }
Console.Read();
}
}
}
}

14. LINQ

319

. 14.3. LINQ

LINQ
, , . .
.
, 14.4. . 14.4.
14.4

/* Created by SharpDevelop.
* User: user
* Date: 24.12.2012
* Time: 16:40
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
namespace app68_linq_sort
{
using System;
using System.Linq;
class Program
{
public class dict
{
public int a
{get; set;}

320

II. -
public
int b
{get; set;}
public dict(int A, int B)
{ a=A; b=B; }
static void Main()
{ Console.WriteLine(" LINQ. " +
"");
// LINQ-:
// 1. .
dict [] n = new dict[4];
// ,
//
//
n[0] = new dict(11,5);
n[1] = new dict(2,8);
n[2] = new dict(3,4);
n[3] = new dict(14,4);;
Console.WriteLine(" " +
"( a,b):");
foreach (dict num in n)
{ Console.WriteLine("{0} {1} ", num.a, num.b); }
// 2. .
// Query IEnumerable<int>
var Query =
from num in n
orderby num.b
select num;
// 3.
Console.WriteLine(" ( " +
" b- ):");
foreach (dict num in Query)
{ Console.WriteLine("{0} {1} ", num.a, num.b); }
Console.Read();
}
}

}
}

14. LINQ

321

. 14.4.

ascending ( ), . . , .
, orderby <,
> descending ( ).

LINQ
,
14.5, . 14.5.
14.5

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 25.12.2012
Time: 13:20
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

using System;
using System.Linq;
using System.Collections.Generic;
namespace app69_linq_except
{
class Program

322

II. -

{
//
// LINQ
//
static void DisplayDiff()
{
List<string> myCars = new List<String> {"Yugo",
"Aztec", "BMW"};
List<string> yourCars = new List<String> {"BMW",
"Saab", "Aztec"};
Console.WriteLine(" :");
foreach (string s in myCars)
Console.Write("{0}\t",s);
Console.WriteLine();
foreach (string s in yourCars)
Console.Write("{0}\t",s);
Console.WriteLine();
// ,
//
var carDiff = (from c in myCars select c)
.Except(from c2 in yourCars select c2);
Console.WriteLine(" " +
" ");
foreach (string s in carDiff)
Console.WriteLine(s); //
// , Yugo
}
//
static void Displaylntersection()
{
List<string> myCars = new List<String> { "Yugo",
"Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW",
"Saab", "Aztec" };
//
var carlntersect = (from c2 in myCars select c2)
.Intersect(from c2 in yourCars select c2);

14. LINQ
Console.WriteLine("\n " +
":");
foreach (string s in carlntersect)
Console.WriteLine(s); // Aztec BMW
}
// (
// )
static void DisplayUnion ()
{
List<string> myCars = new List<String> { "Yugo",
"Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW",
"Saab", "Aztec" };
//
var carUnion = (from c3 in myCars select c3)
.Union(from c3 in yourCars select c3);
Console.WriteLine("\n " +
"( ):");
foreach (string s in carUnion)
Console.WriteLine (s); //
Console.WriteLine();
}
// ()
static void DisplayConcat ()
{
List<string> myCars = new List<String> { "Yugo",
"Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW",
"Saab", "Aztec" };
//
var carConcat = (from c4 in myCars select c4)
.Concat(from c4 in yourCars select c4);
Console.WriteLine ("\n " +
"( ):");
foreach (string s in carConcat)
Console.WriteLine (s);
}
//
static void DisplayConcatNoDups ()

323

324

II. -
{
List<string> myCars = new List<String> { "Yugo",
"Aztec", "BMW" };
List<string> yourCars = new List<String> { "BMW",
"Saab", "Aztec" };
var carConcat = (from 5 in myCars select 5)
.Concat(from c5 in yourCars select c5);
// Yugo Aztec BMW Saab.
Console.WriteLine ("\n " +
" :");
foreach (string s in carConcat.Distinct ())
Console.WriteLine (s);
}
//
static void AggregateOps ()
{
double[] winterTemps = {5.0, -17.3, 8, -4,
0, -10.6};
Console.WriteLine("\n :");
foreach(double t in winterTemps)
Console.Write("{0}\t",t);
//
//
//
Console.WriteLine("\n : {0}",
(from t in winterTemps select t).Max());
Console.WriteLine(" : {0}",
(from t in winterTemps select t).Min());
Console.WriteLine(" : {0}",
(from t in winterTemps select t).Average ());
Console.WriteLine(" : {0}",
(from t in winterTemps select t).Sum());
}
static void Main()
{
Console.WriteLine(" " +
" ");
DisplayDiff();

14. LINQ
Displaylntersection();
DisplayUnion();
DisplayConcat();
DisplayConcatNoDups();
AggregateOps();
Console.Read();
}
}
}

. 14.5. LINQ-

325

326

II. -

var

, ,
. var : , ,
.

15



Windows
. ,
( ) . exe-
. , . ,
,

.

, PID (Process Identifier), . ,
(<Ctrl>+<Shift>+<Esc>).
,
Main().
.
Main() .
, ( ),
, . . .
, . . -

328

II. -

, - - . , . ,
,
. ,
- , . , , . ( CreateThread()) ,
.
.
, -. -, , . .
- . - () , , ,
, . . .
? , : , , .
.

DLL EXE, . .

.NET? , .
System.Diagnostics, ,
. System.Diagnostics.
 Process -

,
.
 ProcessModule dll exe,

.
 ProcessModuleCollection -

ProcessModule.
 ProcessStartInfo ,

Process.Start().

15. Windows

329

 ProcessThread

.
 ProcessThreadCollection -

ProcessThread.
System.Diagnostics.Process:
 ExitTime ,

, ;
 Id PID

;
 MachineName ,

;
 MainWindowTitle

;
 Moduls -

, ;
 ProcessName , -

;
 Responding , -

, , . . ;
 StartTime ,

;
 Threads , -

;
 CloseMainWindow() , -

, ;
 GetCurrentProcess() Process,

;
 GetProcesses() Process,

;
 Kill() -

;
 Start() .

330

II. -


, ,
, 15.1,
. 15.1.
15.1

/* Created by SharpDevelop.
* User: user
* Date: 26.12.2012
* Time: 13:29
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
namespace app70_Windows_Processes
{ /* ,
, PID*/
class Program
{
public static void ListAllRunningProcesses()
{
var runmngProcs =
from proc in Process.GetProcesses (".") orderby proc.Id
select proc;
foreach (var p in runmngProcs)
{
string info =
string.Format("-> PID: {0}\tName: {1}",
p.Id, p.ProcessName);
Console.WriteLine (info);
}
Console.WriteLine("************************************");
}

15. Windows

331

public static void Main(string[] args)


{
Console.WriteLine(", " +
" ");
ListAllRunningProcesses();
Console.Read();
}
}
}

. 15.1.

GetProcesses() public static Process[]


GetProcesses().
Process. Process, , Id ,
ProcessName Id. GetProcesses()
. , ,
. Format
string .

332

II. -

WriteLin(). :
info , WriteLin(). GetProcesses()
, ,
Linq, System.Linq.


,
, GetCurrentProcess(). , , 15.2,
. 15.2.
15.2

/* Created by SharpDevelop.
* User: user
* Date: 26.12.2012
* Time: 14:27
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
namespace app71_GetProcId
{
class Program
{
static void EnumThreadsForPid (int pID)
{
Process theProc = null;
try
{
theProc = Process.GetProcessById(pID);
Console.WriteLine(" : {0}",
theProc.MachineName);

15. Windows

333

if(theProc.MachineName == ".")
Console.WriteLine(" : ");
}
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message); }
}
public static void Main()
{
Console.WriteLine(" " +
" ");
EnumThreadsForPid (1572);
Console.Read();
}
}
}

. 15.2.

GetProcessById() Process. .
. ,
, 15.1, ,
. theProc null,
try{} , theProc. - , ArgumentException.


, .
Process Threads,
. ProcessThreadCollection,

334

II. -

. . Threads Process ProcessThreadCollection.


ProcessThreadCollection . 15.115.4.
15.1. ProcessThreadCollection

ProcessThreadCollection

. ProcessThreadCollection

15.2. ProcessThreadCollection

Add()

Contains()

CopyTo()


ProcessThread

GetEnumerator()

,

ReadOnlyCollectionBase (
ReadOnlyCollectionBase)

IndexOf()

Insert()

Remove()

ToString()

String,
Object ( Object)

15.3. ProcessThreadCollection

Count

, ReadOnlyCollectionBase

InnerList

, ReadOnlyCollectionBase

Item

15. Windows

335

15.4.

ICollection.CopyTo

ReadOnlyCollectionBase
Array,

,
, , . Threads
() theProc Process.
15.3, . 15.3.
15.3

/* Created by SharpDevelop.
* User: user
* Date: 26.12.2012
* Time: 14:27
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
namespace app71_GetProcId
{
class Program
{
public static Process theProc;
static void EnumThreadsForPid (int pID)
{
theProc = null; // Process
try
{
theProc = Process.GetProcessById(pID);
Console.WriteLine(" : {0}",
theProc.MachineName);

336

II. -
if(theProc.MachineName == ".")
Console.WriteLine(" : ");
}
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message); }
}
public static void Main()
{
Console.WriteLine(" " +
" ");
EnumThreadsForPid (1572);
Console.WriteLine(", " +
": {0}",
theProc.ProcessName);
ProcessThreadCollection theThreads =
theProc.Threads;
// Threads ProcessThreadCollection,
// ProcessThread
foreach(ProcessThread pt in theThreads)
{
string info =
string.Format("-> Thread ID: {0}\tStart Time {1}\tPriority

{2}",
pt.Id, pt.StartTime.ToShortTimeString(),
pt.PriorityLevel);
Console.WriteLine(info);
}
Console.WriteLine ("************* ^ " +
"********************** \n");
Console.Read();
} // Main()
} // Program
} // NameSpace

: , System.Diagnostics. ,
pt foreach. .

.

15. Windows

337

. 15.3. 1572 chrome

int.
15.4. . 15.4.
15.4

/* Created by SharpDevelop.
* User: user
* Date: 26.12.2012
* Time: 14:27
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
namespace app71_GetProcId
{
class Program
{
public static Process theProc;
static void EnumThreadsForPid (int pID)
{
theProc = null; // Process
try

338

II. -
{
theProc = Process.GetProcessById(pID);
Console.WriteLine(" : {0}",
theProc.MachineName);
if(theProc.MachineName == ".")
Console.WriteLine(" : ");
}
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message); }
}
public static void Main()
{
while(true)
{ //
Console.WriteLine(" " +
" (<->) > ");
Console.Write("PID: ");
string pID = Console.ReadLine();
if(pID=="")
pID = Console.ReadLine();
if(pID=="-")
break;
int theProcID = int.Parse(pID);
Console.WriteLine(" " +
" ");
EnumThreadsForPid(theProcID);
Console.WriteLine(", " +
": {0}",
theProc.ProcessName);
ProcessThreadCollection theThreads =
theProc.Threads;
foreach(ProcessThread pt in theThreads)
{
string info =
string.Format("-> Thread ID: {0}\tStart Time
{1}\tPriority {2}",
pt.Id, pt.StartTime.ToShortTimeString(),
pt.PriorityLevel);
Console.WriteLine(info);
}
Console.WriteLine("************* ^ "+
"********************** \n");

15. Windows
Console.Read();
} // while
Console.Read();
} // Main()
} // Program
} // NameSpace

. 15.4.

339

340

II. -

, Threads ProcessThreadCollection, ProcessThread. ProcessThread Id, StartTime, PriorityLevel, ,


. , :
 CurrentPriority ;
 ProcessorAffinity , -

;
 StartAdress ,

, ;
 ThreadState ;
 TotalProcessorTime ,

;
 WaitReason , -


, System.Diagnostics
ProcessModuleCollection, ProcessModule. ,
.
15.5, . 15.5.
15.5

/* Created by SharpDevelop.
* User: user
* Date: 27.12.2012
* Time: 11:05
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;

15. Windows
namespace app72_proc_modul
{
class Program
{
public static Process theProc;
public int pID;
//
static void EnumModsForPid (int pID)
{
Process theProc = null;
try
{ theProc = Process.GetProcessById(pID); }
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message);
return;
}
Console.WriteLine(", " +
": {0}", theProc.ProcessName);
try
{
ProcessModuleCollection theMods = theProc.Modules;
// Modules ProcessModuleCollection,
// ProcessModule
foreach(ProcessModule pm in theMods)
{
string info = string.Format("-> : " +
"{0}", pm.ModuleName);
Console.WriteLine(info);
}
}
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message);
return;
}
} //
//
static void EnumThreadsForPid (int pID)
{
theProc = null; // Process
try

341

342

II. -
{
theProc = Process.GetProcessById(pID);
Console.WriteLine(" : {0}",
theProc.MachineName);
if(theProc.MachineName == ".")
Console.WriteLine(" : ");
}
catch(ArgumentException ex)
{ Console.WriteLine(ex.Message); }
}
public static void Main()
{
while(true)
{ //
Console.WriteLine (" " +
" (<->) > ");
Console.Write("PID: ");
string pID = Console.ReadLine();
if(pID=="")
pID = Console.ReadLine();
if(pID=="-")
break;
int theProcID = int.Parse(pID);
EnumThreadsForPid (theProcID);
EnumModsForPid (theProcID);

Console.WriteLine ("************* ^ " +


"********************** \n");
Console.Read();
} // while
Console.Read();
} // Main()
} // Program
} // NameSpace

, .

15. Windows

343

. 15.5. , Skype



, Process Kill()
Start(), .
, , 15.6, . 15.6.
15.6

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 27.12.2012
Time: 14:07

344

II. -

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.Threading;
namespace app74_start_kill2
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" ");
// .
Process process = Process.Start("notepad.exe");
Console.WriteLine(" " +
" <Enter>");
Console.Read();
process.Kill();
Console.Read();
}
}
}

<Enter>.
Start() System.Diagnostics.
ProcessStartlnfo, . :
public sealed class ProcessStartlnfo : object
{
public ProcessStartlnfo();
public ProcessStartlnfo(string fileName);
public ProcessStartlnfo(string fileName,
string arguments);
public string Arguments { get; set; }
public bool CreateNoWindow { get; set; }

15. Windows
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public
public

345

StringDictionary EnvironmentVariables { get; }


bool ErrorDialog { get; set; }
IntPtr ErrorDialogParentHandle { get; set; }
string FileName { get; set; }
bool LoadUserProfile { get; set; }
SecureString Password { get; set; }
bool RedirectStandardError { get; set; }
bool RedirectStandardlnput { get; set; }
bool RedirectStandardOutput { get; set; }
Encoding StandardErrorEncoding { get; set; }
Encoding StandardOutputEncoding { get; set; }
bool UseShellExecute { get; set; }
string Verb { get; set; }
string [] Verbs { get; }
ProcessWindowStyle WindowStyle { get; set; }
string WorkingDirectory { get; set; }

. 15.6. ( )

MSDN
C#. FileName, , -

346

II. -

- , , StartInfo.
UseShellExecute Process true. false, ,
. 15.7, . 15.7.
JPG.
15.7

/* Created by SharpDevelop.
* User: user
* Date: 27.12.2012
* Time: 15:26
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace app75_start_info
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" , " +
" ");
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = true;
// ,
//
myProcess.StartInfo.FileName =
"F:\\\\9 2012 ..jpg";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
catch (Exception e)
{ Console.WriteLine(e.Message); }

15. Windows

347

Console.Read();
}
}
}

. 15.7. Start() JPG

, ? . exe-. ?
, , , , 100 ,
, . 100 , . ,
, exe-, . , ( )
, .

348

II. -

16

-
-, , . .
-. Console, Read(),
ReadLine(), Write(), WriteLine() .
-:
( , ), ( , ).
:
.
, .
System.IO (System Input/Output).
, -. , System.IO:
 BinaryReader, BinaryWriter -

(, , )
;
 BufferedStream -

,
- ;
 Directory, DirectoryInfo

.
(. .
),

350

II. -

(. . );
 DriveInfo

 File, FileInfo , Directory, DirectoryInfo,

, ;

 FileStream ,

();

 FileSystemWatcher -

 MemoryStream -

, ;

 Path ,

 StreamWriter, StreamReader - -

.
();

 Stream ,

 TextReader , -


StreamReader
StringReader;

 TextWriter

,
StreamWriter
StringWriter.

,
- .

DirectoryInfo
:
 Create(), CreateSubdirectory() ,

 Delete() ;

16. -

351

 GetDirectories() DirectoryInfo,

;
 GetFiles() FileInfo, -

;
 MoveTo() -

;
 Parent ;
 Root .

,
,
, ,
, .
, \
(\\), ( , ,
, ,
, ). , ( )
(
\n, \t).
, . . C# @, .
, #
, "" , @. , @for
C#-. ,
- for, @
. ( )
@- . , @ ( ),
.
( ) @, , .

.

352

II. -

, .
DirectoryInfo
16.1, . 16.1.
16.1

/* Created by SharpDevelop.
* User: user
* Date: 28.12.2012
* Time: 12:43
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app76_directory_info
{
class Program
{
static void ShowWindowsDirectorylnfo(string path)
{
// .
// DirectoryInfo
DirectoryInfo dir = new DirectoryInfo(path);
// @"C:\Windows"
Console.WriteLine("***** Directory Info *****");
// :
Console.WriteLine("FullName: {0}", dir.FullName);
// :
Console.WriteLine("Name: {0}", dir.Name);
// :
Console.WriteLine("Parent: {0}", dir.Parent);
// :
Console.WriteLine("Creation: {0}",
dir.CreationTime);
// :
Console.WriteLine("Attributes: {0}",
dir.Attributes);

16. -

353

// :
Console.WriteLine("Root: {0}", dir.Root);
Console.WriteLine("************************** \n" );
}
public static void Main()
{
Console.WriteLine(" ");
ShowWindowsDirectorylnfo(@"C:\Windows");
DirectoryInfo dir2 = new DirectoryInfo(@"D:\");
Console.WriteLine(" :");
//
// , . .
//
dir2.CreateSubdirectory(@"MyNewDir\");
ShowWindowsDirectorylnfo(@"d:\MyNewDir\");
// MoveTo().
// d:\MyNewDir :
// .
// MoveTo() :
// ,
// . .
// ()
DirectoryInfo dir3 =
new DirectoryInfo(@"d:\MyNewDir\");
dir3.MoveTo(@"d:\MyNewDir2\");
// D:\
foreach(DirectoryInfo d in dir2.GetDirectories())
Console.WriteLine("{0} \n",d);
Console.Read();
}
}
}

, ShowWindowsDirectorylnfo() . MyNewDir , C:\Windows, ,

354

II. -

.
MoveTo(), ,
. ( ) .
:
. , MoveTo(), D:. ( . 16.1
MyNewDir2. MyNewDir . .)

. 16.1. DirectoryInfo

Directory
.
. ,

16. -

355

,
, DirectoryInfo. 16.2,
. 16.2.
16.2

/* Created by SharpDevelop.
* User: user
* Date: 29.12.2012
* Time: 12:06
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app77_directory
{
class Program
{
static void DirectoryType ()
{
//
string [] drives = Directory.GetLogicalDrives();
Console.WriteLine(" " +
":");
foreach (string s in drives)
Console.WriteLine(" {0} ", s) ;
//
Console.ReadLine();
try
{
Directory.Delete(@"D:\MyNewDir");
Directory.Delete(@"D:\MyNewDir2",true);
// ,
//
}
catch (IOException e)
{ Console.WriteLine(e.Message); }
}

356

II. -
public static void Main(string[] args)
{
Console.WriteLine(" Directory");
DirectoryType ();
Console.Read();
}

}
}

. 16.2.

DriveInfo

. , , , . 16.3, . 16.3.
16.3

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 29.12.2012
Time: 12:56

16. -
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app78_driveinfo
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" DriveInfo");
//
DriveInfo[] myDrives = DriveInfo.GetDrives();
//
foreach(DriveInfo d in myDrives)
{
Console.WriteLine(": {0}", d.Name);
Console.WriteLine(": {0}", d.DriveType);
// ,
if (d.IsReady)
{
//
Console.WriteLine(" : {0}",
d.TotalFreeSpace);
//
Console.WriteLine(": {0}", d.DriveFormat);
//
Console.WriteLine(" : {0}",
d.VolumeLabel);
Console.WriteLine();
}
Console.Read();
}
}
}
}

357

358

II. -

. 16.3.

FileInfo
,
. , ,
.
.
 AppendText() StreamWriter (. )

.
 CopyTo() .

16. -

359

 Create() FileStream (.

) .

 CreateText() StreamWriter,

.
 Delete() .
 Directory , .
 DirectoryName , -

.
 Length .
 MoveTo() ,

.
 Name .
 Open()

-.
 OpenRead()
FileStream.

 OpenText() StreamReader -

.
 OpenWrite()

FileStream.

FileStream (http://
msdn.microsoft.com/ru-ru/library/system.io.filestream.aspx).
, ,
, , , . , .
Create() FileInfo.
FileStream,
Close(), , . .
, . , , , . ,
,
.
Open() FileInfo. : public enum FileMode,

360

II. -

"".
:
public enum FileMode
{ CreateNew, Create, Open, OpenOrCreate, Truncate, Append }

Open().
:
 CreateNew . , -

IOException;
 Create . ,

;
 Open .

, FileNotFoundException;
 OpenOrCreate , .

, ;
 Truncate ;
 Append , , .

. FileMode.Append
FileAccess.Write. (
, ,
:
. . Append : " ", . .
-.)
Open() , , . :
public enum FileAccess
{
Read,
Write,
ReadWrite
}

,
, , .

16. -

361

Open() ,
. :
public enum FileShare
{
None,
Read,
Write
ReadWrite,
Delete,
Inheritable
}

:
 None . -

( ) , ;
 Read .

,
( )
, ;
 Write .

,
( )
, ;
 ReadWrite

. , ( )
, ;
 Delete ;
 Inheritable -

. Win32 ( , ,
).
, , AppendText(). 16.4, . 16.4.

362

II. -

16.4

/* Created by SharpDevelop.
* User: user
* Date: 29.12.2012
* Time: 13:52
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app79_fileinfo
{
class Program
{
public static void Main(string[] args)
{
FileInfo f = new FileInfo(@"D:\Test.txt");
StreamWriter sw = f.AppendText(); //
// StreamWriter
sw.WriteLine(" 1");
sw.WriteLine(" 2");
sw.WriteLine(" 3");
sw.Close();
//
string s;
Console.WriteLine(" ");
StreamReader sr = f.OpenText();
s = sr.ReadLine();
Console.WriteLine(s);
s = sr.ReadLine();
Console.WriteLine(s);
s = sr.ReadLine();
Console.WriteLine(s);
sr.Close();
Console.ReadKey(true);
}
}
}

16. -

363

. 16.4. AppendText()

AppendText() , ,
Create(). FileInfo

AppendText(),
sw StreamWriter,
WriteLine(), .
, , .
.
, .
OpenText(), sr
StreamReader. ReadLine(),
:
, ( )
.
ReadLine() s . . . " ": " ". StreamReader
Close(). . , , , . , .
.

File
FileInfo:
AppendText(), Create(),
CreateText(), Open(), OpenRead(), OpenWrite(), OpenText(). , - . :
 ReadAllBytes() ,

364

II. -

 ReadAllLines() ,

;
 ReadAllText() ,

, string ;
 WriteAllBytes() ,

;
 WriteAllLines() , -

. public
static
void
WriteAllLines(string
path,IEnumerable<string>
contents),

contents

Type:
System.Collections.Generic.IEnumerable<String> ();
 WriteAllText() ,

. public static void


WriteAllText(string path, string contents), contents
.
WriteAllLines() ReadAllText() , 16.5, . 16.5.
16.5

/* Created by SharpDevelop.
* User: user
* Date: 30.12.2012
* Time: 13:29
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app80_file
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" File");
string [] MyArr = {"1","2","3"}; //
//

16. -

365

// :
File.WriteAllLines(@"D:\Test.txt",MyArr);
// :
string s = File.ReadAllText(@"D:\Test.txt");
Console.WriteLine(" : ");
Console.WriteLine(s);
Console.Read();
}
}
}

. 16.5. WriteAllLines() ReadAllText():


, ; s,
ReadAllText(); ,

. 16.5, ReadAllText(),
: , ,
. (\r)
(\n).

366

II. -

Stream
, .
.
. :
( , , , ; ""
), , . . .
. Stream
.
. :
.
. :
, , ( )
. Stream
, ( ). Stream:
 CanRead , ;
 CanWrite , ;
 CanSeek , ;
 Close()

 Flush() -

( , ) .
, Flush() ;

 Length ;
 Position ( -

);

 Read() -

 ReadByte() , Read(), ;

16. -

367

 Seek() (

);
 SetLength() ;
 Write() -

;
 WriteByte() , Write(), .

FileStream
Stream.
.
, , : . . ,
System.Text
Encoding,
. FileStream.Write(),
, Position
ReadByte().
16.6, . 16.6.
16.6

/* Created by SharpDevelop.
* User: user
* Date: 30.12.2012
* Time: 15:33
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
using System.Text;
namespace app81_filestream
{
class Program

368

II. -

{
public static void Main()
{
Console.WriteLine(" FileStream");
//
FileStream f= File.Open(@"D:\myTest22.txt",
FileMode.Create);
//
string msg = " FileStream";
byte[] Arr = Encoding.Default.GetBytes(msg);
// Default
// ANSI
//
f.Write(Arr, 0, Arr.Length); /* 0
,
*/
//
f.Position = 0;
//
Console.Write(" " +
"( ):\n");
byte[] b = new byte[Arr.Length];
for (int i = 0; i < Arr.Length; i++)
{
b[i] = (byte)f.ReadByte();
// ReadByte() ,
// Int32,
// byte
Console.Write(b[i]);
}
//
Console.Write("\n " +
"(, ):\n");
Console.WriteLine(Encoding.Default.GetString(b));
Console.Read();
} // Main()
}
}

16. -

369

. 16.6. FileStream

StreamWriter, StreamReader
( ,
, ).
Unicode,
System.Text.Encoding. StreamReader
TextReader, StreamWriter TextWriter.
StreamWriter.
:
 StreamWriter(Stream)
StreamWriter , UTF-8
;

 StreamWriter(String)
StreamWriter ;

 StreamWriter(Stream, Encoding) -

StreamWriter ,
;
 StreamWriter(String, Boolean)

StreamWriter
. ,
, .
, ;
 StreamWriter(Stream, Encoding, Int32)

StreamWriter , ;
 StreamWriter(String, Boolean, Encoding)

StreamWriter

370

II. -

.
, ,
. , ;
 StreamWriter(Stream, Encoding, Int32, Boolean) -

StreamWriter , , ;
 StreamWriter(String, Boolean, Encoding, Int32) -

StreamWriter
, .
, ,
. , .
:
 AutoFlush , ,
StreamWriter StreamWriter.Write;

 BaseStream ,

;
 Encoding Encoding,

( TextWriter.Encoding);
 NewLine ,

TextWriter.
:
 Close() StreamWriter ;
 Dispose() , ;
 TextWriterDispose(Boolean) (

) ,
StreamWriter;

 Flush() -

;
 FlushAsync

;
 ToString() ,

16. -

371

 Write(Boolean) -

Boolean;
 Write(Char) ;
 Write(Char[]) ;
 Write(Decimal)

;
 Write(Double) -

8 ;
 Write(Int32)

4 ;
 Write(Int64)

8 ;
 Write(Object) -

ToString()
;
 Write(Single) -

4 ;
 Write(String) ;
 Write(UInt32) -

4 ;
 Write(UInt64) -

8 ;
 Write(String, Object)

, ,
String.Format(String, Object);
 Write(String, Object[])

, ,
String.Format(String, Object[]);
 Write(Char[], Int32, Int32) -

;
 Write(String, Object, Object)

, ,
String.Format(String, Object, Object);
 Write(String, Object, Object, Object) -

, , String.Format(String, Object, Object, Object);

372

II. -

 WriteAsync(Char) ;
 WriteAsync(Char[]) -

;
 WriteAsync(String) ;
 WriteAsync(Char[], Int32, Int32) -

;
 WriteLine()

;
 WriteLine(Boolean)

Boolean, ;
 WriteLine(Char) -

, ;
 WriteLine(Char[]) -

, ;
 WriteLine(Decimal)

,
;
 WriteLine(Double) -


8 , ;
 WriteLine(Int32) -

4 ,
;
 WriteLine(Int64) -

8 ,
;
 WriteLine(Object) -

ToString()
, ;
 WriteLine(Single) -


4 , ;
 WriteLine(String)

, ;

16. -

373

 WriteLine(UInt32) -

4 ,
;
 WriteLine(UInt64) -

8 , ;
 WriteLine(String, Object)

, , String.Format(String, Object);
 WriteLine(String,

Object[])
, , Format;

 WriteLine(Char[], Int32, Int32)

,
;
 WriteLine(String, Object, Object) -

, , String.Format(String, Object,
Object);
 WriteLine(String, Object, Object, Object) -

, ,
Format;
 WriteLineAsync()

;
 WriteLineAsync(Char) ,

;
 WriteLineAsync(Char[])

,
;
 WriteLineAsync(String) ,

;
 WriteLineAsync(Char[], Int32, Int32)

,
.
:
 CoreNewLine ,
TextWriter;

 Null.

374

II. -

, , 09
, 16.7,
. 16.7.
16.7

/* Created by SharpDevelop.
* User: user
* Date: 31.12.2012
* Time: 18:24
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app82_streamwriter
{
class Program
{
public static void Main()
{
Console.WriteLine(" StreamWriter");
// CreateText StreamWriter:
StreamWriter w = File.CreateText (@"D:\Test.txt");
w.WriteLine(" ");
w.WriteLine(" " +
" ");
w.WriteLine(" 10 ");
//
w.Write (w.NewLine); // NewLine \r\n
//
for(int i = 0; i < 10; i++)
w.Write (i + " ");
w.Close();
Console.Read();
}
}
}

16. -

375

. 16.7. 16.7

StreamReader.
:
 StreamReader(Stream)
StreamReader ;

 StreamReader(String)
StreamReader ;

 StreamReader(Stream, Boolean)

StreamReader
;
 StreamReader(Stream, Encoding) -

StreamReader ;
 StreamReader(String, Boolean)

StreamReader ;
 StreamReader(String, Encoding) -

StreamReader ;
 StreamReader(Stream, Encoding, Boolean)

StreamReader ;
 StreamReader(String, Encoding, Boolean)

StreamReader
;
 StreamReader(Stream, Encoding, Boolean, Int32) -

StreamReader -

376

II. -

, ;
 StreamReader(String Encoding, Boolean Int32)

StreamReader
,
.
:
 BaseStream ;
 CurrentEncoding , -

StreamReader;
 EndOfStream , ,

.
:
 Close() StreamReader -

, ;
 DiscardBufferedData() ;
 Dispose() ,
TextReader;

 Dispose(Boolean) , -

, StreamReader, , , ;
 Peek() , -

;
 Read() -

;
 Read(Char[], Int32, Int32)

, ;
 ReadBlock() -

count buffer,
index;
 ReadLine() -

;
 ReadToEnd() ;
 ToString() , .

16. -

377

: Null StreamReader .
, StreamReader, 16.8, . 16.8. ,
, ().
, 16.7.
, . ,
, , . , . 16.7, WordPad.
16.8

/* Created by SharpDevelop.
* User: user
* Date: 01.01.2013
* Time: 17:31
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
namespace app83_streamreader
{
class Program
{
public static void Main()
{
Console.WriteLine(" SteamReader");
//
Console.WriteLine(" :\n");
StreamReader sr = File.OpenText(@"D:\Test.txt");
string input = null;
while ((input = sr.ReadLine()) != null)
{ Console.WriteLine(input); }
Console.Read();
}
}
}

378

II. -

. 16.8. ,
16.7

StreamWriter
StreamReader FileInfo, File ( StreamWriter
StreamReader). StreamWriter
StreamReader , . 16.9, . 16.9.

StreamWriter StreamReader. , ,
.
,
.

StringWriter StringReader
TextWriter TextReader
-
.
StringWriter .
StringBuilder,
.
,
, , . , ,
. . StringBuilder , . -

16. -

379

.
Capacity EnsureCapacity(),
Length.


, .
,
"" , .

, ,
: ,
.
StringBuilder .
:
 StringBuilder() ;
 StringBuilder(Int32)

;
 StringBuilder(String) ,

( - );
 StringBuilder(Int32, Int32)

, , , , ;
 StringBuilder(String, Int32)

, ;
 StringBuilder(String, Int32, Int32, Int32)

,
.
. .
:
 Capacity ;
 Chars , -

380

II. -

 Length

.
:
 Append(Boolean)

;
 Append(Byte) ,

;
 Append(Char) -

Unicode;
 Append(Double)

double;
 Append(Int16) -

int16;
 Append(Int32)

int32;
 Append(Int64) -

int64;
 Append(Object) -

;
 Append(SByte) -

, ;
 Append(Single) -

;
 Append(String) -

( );
 Append(UInt16) -

UInt16;
 Append(UInt32) -

UInt32;
 Append(UInt64) -

UInt64;
 Append(Char, Int32) -

Unicode;
 Append(String, Int32, Int32) -

, ;

16. -

381

 AppendLine()

, ;
 AppendLine(String)

, ;
 Clear() ;
 EnsureCapacity(Int32) , ,

, ;
 Insert(Int32, String)

, ;
 Insert(Int32, String, Int32)

, , , ;
 Remove(Int32, Length)

, , , from this instance;


 Replace(Char, Char) -

, ,
, , ;
 Replace(String, String)

, ,
, , ;
 Replace(Char, Char, Int32, Int32)

,
, ,
, , ;
 Replace(String, String, Int32, Int32) -

,
, , , ,
.
StringWriter.
: StringWriter()
StringWriter.
:
 Close() StringWriter ;

382

II. -

 Flush()

;
 GetStringBuilder() StringBuilder;
 ToString() , ,

StringWriter.
: CoreNewLine() ,
TextWriter.
:
 Encoding Encoding,

;
 FormatProvider , -

;
 NewLine ,

TextWriter.
StringWriter 16.9, . 16.9.
16.9

/* Created by SharpDevelop.
* User: user
* Date: 02.01.2013
* Time: 13:02
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
using System.Text; // StringBuilder
namespace app85_stringwriter
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" StringWriter");
StringWriter sw = new StringWriter();

16. -

383

// StringBuilder,
// :
sw.WriteLine(" ");
StringBuilder sb = sw.GetStringBuilder(); //
// StringBuilder
Console.WriteLine(" StringBuilder'a:\n {0}",sb);
sb.Insert (0, " ! ") ; //
// 0-
// :
Console.WriteLine(" StringBuilder " +
" :");
Console.WriteLine(" {0}", sb.ToString());
// :
// .
// , ,
// ( ,
// )
sb.Remove(0, " ! ".Length);
Console.WriteLine(" StringBuilder " +
" :");
Console.WriteLine(" {0}", sb.ToString ());
Console.WriteLine(" " +
"StringWriter:\n {0}", sw);
Console.Read();
}
}
}

. 16.9. StringWriter

384

II. -

StringReader
StreamReader. ,
,
TextReader.StreamReader,
TextReader.
, 16.9,
StringReader. 16.10,
. 16.10.
16.10

/* Created by SharpDevelop.
* User: user
* Date: 02.01.2013
* Time: 17:07
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.IO;
using System.Text;
namespace app86_stringreader
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(" StringWriter "+
" StringReader");
StringWriter sw = new StringWriter();
// StringBuilder,
// :
sw.WriteLine(" ");
StringBuilder sb = sw.GetStringBuilder(); //
// StringBuilder
Console.WriteLine(" StringBuilder'a:\n {0}",sb);

16. -

385

sb.Insert (0, " ! ") ; //


// 0-
// :
Console.WriteLine(" StringBuilder " +
" :");
Console.WriteLine(" {0}", sb.ToString());
StringReader sr = new StringReader(sw.ToString());
string input = null;
Console.WriteLine(" " +
"StringReader:");
while ((input = sr.ReadLine()) != null)
Console.WriteLine(input);
Console.Read();
}
}
}

. 16.10. StringReader

BinaryWriter BinaryReader
Object.
. BinaryWriter .
:
 BinaryWriter() ;
 BinaryWriter(Stream) ,

, UTF-8;

386

II. -

 BinaryWriter(Stream, Encoding) , -

, , ;
 BinaryWriter(Stream,

Encoding, Boolean)
, , ,
,
.

BaseStream
BinaryWriter.

:
 Close() ;
 Dispose() , -

;
 Flush()

;
 Seek() -

;
 ToString() -

;
 Write(Boolean)

( false)
( true);
 Write(Byte) Byte

;
 Write(Byte[]) ;
 Write(Char) Unicode- -

,
;
 Write(Char[])

,
;
 Write(Decimal) -

16 (
decimal 128 );

 Write(Double) double

16. -

387

 Write(Int16)


;
 Write(Int32)


;
 Write(Int64)


;
 Write(SByte) Byte


;
 Write(Single)

;
 Write(String) -

;
 Write(UInt16)


;
 Write(UInt32) -


;
 Write(UInt64)


;
 Write(Byte[], Int32, Int32)

Byte .
;
 Write(Char[], Int32, Int32) -

.
;
 Write7BitEncodedInt() 32- -

388

II. -

:
 Null BinaryWriter ;
 OutStream .

BinaryReader:
 BaseStream ( ) -

BinaryReader;

 Close() ;
 PeekChar() " ": -

(
);
 Read() -

;
 Readxxxx()
BinaryWriter,
(Boolean, Int16, Int32 . .).

BinaryWriter BinaryReader
, 16.11,
. 16.11.
16.11

/* Created by SharpDevelop;
* User: user
* Date: 03.01.2013
* Time: 13:29
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers; */
using System;
using System.IO;
namespace app87.binarywriterreader
{
class Program
{
public static void Main(string[] args)

16. -

389

{
Console.WriteLine(" " +
"BinaryWriters/Readers \n");
// .
/* BinaryWriter Open(),
* FileInfo */
FileInfo f = new FileInfo(@"D:\BinFile.txt");
BinaryWriter bw = new BinaryWriter(f.OpenWrite());
// BaseStream
Console.WriteLine("Base stream :: {0}",
bw.BaseStream);
// :
double aDouble = 1234.67;
int anlnt = 34567;
string aString = "A,B,C";
bw.Write(aDouble);
bw.Write(anlnt);
bw.Write(aString);
bw.Close();
Console.WriteLine(" :\n");
BinaryReader br = new BinaryReader(f.OpenRead());
Console.WriteLine(" double: {0}",
aDouble);
Console.WriteLine(" Int: {0}", anlnt);
Console.WriteLine(" : {0}", aString);
Console.Read();
}
}
}

, BinaryWriter Open(),
FileInfo.
f.OpenWrite() FileStream, BinaryWriter. , BinaryWriter
, Stream,
FileStream.

390

II. -

. 16.11.

17


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

, ,

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

392

II. -

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

System.Threading, ( ), . :
 Interlocked -

, ;
 Monitor , -

.
lock
Monitor;
 Mutex ,

(. 17.1);
 ParametrizedThreadStart ,

, ;
 Semaphore ,


;
 Thread . -

;
 ThreadPool -

.
, ;
 ThreadPriority ,

(, . .);
 ThreadStart , ,

ParametrizedThreadStart,

( , );

17.

393

 ThreadState ,

(, . .);
 Timer , , -

;
 TimerCallback , Timer.

Thread
:
 CurrentContext ,

;
 CurrentThread .

:
 GetDomain() ,

;
 GetDomainId() , -

;
 Sleep() .

(. . ) :
 IsAlive , ,

(. . );
 IsBackground ,

, ;
 Name ;
 Priority

ThreadPriority;

 ThreadState -

ThreadState;
 Abort() ,

( );
 Interrupt() -

394

II. -

 Join() , , -

Join(), ;
 Resume() -

;
 Start() ,

;
 Suspend() . -

, .
Thread. , 17.1, . 17.1.
17.1

/* Created by SharpDevelop.
* User: user
* Date: 04.01.2013
* Time: 8:18
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;
namespace app88_thred_statistics
{
class Program
{
public static void Main()
{
Console.WriteLine(" Thread. " +
" :");
Thread pr = Thread.CurrentThread; //
//
pr.Name = " "; //
Console.WriteLine(" : {0}",
Thread.GetDomain().FriendlyName); //
// :

17.

395

Console.WriteLine(" " +
": {0}",
Thread.CurrentContext.ContextID);
Console.WriteLine(" : {0}", pr.Name);
Console.WriteLine(" ? {0}",
pr.IsAlive);
Console.WriteLine(" : {0}",
pr.Priority);
Console.WriteLine(" : {0}",
pr.ThreadState);
Console.Read();
}
}
}

. 17.1.

, Main().
, Windows , ,
.
,
, . .

.
,
. ,
. .

396

II. -

, .
, .
, ,
Thread.GetDomain().
, , :
public enum ThreadPriority
{
Lowest,
//
BelowNormal, //
Normal,
//
AboveNormal, //
Highest
//
}


, :
1. , (
Main() ).
2. ParametrizedThreadStart ThreadStart,
,
.
3. Thread, ParametrizedThreadStart ThredStart.
4. : , . .
5. ThreadStart(), .
ThreadStart
(. . , ),

- .
ParametrizedThreadStart ThreadStart
Object. ,
,
. , void ( -

17.

397

). Thread . 17.2, . 17.2.


17.2

/* Created by SharpDevelop.
* User: user
* Date: 04.01.2013
* Time: 10:35
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;
namespace app89_threadStart
{
public class Printer
{
public void PrintNumbers()
{
//
Console.WriteLine("{0} :",
Thread.CurrentThread.Name);
// :
Console.Write(" : ");
for(int i = 0; i < 10; i++)
{
Console.Write ("{0}, ", i);
Thread.Sleep(5000); //
// 5
}
Console.WriteLine ();
} // PrintNumbers()
} // Printer
class Program
{
public static void Main()

398

II. -
{
Console.WriteLine(" " +
"ThreadStart:");
Printer pr = new Printer();
pr.PrintNumbers();
Console.Read();
}

}
}

. 17.2. 10
5


Sleep() 5
. , ,
Thread.Sleep(5000)
5 ( ).
Thread , 17.3.
. 17.3.
17.3

/* Created by SharpDevelop.
* User: user
* Date: 04.01.2013
* Time: 11:06
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;

17.
using System.Windows;

// Project
// PresentationFramework

namespace app90_secondThread
{
public class Printer
{
public void PrintNumbers()
{
//
Console.WriteLine("{0} :",
Thread.CurrentThread.Name);
// :
Console.Write(" : ");
for(int i = 0; i < 10; i++)
{
Console.Write ("{0}, ", i);
Thread.Sleep(5000); //
// 5
}
Console.WriteLine ();
} // PrintNumbers()
} // Printer
class Program
{
public static void Main()
{
Console.WriteLine(" :");
Console.Write(" [1] [2] "+
"? ");
string nt = Console.ReadLine();
Thread pr = Thread.CurrentThread;
pr.Name = " ";
Console.WriteLine("{0} " +
": ",
Thread.CurrentThread.Name);
Printer p = new Printer();
switch(nt)
{
case "2": //

399

400

II. -
{ // .
// ThreadStart
// PrintNumbers():
// void
// .
// .
Thread sec =
new Thread(new ThreadStart(p.PrintNumbers));
sec.Name = " "; //
//
sec.Start(); // .
//
break;
}
case "1":
{
// Thread pr = Thread.CurrentThread;
pr.Name = " "; //
//
Console.WriteLine("{0} "+
": ", Thread.CurrentThread.Name);
// Printer p = new Printer();
p.PrintNumbers();
break;
}
default:
goto case "1";
} // switch
// ,
//
// . ,
// 10 ,
//
// , . .
// 1- (),
// 2- .
MessageBox.Show(", " +
"...");
Console.Read();
}

}
}

17.

401

. 17.3.

. ,
/ -
Windows.Forms.
, , , , ,
.
, : , , ,
. . , ,
. 17.3. , System.Windows,
System.
WPF (Windows Presentation Foundation) PresentationFramework
4.0.0.0. ,
, : Project Add
Reference ( ). ,
GAC
.
using System.Windows;

, :
,
Windows.Forms , 10 -

402

II. -

, 5 .
. ,
,
.
ParameterizedThreadStart
, 17.4.
. 17.4. , ThreadStart , . - ,
ParameterizedThreadStart,
, System.Object.
17.4

/* Created by SharpDevelop.
* User: user
* Date: 04.01.2013
* Time: 15:36
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;
/* WindowsForms
PresentationFramework 4.0.0.0
: */
using System.Windows;
namespace app91_ParametrizedTreadStart
{
class AddParams
{
public int a,b;
public AddParams(int A, int B) //
{ a=A;
b=B; }
}
public class Printer
{
public void PrintNumbers()

17.
{
// :
Console.Write(" : ");
for(int i = 0; i < 10; i++)
{ Console.Write ("{0}, ", i);
Thread.Sleep(5000); //
// 5
}
Console.WriteLine ();
} // PrintNumbers()
} // Printer
class Program
{ // void:
//
// ParameterizedThreadStart
static void Add(object data) //
// AddParam()
{
// ,
// cz AddParams
if(data is AddParams)
{
AddParams ap = (AddParams)data; // data
// object.
//
// :
for(int i = 0; i < 10; i++)
{
Console.Write ("{0}, ", i+ap.a + ap.b);
Thread.Sleep(5000); //
// 5
}
}
}
public static void Main()
{
Console.Write(" [1] " +
" [2] ? ");

403

404

II. -
string nt = Console.ReadLine();
Thread pr = Thread.CurrentThread;
pr.Name = " ";
Console.WriteLine("{0}
Thread.CurrentThread.Name);
Printer p = new Printer();

",

switch(nt)
{
case "2": //
{
// .
// ParameterizedThreadStart
// Add():
// void .
// Add()
//
// AddParams :
AddParams ap = new AddParams(100,200);
// Add() ,
// :
Thread sec =
new Thread(new ParameterizedThreadStart(Add));
sec.Name = " "; //
//
sec.Start(ap); // .
//
Console.WriteLine("{0} ",sec.Name);
break;
}
case "1":
{
p.PrintNumbers();
break;
}
default:
goto case "1";
} // switch

17.

405

/* ,

. ,
10 ,

, . .
1- (),
2- . */
MessageBox.Show(", " +
"...");
Console.Read();
}
}
}

. 17.4.
ParameterizedThreadStart

17.4 17.3. , ParameterizedThreadStart


Add(). object
17.3 , a b
AddParams. ,
. - Add(), 0 9, . -

406

II. -

, Windows.Forms.

AutoResetEvent
, EventWaitHandle.
, , .
.
AutoResetEvent(bool initialState) AutoResetEvent ,
:
true, , false
( , 17.5).
SafeWaitHandle .
:
 Close() ,
WaitHandle;

 GetAccessControl() EventWaitHandleSecurity,

, EventWaitHandle;
 Reset() , -

;
 Set() ,

;
 WaitOne() -

WaitHandle;
 WaitOne(Int32)

WaitHandle , 32- ;
 WaitOne(TimeSpan) -

, TimeSpan ;
 WaitOne(Int32, Boolean)

WaitHandle, 32- -

17.

407

, ,
;
 WaitOne(TimeSpan, Boolean) -

, TimeSpan
, , .
AutoResetEvent , 17.5,
. 17.5.
17.5

/* Created by SharpDevelop.
* User: user
* Date: 05.01.2013
* Time: 11:20
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;
namespace app92_AutoResetEvent
{
class Program
{
//
// AutoResetEvent
const int numIterations = 100;
static AutoResetEvent myResetEvent =
new AutoResetEvent(false);
static int number;
static void Main()
{
// Reader- ()
Thread myReaderThread =
new Thread(new ThreadStart(MyReadThreadProc));
//
myReaderThread.Name = "Reader-";
myReaderThread.Start();

408

II. -
//
// (Writer-):
for(int i = 1; i <= numIterations; i++)
{
Console.WriteLine("Writer-. " +
": {0}", i);
number = i;
// , :
//
// .
// Reader :
myResetEvent.Set();
// Writer-
Thread.Sleep(2000);
}
// Reader
myReaderThread.Abort();
Console.Read();
}
static void MyReadThreadProc()
{
while(true)
{ // ,
// Writer
myResetEvent.WaitOne(); //
// (. . Reader-
// Writer-)
myResetEvent.Reset();
//
// AutoResetEvent
Console.WriteLine("{0} : {1}",
Thread.CurrentThread.Name, number);
}
}

}
}

17.

409

. 17.5. 17.5

AutoResetEvent,
. , , Main(). Writer-.
number, static-.
ThreadProc(), , Main(), . . Writer-.
MyReadThreadProc(), , AutoResetEvent
( Set()).
WaitOne(). Writer- , AutoResetEvent
( Set()), Reader- ( WaitOne() ),
MyReadThreadProc() , Writer, AutoResetEvent
, MyReadThreadProc() .
Writer- Sleep()
. 2 , .

. :
, . .

410

II. -

,
. ? ,
, . . - ,
. 17.5. , ( ,
Windows-)
, ,
Main(). , , .
,
. . number,
. , . -
: ( - ), , ? , -
.
() ().
. ,
. , ,
.
,
.
() . ,
ThreadStart(), .
, , , . . ,
. - , ,
, , . . , , .
, ,
.
.
, ,
Thread, IsBackground (Background
"", Foreground ), true.
17.3:
Thread sec = new Thread(new ThreadStart(p.PrintNumbers));

17.

411

, , .
, :
sec. IsBackground=true;


, (, ),
. , .
, , . , .
,
? , , , ,
, . ,
,
, lock ().
(
, , ).
( ),
, . ,
.
, . , ( ()),
. ,
, , , , . lock.
, lock, 17.6, . 17.6.
17.6

/*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 05.01.2013
Time: 17:23

412

II. -

* To change this template use Tools | Options | Coding |


* Edit Standard Headers. */
using System;
using System.Threading;
namespace app92_lock
{
class Program
{
class Printer
{
private object threadLock = new object();
public void PrintNumbers ()
{
lock (threadLock)
{
Console.WriteLine(" {0} " +
"PrintNumbers()",
Thread.CurrentThread.Name);
Console.Write(": ");
for (int i = 0; i < 5; i++)
{ Thread.Sleep(1000);
Console.Write ("{0}, ", i);
}
} // lock's end
Console.WriteLine();
}
}
}
public static void Main(string[] args)
{
Console.WriteLine(" " +
" lock\n");
Printer p = new Printer();
// 5 ,
//
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++)
{ threads[i] =
new Thread(new ThreadStart(p.PrintNumbers));

17.

413

threads[i].Name =
string.Format(" #{0}", i);
}
//
foreach (Thread t in threads)
t.Start();
Console.Read();
}
}
}

. 17.6. lock.

Timer

. . :
 Change(Int32, Int32)

, 32-
;
 Change(Int64, Int64)

, 64-
;
 Change(TimeSpan, TimeSpan) -

, TimeSpan
;

414

II. -

 Change(UInt32, UInt32)

, 32-
.
,
, . . . . .
Timer
TimerCallback. Timer 17.7, . 17.7.
17.7

/* Created by SharpDevelop.
* User: user
* Date: 06.01.2013
* Time: 12:07
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers. */
using System;
using System.Threading;
namespace app93_Timer
{
class Program
{
//
static void PrintTime(object state)
{
Console.WriteLine(" : {0}",
DateTime.Now.ToLongTimeString());
}
public static void Main(string[] args)
{
Console.WriteLine(" \n");
// Timer
TimerCallback tcb = new TimerCallback(PrintTime);

17.

415

//
Timer t = new Timer (tcb, // TimerCallback
null,
//
// : .
// ,
// null .
0,
//
// ( ).
1000); //
//
Console.Read();
}
}
}

. 17.7.

Timer .
Timer(TimerCallback, Object, Int32, Int32)

Timer, 32- .

416

II. -

18

Windows Forms
. , , ,
. , C#, , , Windows Forms.
, : Windows Forms,
Visual Studio (2010, 2012).
, Windows Forms Application
(, . .) , ,
. . ,
.
.
. Windows Forms
,
.
Windows Forms,
System.Windows.Forms
. : Project | Add Reference.
,
System.Windows.Forms.

using

System. Windows.Forms;

418

II. -

. , Windows Forms
, ( Main()) . .
, Windows
Forms (
), Form. Windows Forms
Application Form Form1. , : Windows-.
, . . ( ), Form2
Form. . . , :
Form1, Form2, ... , -
, . Form.
. , , .
Windows Forms Application: - Form1,
Form.
, Form Form1, Form2, ...
Windows Forms 18.1, . 18.1.
18.1

/*
*
*
*
*
*
*

Created by SharpDevelop.
User: user
Date: 07.01.2013
Time: 11:12
To change this template use Tools | Options | Coding |
Edit Standard Headers. */

// System.Windows.Forms,
// using System.Windows.Forms;
using System;
using System.Windows.Forms;
using System.Collections.Generic;

18. Windows Forms

419

using System.Linq;
using System.Text;
namespace app94_WindowsForm_begin
{
class Program
{
class Form1 : Form
{
public Form1(string title, int height, int width)
{ //
Text = title;
Width = width;
Height = height;
//
//
CenterToScreen ();
}
}
static void Main()
{ // Windows Forms
Application.Run(new Form1("MyForm", 200, 300));
// Windows Forms
//
Console.Read();
}
}
}

Form , .
,
http://msdn.microsoft.com/en-us/library/
system.windows.forms.form.aspx.
Form1 , , .
,
, . CenterToScreen(), (
,
- ).

420

II. -

. 18.1. ( ) Windows Forms

Windows Forms Run()


System.Windows
Application.
http://msdn.microsoft.com/en-us/library/
system.windows.application.aspx.
, Run() , , .


: , , . .
:
1. , Form, - .
2. .
3. ControlCollection
Controls.Add().Control

18. Windows Forms

421

Collection System.Windows.Forms.Control.
ControlCollection, . . System.
Windows.Forms ,

()
. . , ,
: ,
, , ,
ControlCollection.
?
Windows Forms Application,
.
.
, ( ) , , (
Windows) Properties. . Form1, ,
. - Visual C# 2010 2012, Tools,
,
MSDN Microsoft. ,
.
, , 18.2,
. 18.2.
18.2

/* Created by SharpDevelop.
* User: user
* Date: 08.01.2013
* Time: 10:41
*
* To change this template use Tools | Options | Coding |
* Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;//

422

II. -

using System.Drawing; //
// ( )
namespace app95_WindowsForm_Continue
{
class Program
{
class Form1 : Form
{ //
// 4- :
private MenuStrip mn = new MenuStrip();
private ToolStripMenuItem mnFile =
new ToolStripMenuItem();
private ToolStripMenuItem mnCopy =
new ToolStripMenuItem();
private ToolStripMenuItem mnPaste =
new ToolStripMenuItem();
private ToolStripMenuItem mnDelete =
new ToolStripMenuItem();
private ToolStripMenuItem mnRename =
new ToolStripMenuItem();
private void BuildMenuSystem()
{
//
mnFile.Text = "File";
mn.Items.Add(mnFile);
// :
mnCopy.Text = "Copy";
mnFile.DropDown.Items.Add(mnCopy);
mnCopy.Click += (o, s) => Application.Exit();
mnPaste.Text = "Paste";
mnFile.DropDown.Items.Add(mnPaste);
mnPaste.Click += (o, s) => Application.Exit();
mnDelete.Text = "Delete";
mnFile.DropDown.Items.Add(mnDelete);
mnDelete.Click += (o, s) => Application.Exit();

18. Windows Forms


mnRename.Text = "Rename";
mnFile.DropDown.Items.Add(mnRename);
mnRename.Click += (o, s) => Application.Exit();
//
Controls.Add(this.mn);
// MainMenuStrip-.
// .
// (- ),
// . .
//
MainMenuStrip = this.mn;
}
//
public Label lb=new Label(); //
//
public void AddLabel_1()
{
lb.Visible=true;
lb.Text="_1";
lb.Location = new Point(160, 45); //
//
Controls.Add(this.lb);
}
//
public Button bt=new Button();
public void AddButton_1()
{
bt.Location=new Point(160,70);
bt.Text=" 1";
bt.Visible=true;
Controls.Add(this.bt);
}
//
public Form1(string title, int height, int width)
{
//
Text = title;

423

424

II. -
Width = width;
Height = height;
//
// :
CenterToScreen ();
// :
BuildMenuSystem();
AddLabel_1();
AddButton_1();
}

}
static void Main()
{ // Windows Forms.
// Windows Forms
//
Application.Run(new Form1("MyForm", 200, 300));
Console.Read();
}
}
}

. 18.2.

MenuStrip ,
ToolStripMenuItem ,
.
ToolStripMenuItem Text,

18. Windows Forms

425

.
(& ).
, <Alt> , , . ,

, , <Alt>,
. : . ,
&File, <Alt>+<F>,
, File: , . ,
ToolStripMenuItem ( mnFile)
DropDown.Items (
" "). (MenuStrip)
( )
Items (. mn.Items.Ass(mnFile);). ( ), ,
Project:
private ToolStripMenuItem mnProject= new ToolStripMenuItem();

BiuldMenuSystem() :
mn.Project.Text = "Project";
mn.Items.Add(mn.Project);

. .
Click .
? ,
,
. .
,
, ,
- . - .
Click ( ). ,
: , -.
, Object, EventArgs. (. 18.3), . . Object EventArgs.

426

II. -

. 18.3. - - Click

System.EventArgs
System.EventHandler
System.EventHandler , Windows Forms . , -, ,
System.Object.
, () ,
System.EventArgs, .
mnRename.Click += (a, b) => Application.Exit();


mnRename.Click += (a, b) =>
{
MessageBox.Show(string.Format ("{0} " +
" ", a.ToString()));
Application.Exit ();
};

.
. 18.4.
File ,
.

18. Windows Forms

427

Rename, .
, ,
( ) Rename
: .

. 18.4. , Click

EventArgs .
:
public class EventArgs
{
public static readonly EventArgs Empty;
static EventArgs ();
public EventArgs ();
}

, , , , : MouseEventArgs, ;
KeyEventArgs, ;
PaintEventArgs, EventArgs
. Window
Forms , . . ,
Visual C# 2010 .
, , .

428

II. -

88

115
- 349
116
122
52

293

312

107
150
203
254

35
182
172
175
163
183
149

static 147
this 146

82, 84
84
54
223
34
73
140
149
61

55
- 306

430

40
107
108
109
113
108
107
108
94
140
302
179
146
179
328

167


105
287
296

as 186
do while 53
finally 200
for 50
foreach 111
goto 94
if 93
is 186
new 122
return 86
switch 102
try...catch 196

79
79
80
75
82
79
45

87

88
85, 86
146
87
37
39
105
128
129
140
178
40
333
396

74

75
74

184
184
Windows Forms 417


65
35, 214
327
391
391

29

212, 328
155
160
87
191


- 121
41
40

431

55
61
391

51

418
35, 85

94

97
106

Вам также может понравиться