796
о о о. ш о ID Эндрю Троелсен и платформа философия .NET основы языка С# интерфейсы и коллекции элементы управления ввод, вывод и сериализация объектов взаимодействие с унаследованным программным кодом web-службы

Andrew Troelsen - CSharp and .NET FrameWork (Rus)

  • Upload
    cam029

  • View
    897

  • Download
    28

Embed Size (px)

Citation preview

. ID

.NET #

, web-

- --

2004

Andrew Troelsen

32.973-018 681.3.06

T70

70

. . # .NET. . .: , 2004. 796 .: .ISBN 5-318-00750-3 #, .NET. , #. , . - .NET, , (C++, Visual Basic, Java - ).

32.973-018 681.3.06

, , , . , , ,

AndrewTroelsen, 2001ISBN 1-893115-59-3 (.) ISBN 5-318-00750-3

, 2002 , , 2004

. 1. .NET 2. # , 22 28 29 .....75 139 197 225 261 315 343 409 471 519

3. # - 4, 5. # 6. , 7.' 8. : Windows.Forms 9. (GDI+) 10. 11. ,

12. ...563 13. ADO.NET 14. web- ASP.NET 15. Web- 629 691 749 782

1. .NET , , Win32/C , C++/MFC , Visual Basic , Java - , Windows DNA .NET '. .NET (CI_R, CTS CLS) .NET # .NET .NET () , Microsoft Intermediate Language IL IL - .NET .NET Common Language Runtime .NET CTS CTS CTS

22 28 ...2929 30 30 30 31 31 32 33 33 34 35 36 36 37 38 40 40 41 41 42 42 43 43 45

,

CTS CTS CTS CTS :. CTS CLS .NET ILDasm.exe IL Web- Class Viewer \VinCV # # Visual Studio.NET Visual Studio.NET Solution Explorer Properties Visual Studio.NET Server Explorer XML UML Object Browser 4

7 45 46 46 4() 46 47 49 50 51 52 53 53 5.5 5,") 55 56 58 5S 60 61 62 63 63 65 66 67 68 68 70 70 70 70 70 74

2. # # Main() : ? # Console ,

7575 7(i 77 78 80 81 82 82

8

# : : System.Object System.Object System.Object # : # for foreach/m while do/while # # : Environment System.Array System.Text.StringBuilder # System.Enum # 83 85 87 89 92 95 95 98 99 100 102 103 103 104 104 105 108 109 109 112 112 114 115 119 120 122 124 125 126 128 129 131 133 134 ;.... 136 137 137 138

3. # -

139139 141 143 143

# : ....

- : * : !1] # ; # , : , # : protected : , sealed - # : # '. , , finally IDisposable

9 145 145 146 147 149 151 151 153 154 156 157 158 159 161 161 162 163 167 168 171 171 174 176 177 177 178 180 181 183 184 184 185 187 188 189 190 191 191 193 195

4.

197197 199 200

10

-. 202 203 206 208 ( lEnumerable {Enumerator) 209 ( ICloneable) 212 ( IComparable) 214 (IComparer) 216 ,... 218 System. Collections , 219 System.Colle^tions.Specialized 220 ArrayList 221 223

5. # System. MulticastDelegate CarDelegate '. , XML XML HTML

225225 228 231 233 234 235 236 237 238 239 241 242 243 245 246 248 251 252 255 258 259 259

'.

6. , : : .NET

261262 262 263 264 265 265

# Visual Basic.NET CarUbrary IL CarLibrary GAC? () (GAC) .NET SharedAssembly SharedAssembly 2.0 .NET Win32 '. System.Threading Thread lock System.Threading. Monitor System.Threading. Inter locked

11 267 268 268 269 269 270 273 274 276 277 280 282 283 284 284 286 287 28 288 29 291 2!J'2 293 294 295 296 297 297 2539 299 300 3d 1 302 303 3D4 3(15 306 3(17 308 309 312 313 313 3:14

12

7. : System.Reflection System.Activator System. Reflection. Emit Assembly Info.cs

315315 316 316 317 320 321 322 323 324 325 325 327 328 328 332 334 335 336 338 339 340 341 342

8. : Windows.Forms Windows. Forms Windows. Forms () Windows Forms System.Windows.Forms.Application Application ApplicationExit Application System.Object MarshalByRefObject Component Control Control Control : :

343343 344 344 346 346 348 352 354 355 356 357 357 358 359 360 362 362 364 366

Control Painting Basics ScrollableControl ContainerControl Form Form MenuSMenuItemCollection IDE Visual Sudio.NET Timer Visual Studio IDE ( ImageList) Visual Studio Windows Forms Windows 2000 Windows 2000

13 367 368 371 371 372 373 374 375 376 377 379 380 382 385 387 388 389 391 392 396 3!)7 399 401 403 406 408 (

9. (GDI+) GDI+ System.Drawing System.Drawing THnPoint(F) Rectangle(F) TnnSize(F) Region Paint Graphics GDI+

409409 410 412 412 414 415 415 416 417 418 419 4!>1 4!22 423

14

424 ColorDialog 425 427 428 429 430 (System.Drawing.Text) 432 FontDialog 434 System.Drawing.Drawing2D 436 437 438 442 443 445 447 448 450 , , , PictureBox 452 455 458 .NET 460 System.Resources 462 *.resx 462 *.resx 464 ".resources 464 ResourceWriter 465 ResourceManager .., 466 IDE Visual Studio.NET 468 470

10. Controls ControlCollection Visual Studio TextBox TextBox ( ButtonBase) Checked List Box

471471 472 473 475 476 478 480 481 481 483 484 486 488 490

Tab Tab Order Wizard TrackBar MonthCalendar DateTime UpDown Panel (ToolTips) Visual Studio ErrorProvider .'.

15

492 492 494 496 499 .....500 502 503 505 505 507 508 510 511 5:14 516 517

11. , System.IO Directory (Info) File(Info) FileSystemlnfo Directorylnfo FileAttributes Directorylnfo Directorylnfo Directory Filelnfo FileInfo.Open() FileInfo.OpenRead() FiieInfo.OpenWrite() FileInfo.OpenText(), FileInfo.CreateText() Filelnfo.AppendText() Stream FileStream MemoryStream BufferedStream StreamWriter StreamReader StringWriter StringReader ( Binary Reader BinaryWriter) ...

519519 521 521 522 523 524 525 526 528 529 531 531 531 533 534 535 535 536 537 539 541 541 544

:.

16

.NET Formatter System.Runtime,Serialization SOAP ISerializable 545 545 546 549 549 550 552 553 554 556 559 560 562

,

12. ... 563 System.Runtime.InteropServices DLL, ExactSpelUng CharSet : CallingConvention EntryPoint .NET .NET - Visual Basic 6.0 IDL - Visual Basic 6.0 - CoCalc CoCalc - ATL SAFEARRAY : IDL - Visual Basic 6.0 IDL 563 564 565 567 567 568 569 570 570 571 572 574 575 576 576 578 579 581 583 584 585 587 588 590 591 592 592 593 594 595

COM SAFEARRAY # .NET PoCCW .NET .NET ^Object .NET OLE/COM Object Viewer Visual Basic 6.0 .NET , , IDL ( , tlbexp.exe) CCW + System.EnterpriseServices .NET + # + + + Component Services Explorer '. ,

17 596 598 598 6(10 6(13 603 605 605 606 607 607 608 609 610 610 611 611 613 615 616 616 617 619 619 620 622 623 623 625 625 626 627

13. ADO.NET ADO.NET ADO.NET: ADO.NET System.Data DataColuran DataColumn DataColumn DataTable XML

629629 630 ./. 632 632 634 635 63 S 63S 637 S3I3

18

TmiDataRow DataRow.RowState ItemArray DataTable DataTable ; DataTable Data View DataSet DataSet DataSet DataRelation , DataSet XML ADO.NET OLE DB .' OleDbConnection SQL OlcDbDataReader Access OleDbDataAdapter DataSet OleDbDataAdapter SQL System. Data. SqlTypes SqlDataAdapter SqlDataAdapter SQL DataSet " DataRelations ; 639 640 642 643 643 646 648 650 651 654 656 657 660 661 664 665 667 668 669 670 671 673 673 676 677 679 680 681 683 685 687 690

14. web- ASP.NETWeb- web- HTML HTML HTML HTML- Visual Studio.NET HTML

691691 692 694 695 697 698 699 701 ....703

( GET POST) HTTP ASP , POST ASP.NET ASP ASP.NET ASP.NET '. System.Web web- # *.aspx web.config Global.asax ASP.NET # web- ASP.NET System.Web.UI.Page *.aspx/Codebehind Page.Request Page.Respon.se Page.Application ASP.NET WebForm WebForm ,. WebForm WebForm WebForm WebForm ,

19 703 705 706 708 709 709 712 713 714 714 7 L5 71.6 71.6 71.7

...720 720 721 721 722 723 724 725 727 728 729 71:11 732 734 735 735 737 741 7-14 747 747

15. Web- web- web- web- System.Web.Services

..749749 750 751 751 751 751 752

20

web- # web- (".asmx.cs) web- web- Web Method Attribute System.Web. Services.WebService Web Service Description Language (WSDL) web- HTTP-GET HTTP-POST SOAP - web- : ; - wsdl.exe - - - Visual Studio.NET web- ( ) web- ( ) web- web- '. 752 754 755 756 757 760 761 763 764 766 767 768 770 770 771 773 774 776 777 778 779 780

782

, . , , , .

.NET # . , , .NET Windows ( , , Windows). .NET , . , .NET ( ). .NET , lUnknown, . . Microsoft #. , Java, C++ ( ). # Visual Basic 6.0. , # , , C++, Java Visual Basic, # . , .NET . .NET- ( , ) . , # . , .NET. ( , , , #) .NET- . , , #, .NET. ( ) , #. .

23

1. .NET , , .NET. , .NET : Common Language Runtime (CLR) .NET, Common Type System (CTS) Common Language Specification (CLS) .NET- . # (csc.exe). , # Visual Studio.NE . .

2. # #. # . , , #, , , , # , , System. Object. , , #.:

3. # - # - , - : , ( Is- has-) ( , ad hoc). , # . , , readonly . : (Structured Exception Handling, SEH). .NET, ' , System. GC.

4. - Java, , # ( ). , , #. , , , .

24

.NET , , . , , foreach.

5. # , # , . , , .NET, . .NET XML . .

6. , #. , : , , , .NET , . . (Global Assembly Cache, GAC), .NET, XML CLR, .

7. . .NET System.Reflection. , , System. Ref I ect 1 on. Emi t. , # , . , ( ) . i

8. : Windows.Forms , .NET . , -

25

() System. Windows. Forms. , , . , Windows 2000.

9. (GDI+) , , . , , ( ) Windows. , . .NET, XML.

10. , Windows Forms. , Windows . ( TextBox, Button, ListBox . .) , Calendar DataGrid. , .

11. , .NET, , , , -. ( ) , , . . 1 .NET. , (). .NET , : XML. .

12. , .NET , Component Object Model (COM) . , .NET .

26

.NET : .NET - ( - RCW) .NET, - ( CCW). , .NET Win32 API DLL, , .NET, +.

13. ADO.NETADO.NET ADO. ADO.NET . Recordset ADO.NET DataSet, ( DataTables) . DataSet , SQL Server Access. , , -, .

14. web- ASP.NET , web-: web- HTML, , web- ASP. ASP.NET. ASP.NET web-, Web Controls, , Page ( Request Response).

15. Web- web- ASP.NET. Web- .NET, - HTTP. .NET (WSDL, SOAP, ), web- . .NET , web-

27

( ASP), . web- XM.L (, web- ) -, .

-, Visual Studio.NET. Visual Studio.NET Beta 2, .NET. , # (csc.exe) Notepad, . -, , (www.piter.com). . -, . - # .NET, , (C++, Visual Basic, Java - ). , , # .NET . . #, Visual Studio .NET SDK , , . ! , .NET. (Andrew Troelsen), , .

, , [email protected] ( , ). ! -. web- http://www.piter.com.

, Apress. , (Gary Cornell) . (Grace Wong), . (Stephanie Rodriguez), , . , , - . , (Nancy Guenther), , . , : (Doris Wong), (Anne Friedman), (Nancy Rapoport) - (Beverly McGuire). , , . (Eric Gunnerson) ( Microsoft #), , . Microsoft (Joe Nalewabau), (Nick Hodapp) (Dennis Angeline), . - : ( ), Intertech, Inc: (Steve Close), - (Gina McGhee), * (Andrew Gunner Sondgeroth) (Tom Barnaby), , , - . ( Salonek) , .

.NET

, , . (C++, Visual Basic, Java), (MFC, ATL, STL), (COM, CORBA), , . , , . .NET Microsoft , . .NET, . , .NET (assemblies), (intermediate language, IL) (just in time compilation, JIT). .NET Common Language Runtime (CLR), Common Type System (CTS) Common Language Specification (CLS). , .NET ( ILDasm.exe), . # (csc.exe) (Integrated Development Environment, IDE) Visual Studio.NET.

.NET, , , ? , , , , # .NET .

30

1 .NET

, Win32/C Windows Windows Application Programming Interface ( Windows, 32- Windows Win32 API). , - , Windows API . , . , , , . , , , - . Win32 API , , .

, C++/MFCC++ . C++ - . * - , . , C++, ( ). C++, Windows, . MFC (Microsoft Foundation Classes). MFC Win32 API, , . MFC . MFC , .

, Visual Basic . C++ , Visual Basic (VB). Visual Basic , (, -) . Visual Basic , MFC, Win32 API .

31

Visual Basic . , , C++ ( , , , VB.NET). Visual Basic , - . Visual Basic , , .

, Java Java - , C++. , Java . Java , C++. Java (), . Java , , , web-, , , . Java . . , Java . Java ( Java ). , Java. . Java . Java , 3D, , , . , , 3D , (, C++). Java . API , , Java , Java .

- , Java-, , Microsoft Component Object Model (COM). - : , . - , . , , C++, -

32

1 .NET

, VBasic. , Delphi, , . . . , ( ). , . , . , Application Identifiers (AppIDs, ), (stubs), , , , RPC . Visual Basic 6.0 :' VB 6.0 . ' . ' . Dim as New MyCOMClass ' ' AppID c.DoSomeWork

. . , . - , , Active Template Library (ATL) , . (, Visual Basic) . . , COM Visual Basic, , .

, Windows DNA , , . Microsoft , , -. web- Windows DNA (Distributed iNternet Architecture ) . , Windows DNA (ASP, HTML, XML, JavaScript, VBScript, COM(+), ADO . .). , . , JavaScript, , VBScript Visual Basic. -, +, , ASP-, . -

.NET (CLR, CTS CLS)

33

. , , Windows DN , , . , 1 nt JavaScript , 1 nt , , , i nteger Visual Basic.

.NET . , - , : Windows-. , .NET, . .NET ; , , . .NET Windows ( , , ). .NET: . , . 12, .NET. . , .NET , . .NET, , . , . , , API, , .NET. ! IClassFactory, ITJnknown, . IDL VARIANT- (BSTR, SAFEARRAY ) .NET. . .NET . , .NET DLL ! .

.NET (CLR, CTS CLS) CLR, CTS CLS .NET. .NET . .NET Common Language Runtime (CLR

34

1 .NET

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

.NET CLR CTS/CLS .NET , .NET. , -, , , . , XML, , Web (, ). .NET , . 1.1.The Base Class Library

GUI -

1

XML/SOAP

The Common Language Runtime Common Type System Common Language Specification

. 1.1. .NET

#

35

# .NET Microsoft #. # , Java ( ). , # ( Java) (*.cs), C++, (*.h) (*.). # Java . #, Java C++. Java C++, # Java. # C++, Visual Basic. , #, Visual Basic, . C++', # (Java , ). # . # ( ) , Java, , Visual Basic, , C++. , #. ! #, , ( , , ). . # , . # , C++. . . , . .NET ( ) . - ( ). ( COM IDL) . , , #, , , .NET. , # -. Microsoft , .NET, (managed code). , , (assembly). .

36

1 * .NET

.NET .NET 2000 Professional Developers Conference (PDC) , .NET . .NET- 30 . , Visual StucUo.NET (#, Visual Basic.NET, Managed C++ JScript.NET), .NET- Smalltalk, COBOL, Pascal, Python, Perl . . 1.2.

(

#

#

Perl

COBOL

MSIL (DLL }

C++

C++

. 1.2. , .NET, IL-

, .NET, DLL , . , DLL . .NET IDL . , , , .NET . .NET - , Microsoft Intermediate Language (MSIL, Microsoft), IL.

.NET () .NET DLL , (assembly) IL. 6. , .NET, .

.NET ()

37

, I.L IL - Java - , . , I.L (, ) .NET. IL, .NET , , . , Foo, Foo, Fc ( ), , . .NET . ( IDL). , , . IDL , . .NET, , , , .NET. , , . (manifest). , , (, . .), , . , IL , .

.NET -- .NET DLL, . ( 6) . , . (single file assembly) , , IL. (multifile assembly) (module). ( , IL). IL. ? .

38

1 .NET

, , , , . .

Microsoft Intermediate Language, .NET, Microsoft Intermediate Language (IL) Microsoft, . IL , . .NET IL , (#, Visual Basic.NET, Eiffel . .) . , . . , 10 84. #. , , Add .// namespace Calculator { using System; // Calculator AddO. // - MainO public class Calc {

// public Calc(>{}

public int Addtint x. int y) { return x + y: public static int Main(string[] args) { // Calc Calc = new CalcO: int ans = c.AddUO, 84): Console.WriteLineC'lQ + 84 is {0}.". ans): return 0: }}

# (csc.exe), # . , IL , Calc. ( ), IL, AddC):

Microsoft Intermediate Language 39.method public hidebysig instance int32 Add(int32 x, int32 y) il managed { // 8 (0x8) .maxstack 2 .locals ([0] int32 V_0) ILJJOOO: ldarg.1 IL_0001: ldarg.2 ILJ002: add ILJ003: stloc.O ILJ004: br.s ILJ006 IL_QOQ6: ldloc.0 ILJ007: ret } // IL Calc:AddO

IL , . IL 7. , # - , IL. .NET. Visual Basic.NET:' VB.NET Module Modulel ' -, Calc Add 1 Class Calc Public Function AddCByVal x As Integer, ByVal As Integer) As Integer ' ! Visual Basic 'return' Return x + End function End Class Sub MainO Dim ans As Integer Dim As New CalcO ans = c.AdddO, 84) Console.WriteLineC'10 + 84 is { 0 } . " . ans) End Sub End Module

, A d d C ) , :.method public instance int32 Add(int32 x, int32 y) il managed {

// 11 (Oxb) .maxstack 2

.locals init ([0] int32 Add) ILJOOO: IL_0001: ldarg.1 ILJJ002: ldarg.2 IL_0003: add.ovf IL_OOQ4: stloc.O ILJ005: ILJ006: br.s IL_OQ08 ILJ008: ILJJ009: ldloc.0 ILJOOa: ret 1 // ModulelSCalc::Add

40

1 * .NET

, IL . # Visual Basic.NET. CSharpCalculator VBCalculator Chapter 1. "

IL

, , , IL - ? , , . .NET IL, IL . , , . . , .NET ( Windows). .NET Java .NET , ( Java !) , .NET , . . Microsoft .NET . , .NET Windows.

, , Interface Definition Language (IDL, ). IDL , , , , COM. IDL ( ) midl.exe. , . IDL , , . ( , 1.0,2.0 2.4) (, English, German, Russian). , ( ) , . .NET IDL. .

IL -

41

.NET , . IDL, .NET , (, , ), , . .NET IDL , .NET . , .NET. .NET . , , .NET ( )

A d d ( ) CSharpCalculator ( VBCalculator ):Method #2

MethodName RagsRVA CalcCnvntn

: Add (06000002) : [Public] [HldeBySig] [ReuseSlot] (00000086) : [IL] [Managed] (00000000): [DEFAULT]: 14

ImplFlags

: 0x00002058

hasThis

2 Arguments Argument #1: 14 Argument #2: 14 2 Parameters

ReturnType

(1) ParamToken : (08000001) Name : x flags: [none] .(00000000) default: (2) ParamToken : (08000002) Name : flags: [none] (00000000) default:

, . , : #. ? .NET (: ), . , Intel HSense Visual Studio.Net ( ) . , , , #. '

IL - , , - IL, - , - IL . - "just-in-time compiler" (JIT) . JIT "jitter" (, ). JIT

42

1 .NET

IL - .NET. IL, CPU JIT. IL - JIT -, . , () Foo. JIT IL - . JIT , .

.NET .NET ( , ) . .NET , , , , . .NET (, #) . , ; . . , .NET. . : Windows Forms, . GoCart, . , . : , CustomVehical s .GoCart SlowVehl cal s .GoCart. .

Common Language Runtime - - .NETX

, , IL, .NET CLR . (runtime) , . . , MFC, Microsoft Foundation Classes mfc42.dll Visual Basic , msvbvm60.dU, Java , Java.

CTS 43

.NET. , , , .NET , .NET. , .NET Common Language Runtime (CLR). CLR . , mscoree.dLL .NET mscoree.dU , , , . . , (, , . .) , IL - , , , . CLR . , mscorlib .dll . .NET mscorlib.dll ( , ). . 1.3 , , - .

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

CTS - . .NET. (class) , , . , , , CTS , . CTS . . 1.1.

44

1 .NET .NET

.NET

.

DLL (IL )

(mscoree.dll)

(mscorlib.dll )

. 1.3, .NET

1.1. CTS ? - ? ? ? , . CTS . . (visibility). , , ,

CTS

45

CTS CTS (structures). ; , , , .NET (, , ). , ( 2). CTS ( ). . : // # struct Baby {/ / : public string name; // ( ): public Baby (string name)

{this.name = name: }

// : public void CryO { Console.WriteLine ( " W a a a a a a a a a a a h ! ! ! " ) ; } public bool IsSpleepingC) { return false; } public bool IsChangedO { return false; }

} :// !Baby barnaBaby = new Baby ("Max"); Console.UriteLine ("Changed?: {0}", barnaBaby.IsChangedO.ToStringO); Console.WriteLine ("Sleeping?: {0}", barnaBaby.IsSleepingO.ToStringO); // : for{int i=0: i Open . mscorLib.dLl (. 1.5). ILDasm. , . , , , , ( , ). ILDasm . 1.4.

54

1 .NET/^O:\WINNT\MicrQsoft.NET\Framewofk\vl,0.2204\ms Eiie View tielp- DAWWNT\Mic[OioflNETVFramewoikW1.0.22D4Smscorlib.dy

4;> 9- 9

> MANIFEST

Miciosofl. Win32 System ffi 9 System.Colleclions ft- -9 System.ComponenlModel E I -9 System ConligurationAssernblies n 9 System. Diagnostics FI--9 Syslem.Globafoalion i= 9 System 10 if 9 System. lO.lsolatedStot age ffi JP ConsoteStream u'C Error * f _HResutls ^

.assembly mscorlib as "mscorlib" {

iL.

: - ^ .class public auto ansi ; ^ extends System.Object -^ ManCha/BytesSize : private static literal int32 = inl 32(0x0 DODO : v m_bulfer : private unsigned int9[] : v rn_charBulter : private wchar[] |~ v m_chaiBytes ; piivate unsigned int8[] ;-- v rn decoder: private dassSystem.Texl.Decoder i

t

^

,.

UJ. 1.5. ILDasm.exe .NET 1.4. ILDasm 3 ILDasm (.dot)

^ ^

, . . $< juiaco ( ), ( , )

[NSP]

[OS][VCL] [INT]

[FLD][STF] [MET]

[STM] [PTY]

55

, ILDasm IL, . System. ID.BinaryWriter. , . 1.6.* Binary Writer::. et : voidf) ^ ^ ^^----.

.method private hidebysig specialnanie rtspecialnarne void . cctor() ell managed

// Code size 11 (Oxb) .max?tack 8 IL_0000: newobj instance void System. 10.BinaryVJcit IL_0005: stsfld class System.lO.BinaryWriter Syate IL_DOOa: ret } // end of method BinaryWriter::.cctor

. 1.6. IL ILDasm

ILDasm . , , ( ). , , File Dump TreeView . , , . 1.4. . 1.7.

IL , IL. ILDasm : FiLe > Dump. IL *.iL. . 1.8 IL, GetType( ) mscorLib.dU ( 7).

ILDasm , . ILDasm , .NET- .NET. ILDasm Ctrl+M. TestApp.exe ( ) . 1.9.

56

1 .NETffi core, tut - Notepad

File Edit Fsjrrat [MOD] D:\WINNT\ComPlus\v200Q.l4.l8l2\mscorl1b.dll M A N I F E S T'NSPJ

[CLS] QAVariantLib .class auto ansi sealed extends System.object STF] AlphaBool public static literal 1nt32 - int private static literal int32 - in5TF] CV_OB3ECT _[STF] calendar-Hi r1 : public static literal 1nt32 static assembly initonly class s" classTypes Local Bool public static literal int32 = int STF] Noliseroverride : public static literal int32 NoValuePro public static literal 1nt32 - 1 VARCMP_EQ private static literal 1nt32 - In VARCMP_GT private static literal int32 - in STF] VARCMP_LT private static literal int32 = in

Microsoft.Win32

,, 1.7. , ILDasm lest.il-Notepad

File Edit Format .method /"060QQ002V public hidebysig instance class system./" 020000CF V 11 managed // SIG: 20 00 12 83 3C // Method begins at RVA Ox20d4 // code size 19 (0*13) .maxstack 1 .locals (class system.Type/*1 020000CF */ v_0) IL_0000: /* 02 ! V ldarg.0 IL_0001; 28 | (06)000004 */ call IL_0006: OA V stloc.O IL_0007: /* V Idloc.o IL_0008: 2D | 07 V brtrue.5 lL_OOOa: lL_OOOb: IL_0010: IL_0011: IL_0012: } // end of 02 (06)000003 28 /* OA 06 2 method object::GetType

V V V V V

ldarg.0 call stloc.O Idloc.o ret

ceInstallerDialQQ.MairLMethod Programming wjth C* Visual Studio Walkthroughs

'properties DynamicHelp . 1.33. Dynamic Help

, Dynamic Help (. 1.34).

GO * Programmer's Referertce

MainThe Ham method is the entry point of your program, where the program control starts and ends. It is declared inside a class or struct. It must be static. It can either be void or return an int. The Kain method is where you create objects and invoke other methods. The Ham method can be written without parameters or with parameters. The latter form allows your program to read command-line arguments. See the following topics for more information and examples on using the method: Return Values * Command-line Arguments See Also . LaTiuuaQe_Eeatures

Send feedback.to Visual Studio . 1.34. Visual Studio.NET

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

74

1 .NET

, , . , , , .NET. .NET .NET (Common Language Runtime, CLR), mscoree.dll, (scorlib.dll ). .NET, (assemblies), .NET CLR. (Intermediate Language, IL) () . - . JIT(just-in-time compiler), . Visual Studio.NET . CTS (Common Type System) CLS (Common Language Specification). , .NET SDK, # csc.exe Visual Studio.NET.

#

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

## Java , , (, , , ). ( C++) # . # :// # *.cs using System: class HelloClass { // , MalnO private, // , , ... public static int Main Cstring[] args) ( Console.WriteLine ("Hello. World");

76 2 #return 0;

1

}

"! 1 oCl ass, Mai (). # M a i n ( ) . . , Mai (), , . , . , Mai () . . 1() public static. . , publ 1 , , statl , , , . , 1() , (string[] args). , . HelloClass Mai n(). Console, System. Console WriteLineO, ; // Console.WriteLine"Hel1. World"); M a i n C ) int, ( 0 ), , , , # C++.:

MainQ MainO (Int) . Ma I n ( ) -. 1() (, ):// , - public static void Main (string[] args) ;

.

// //

II ,

# public static void MalnO { // // , public static 1nt MalnO I

77

// } MainC ) ? . : - ? , Mai . : ( MainC))? , M a i n C ) int.

//

, ! loClass , , . H e l l o C l a s s ( {0} ):using System; class HelloClass { public static int Main (string[] args) { // ! fordnt x=0: x < args. Length; x++ { Console. WnteLineC'Arg: {0}", args[x]): } Console. WriteLinef "Hello. World!"): return 0;

, . Length System. Array ( , # System. Array, ). ( ), , . , . 2.1.

78

2 #Command Prompt D j : N T e n p > } i e l l o t h e i - e - e x e -foo -bar -18B0 -godnode ftl'g: --fuurtrg: ftrg:

fli-g: -godnodeH e l l o Borldt D:slemp>

-1000

. 2.1.

, foreach ( ):public static int Main (string[] args)

{

foreach (string s 1n args) Console.Wr1teL1ne("Arg; {0}". s);

I

, , .

: - . (user-defined type, UDT). , . , . # new. , , :// HelloClass MainO Using System; class HelloClass { public static int Main(string[] args) {

// HelloClass cl - new HelloClassO;II... : HelloClass c2; 2 - new HelloClassO; return 0:

}

new , . -

#

79

, .NET (managed heap ). cl 2, Hel loClass. # , . cl 2 , (, ). 3. . # . , , . C++, , . # C++ . C++ ( ). # ( ), , (, -) 0. , , # . . , . Hel I oCl ass. -, , , .// HelloClass using System; class HelloClass {

// no - public HelloClassO { Console.WriteLineC'Default ctor called!"): } // - public HelloClassdnt x, int ) { Console.WriteLinet"Custom ctor called!"); intX = x; intY - y; } // - public int intX, intY; // public static int Main(string[] args)

80

2 # // HelloClass cl - new HelloClassO; Console.WriteLine("cl.intX = {0)\ncl.1ntY - {l}\n", cl.lntX, cl.intY); // HelloClass 2 - new HelloClassdOO. 200); Console.WnteL1neC"c2.intX = {0}\nc2.intY - {l}\n", c2.1ntX. c2.intY): return 0;

I , , - (), - , (. 2.2).F1 D:\CSharpBoak\Labs\Chapter 2\11 conn and line f*is . . . Default ctoi- called* ct.intX = cl.intY = Custom tor called? - i n t X = 1 c 2 . i n t Y = 200 Pi-i-us any l

. 2.12.

# , . . DataTypes Chapter 2.

, .NET . , - . :// # - // , class DefValGbject public public public public public public public public public public public public sbyte byte shortushort int uint long ulong char float double bool theSignedByte: theByte: theShort: theUShort; thelnt: theUInt; theLong; theULong; theChar: theFloat; theOouble; theBool;

public decimal public string public object theDecimal; theStr; thedbj;

101

public static int Main(string[] args) {

DefValObject v - new DefValObjectO; return 0; // // Autos

:> , , DefValObject - (. 2.13).

Names.; v

1 Value -

iv^m r1L.lf;,;L

-{DefaultVahDeFaultValues.VdlObjec I'Default 1

: Type1'"sbyte byte ] short 1 ushort jht jdnt

J

theSignedByte theBybs I E theShort to theUShort

their*theUInt

i i!

j

~To~~ ~theChar theFloat theDoubb theBool theDecimal theStr E theOb] :JO"

_1!_ 'char ; float.double . Jbqqj System.Decimal string System. Object

40,0

ujjgfnul

i Falsenun

]nu(

Autos | d Locals ' This |

. 2.13. .NET

, , . . :// ! localInt public static void MainC) { int 1ocalint;

Console. WriteLinedocal Int. ToStringO);

:// , public static void MainC) Console.WriteLi neC1 oca!Int.ToStri ngC));

int locallnt = 0;

102

2 #

, , , . , . , , , . DefaultValues Chapter 2.

. , C++, # const. , . :using System; class MyConstants { // public const int mylntConst = 5; public const string myStringConst = " I ' m a const": public static void MainO

{

// const string localConst = "I am a rock. I am an island"; // ( // , . Console.UriteLineC'mylntConst - {0}\nmyStringConst - {!}". MyConstants.mylntConst. MyConstants.myStringConst); Console.WriteLineC'Local constant: {0}". localConst):

} , . , :// , private. class MyConstants { // public const int mylntConst = 5; public const string myStringConst = "I'm a const"; // . // - private MyConstants(){}

#

103

: ( abstract). , : // , . abstract class MyConstants // public const int mylntConst = 5; public const string myStringConst = " I ' m a const";

MyConstants . , # . , : # ( C++) const . Constants Chapter 2.

# , , . , #, . # ] :

for; foreach/in; while; do/while., , C++ Java, , for, whil e do/whi I e, foreach. , Visual Basic, . # .

for , , for . , . :public static int Main(string[] args) {fortint i - 0: 1 < 10: 1++)

// ! "1" "for"

104

2 #

{

Console. WriteLineC'Number is: {0}". 1);

// "i" . return 0; , C++ Java #. , goto, continue break.

foreach/in, Visual Basic, For Each. # . , foreach .NET.// , "foreach" public static int MainCstringQ args) ! string[] arrBookTitles = new String[] {"Complex Algorithms", "COM for the Fearful Programmer", "Do you Remember Classic COM?", "C# and the .NET platform", "COM for the Angry Engineer"}: int COM - 0. NET - 0; // , COM . ( ) foreach (string s in arrBookTitles) { if (-1 != s.IndexOfC'COM")) COM++: else lf(-l !- s.IndexOfC'.NET")) NET++; }

Console. WriteLineC'Found {0} COM references and {1} .NET references.". COM, NET); return 0:

} , foreach . 4 , Enumerator lEnumerable.

while do/while for , , . , , whi 1 do/whi I e.

# 105 , # ( 11). # StreamReader, System. 10. , StreamReader , File.QpenTextO. config.win ( ) StreamReader.ReadLine(}:try { // , config.win

// config.winStrearnReader strReader = File.OpenText("C:\conf1g.win"); // string strilne;

whileCnull != (strLine = strReader.ReadLineO)); Console.WriteLlne(strLine);//

I

strReader.CloseC);

catchCFileNotFoundException e) // 3 {Console.WriteLineCe.Message);

1

}

do/whi 1 e whl 1 . , doVwhi 1 , : ( whl I e , , ). , do/while, .string ans; do { Console.WriteLineC'Are you done? [yes] [no] : "); ans = Console.ReadLineO; Jwhile (ans !="yes");

, , . 2.14. Iterations Chapter 2.

# . # If/else switch,

106

2 #- D:\ CSharpBook \Labs\thapter 2\tterations\bin\ Found 3 COM r e f e r e n c e s and 1 .NliT re Here iu tlie c o n t e n t s c o n f i g . u i n DEU I CE=C: \UINDOUS\HIMEn.SVS I)EU I CE =C : 4U 1 NDOUS Sl:MH386 . EX E HIsM To nrtfce A DOS Boot D i s k e t t e ; See the F i l e C:\Bf

; SBPGI mod: d e u i c e = c :4uindoiE\liinen.sys / t e s t mem: ren T l i e b e l o w DOS CD ROM d r i v e r is not r e q u i r e d to DEU l C E = c : \cdi-on\OahCdRon.SVS /D= I DECD000 fire you done? ft i-e you done? ftre you done? re you one rti-e you d o n e ? ou d o n e ? Pi-ass a n y k u y 2000) if (bonus = 2000)

< >=

, C++, ; , 0 true if /else #. , #: // , Length int. // boolstring thoughtOHheDay = "You CAN teach an old dog new tricks": if (thoughtOfTheOay. Length) // !

//

# 107 , # , t h o u g h t O f T h e D a y n e , , :// if (0 != thoughtOfTheOay. Length) // "true" "false" {' //

!

1 f . , . 2.6. 2.6. # # && || ! if ((age = = 30) && (name = = "Fred")) if ((age = = 30) || (name = = "Fred")) if (ImyBool) (AND) (OR) (NOT)

, # e l s e , , , i f . i f / 1 s e # C++ Java , Visual Basic. # s w i t c h . , . , : // "switch" class Selections (

public static int Main(string[] args) { Console. Wr i tell ne(" We! come to the world of .NET"): Console. wnteLlnefl - C#\n2 - Managed C++ (MC++)\n3 = VB.NETNn 1 1 ): Console. WriteC'Please select your Implementation language:"); string s = Console. ReadLineO; // ParseO int n = int.Parse(s):

switch(n)

// C# , ( "default" // ), , // "break" "goto" case 1:Console, WritelineC'Good choice! C# Is all about managed code.") ; break: case 2: Console, WriteLineC'Let rne guess, maintaining a legacy system?");

108 2 #break; case 3: Console.WriteLineC'VB.NET: It is not just for kids anymore..."); break; default: Console.WnteLlneC'Well. ..good luck with that!"); break; return 0:

}

. 2.15.P.? : D:\DoeumenU afwlSettmosVatri Sfelcome to the world of -Nil 1 = CB 2 = Hflfiaged * CMC*+>3 = UB. HO

Please select ytiur inplewentation 1: US.HO: It Is not for j w s t bids anymtiva. .. Press any key to continue

. 2.15. switch

s w i t c h # , ( ). n u l l . Selections Chapter 2,

# , , # . , # , C++ Java. # ( ) . 2.7. 2.7. # (AND) + ! */% + < > < = > = jg as = = != .&

(XOR) (OR) (AND) (OR) | && ||

109

?: = *= /= %=+=-= = = &^ = | -

, , is as. Is . 4, , . as ( 4). , , , # Language Reference.

, , . # . , ( ) .

# , , . . . 2.8. 2.8. # public private , . , private protected , , . internal , . - protected internal protected internal

110

2 #

protected Internal . : // ! class SomeClass (// public void MethodA(){};

// SomeClass private void MethodB(){}; // SomeClass , SomeClass // ) protected void MethodC(){}: // internal void MethodD(){}: // protected internal protected internal void MethodE(){}; // protected - void MethodO {}:}

, pub! 1, , . , private, . , - ( ). , , Teenager publ 1 Compl ai n( ) BeAgreeabl ) , . ( private) GetRandoinNumberO, - System . Random, : // , public, using System; class Teenager {// System. Random private Random = new RandomO; public string ComplainO; string messages = new string[5] {"Do I have to?", "He started it!". "I'm too tired. "1 hate school !". "You are sooo wrong."}; return messages[GetRandomNurnber(5)]:

public string BeAgreeableO { stnng[] messages * new str1ng[3] {"Sure! No problem!". "Uh uh.", "I guess so."}; return messages[GetRandomNuETiber(3)]; // private int GetRandomNurnberfsnort uppertiroit) { // Random. Next () / / 0 upper-Limit return . NexU upper-Limit); public static void Main(string[] args) { // , Teenager mike = new TeenagerO: for (int 1 = 0; i < 10: i++) { Consol e . Wri teLi ne( "mi ke .Compl ai n( ) } ;

111

. 2.16.- D:\CSharpBook\Lebf\Chept I * n too tired..I hate school! He started it! V o n are sooo urong. I hate s c h o o l ! Do I have to? You are sooo wrong. You are sooo wrong. He star-ted it* I ' m too tired... Press any key to continue

. 2.16. ( )

GetRandomNumberO , Teenager. . , , GetRandornNumber . System.Random. , . Random. Next 0 . , Random

112

2 #

, , #.

, static. ? (static method) , . Ma i n() static , . , , Compl ai n() : // , // // - public static string ComplainO

;

string[] messages = new string[5] {"Do I have to?", "He started It!". "I'm too tired. "I hate school!", "You are sooo wrong."}; return messegesCGetRandomNumberCS)]:

} .

: , :// Complaint) Teenager public static void Main(string[] args) I

for int 1=0; 1 < 40; 1++)

Console.Wri teLinedeenager. ComplainO);

}

(instance methods), , . stati , . , . :// ComplainO Teenager Teenager joe = new TeenagerO; joe.ComplainO ;

Teenager Chapter 2.

# , , . , . -

113

. , :class Foo1

public int IntFoo;

}

Foo IntFoo :// Foo - IntFoo Foo fl = new Foo : fl. IntFoo = 100; Foo f2 = new FooC): f2.intFoo = 993;

Foo f3 - new Foo( ) : fS.intFoo = 6;

, . , . , A i r p l a n e NumberlnTheAir 1 . , :// "static" class Airplane ( // // Airplane private static int NumberlnTheAir = 0; public AirplaneO {

NumberInTheAir++;

// NumberlnTheAir // Airplane public int GetNumberFromObjectO {return NumberlnTheAir;} // - NumberlnTheAir // Airplane public static int GetNumberO {return NumberlnTheAir;}

}

1 rpl . 1 rpl ane, . , GetNumberFromObjectO, Ai rpl ane, . GetNumber ( ) , , . , :

114

2 * #

// class StaticApp { public static int Main(string[] args) { / / Airplane al = new AirplaneO; Airplane a2 = new AirplaneO; 1 H ? Console.WriteLinet"Number of planes: {0}", al.GetNumberFromObjectO) Console.WriteLineC'Number of planes: {0}", Airplane.GetNumberO): // Airplane = new AirplaneO: Airplane a4 = new AirplaneO:

// ?Console.WriteLineC'Number of planes: {0}", aS.GetNumberFromObjectO) Console.WriteLineC'Number of planes: {0}". Airplane.GetNumberO): return 0;

}

. 2.17. D:\CShamBook\Labs\Chapter 2\... [ Nunbei1- of Miiiihi-r of Munbei- of Nunbei* of Press any planes - 2 planes: 2 planes: 4 planer: 4 key to cont inue

. 2.17.

, , . . , , . StaticTypes Chapter 2.

: EnvironmentEnvironment , System. , , , .NET. :

// ) Environment using System; class Environment; { public static int Main(string[] args) { // ? Console. WriteLi net "Current OS: {0}". Environment. OSVersion);

115

// ?Console. WriteLineC'Current Directory: {0}". Environment. CurrentDi rectory) // : string[] drives = Environment. GetLogicalDrivesO: for tint 1 - 0; i < drives. Length; 1++) Console. WriteLine( B Drive {0} : {!}", 1. drives[i]);

// .NET ?Console. WriteLineC'CurrentVeersion of .NET: {0}". Environment. Version);

return 0;

, . 2. 18.: > D:\CSnarpBook\Labs\Chapter 2\PlatformSpy\bin\Debiig^ Current 0!> : Microsoft U inHows NT 5..2195- Current D i r e c t o r y : D:\CSliarpltooJ4\Labs\Cbapter 2 \ P l a t f o r m S p y S b i n \ D c h u g Drive 0 Drive 1 Drive 2 Drive 3 Current : C:\ : D:\ : E:\ : F:\ version of

.: 1.0.2615.1

Press any k e y to c o n t i n u e

. 2.18. # PlatformSpy Chapter 2.

. , , , [in], [out] [in, out] IDL. , ( ) , . # IDL , ( ) . . 2.9.

116

2 #

2.9. # () , , ( ), . in [out] IDL: , [in, out] IDL: , . . params, . , SAFEARRAY

out ref

params

i n , out . Add , #, out: // - out - public void Addtint x. int , out int ans) { ans = x + : } out. : // , AddC) Methods public static void MainO {Methods rn = new MethodsO; int ans; // - // // out // m.AddOO. 90, out ans); Console.WriteLine("90 + 90 = {0}", ans};

}

, Add , : public int Add (int x. int y) I return x + y; , ( ref), , . . -

117

(out) , (ref): . .

, , . : . , , ! ref :// , public void Upper-CaseThisStringCref string s) ,

// , s = s.ToUpperO;

)// MalnC) public static void MainO { // ref string s = "Can you really have sonic hearing for $19.00?": Console.WriteLineC'Before: {0}". s); m.UpperCaseThisStringCref s) Console.Wr1teL1ne("After: {0}", s);

}

, , param:;. ( ) . , , . , vi :// public void DisplayArrayOfInts(string rnsg. params int[] list) Console.WriteLine(msg);

for (int i=0; i < list.Length; i++) Console.WriteLineC1i st[i]);

1

, : string, int. , : . :// , params 1nt[] IntArray = new int[3] {10.11.12}: m.DisplayArrayOflnts ("Here is an array of ints". IntArray): m.DisplayArrayQflnts ("Enjoy these 3 ints". 1, 2, 3): m.DisplayArrayOflnts ("Take some more!", 55. 4, 983. 10432, 98, 33):

118

2 #

, , D1 spl a y A r rayOf I nts. , pa r a m s . , Per s on :

// Person class Person {private string fullName: private byte age;{ }

public Pf?rson(string n. byte a)age = a:

full Name = n;

public void Print InfoO{

Console.WriteLine("{0} Is {1} years old". fullName. age);

, M e t h o d s , p a r a ms. , , . , P e r s o n . : , , s , P r i n t l n f o O . . // ? public void DisplayArrayOfObjectsfparams object[] list){

for (int i=0; i < list.Length; 1++){

if(11st[i] is Person)

// // Person?

{else} }

C(Person)list[i]).PrintlnfoO: // , Console.Wri teLi neC1i st[1]);

Console. WriteLineO:}

: // Person Person p = new PersonC'Fred". 93); m.D1splayArrrayOfObjects(777 T p. "I really am an instance of System.String")-. . 2.19.

119

77?

Frttd

! really iFistatsce of System.String

is

V3

yefti-s

old

. 2.19. params

, # . C++: # , , ( r e f ) ; * &. Methods And Params Chapter 2.

# , C++ Java. , * , Sy s t err. Array. # . : ;, . #, , . # . :'! ([ ]) , :// 10 (0, 1 str!ng[] booksQnCOM; boofcsOnCOM - new stringUQ]: // 2 {0. 1} string[] booksQnPLl = new string[2]: // 100 {, 1 str1ng[] booksQnOotNet = new string[100]; 99} 9}

, . ( #). n e w . :// // new lnt[4] ages - {30. 54. 4, 10): , // !

, , . , new. , new:

120

2 #

// 4 . "new" // 1nt[] ages - {20. 22. 23. 0}; , # , , . :// : stringC] firstNames - new string[5] {"Steve". "Glna". "Swallow". "Baldy", "Gunner"}; // : str1ng[] flrstNames = new str1ng[5]: f1rstNames[0] - "Steve"; firstNames[l] - "Glna": firstNames[2] = "Swallow": firstNames[3] - "Baldy"; firstN3mes[4] - "Gunner";

C++ #, , , # . , 0, NULL . .

# . . . . :// int[J myMatrix: inyMatrix = new int[6. 6]; // : for (int I = 0; i < 6; i++) for (Int j = 0; j < 6; J-H-) myMatrix[i. j] = i*j; // for (int 1 = 0 ; i < ; i++) I for (Int j = 0; j < 6; j++) { Console.Write(myMatr1x[i. j] -* "\t"); } Console. WriteLineO: }

. 2.20. .

- ^D:\0ocuments and Setting s\ air els fl rectangular MD array:

1 1 2

Press any key to c o n t i n u e

. 2.20.

(jagged). TaKoii , . : // "" ( ). - // int[][] myJagArray = new int[5][]: // "" for (int 1 = 0; 1 < inyJagArray. Length; 1++) {HiyJagArrayCi] = new int[i + 7];

// ( , // - 0) for (int i = 0: i < 5: i++)

:

Console.WriteC"Length of row {0} is {l}:\t". i. niyJagArrayCi],Length); for (int j = 0; j < myJagArray[i].Length: j++)

Console. WrlteLineO;

;

Console.Write(rnyJagArray[i][j] + " " ) ;

. 2.21 ( ).': D:\Documents andSethngs\atroeteen\D*:sktop\C5haipEQO, II JMJUCrt Ml) -1-: Lci.ytb of Length of Length o f Leriylh of Length of Pi-ess row rii-.i rou roil rou is V: 1 i :; 8 : ( 4 0 0 0 0 2 is 9: 0 3 h; 1: 4 is 11: 0 0 0 0 0 0 0 0 to continue

LSI

. 2.21.

122 2 #

, #, , # System. Array.

System.Array C++ # , # System. Array. # , . (, , ) . 2.10. 2.10. System.Array BinarySearchQ

, IComparer ( 4). , BinarySearch() ( 0, null) lEnumerator . 06 4, ,

Clear()

CopyTof) GetEnumeratorQ

foreachGetLengthQ Length

GetLength() . Length , . , . IComparer, (- 4)

GetLowerBound() GetUpperBoundQ GetValueQ SetValueQ

ReverseQ SortQ

System.Array . ReverseO ClearO, Length f i rstName:// // System.Array

class Arrays

123

{

public static int Main{string[] args)

{

// string[] firstNames - new string[5] {"Steve", "Gina", "Swallow", "Baldy". "Gunner"} // Console. WriteLineC'Here is the array:"): for (int i - 0: 1 < firstNames. Length; i++) Console. Write(firstNames[i] + "\t"); // // ReverseO Array . Reverse(f i rstNames ) : // ... Console. WriteLineC'Here is the array once reversed:"); for (int i = 0; i < firstNames. Length; i++) Console. Write(firstNames[i] + " \ t " } ; // , Console. WriteLineC1 Cleared out all but one..."); Array. Clear(firstNames. 1, 4); for (int i = 0; 1 < firstNames. Length: i--) { Console. Write(firstNames[i] + " \ t \ n " ) ; } return 0:

. 2.22.U:\CSharpBook\Labs\Ehauter2\Arrayrwi Created array of s t r i n g s . H e re is t he array: Steue Gina Sualluvj Baldy ( Here is the array once reuersed: G u n n e r Baldy Suallciu Gina Steue Cleared out all hut one. . . Gunner

. 2.22. System.Array

, Java. # .NET Windows-.

124 2 # : COM SAFEARRAY ( , 12). Arrays Chapter 2.

, s t r i ng ( Unicode) #. , # .NET Sy s t em . S t i -rig. , : , , . . , , S y s t e m . S t r i ng . 2.11. 2.11. System.String Length ConcatQ CompareToQ () Format()

String , ( , ) {0}, () ( )

InsertQ PadLeft() PadRightQ Remove() ReplaceQ

ToUpper() ToLower() ,

, -, , s t r i n g , (= = ! =) , . -, (+) # , nc a t (}:// = = !- . // + , public static int Main(string[] args) \ System.String strObj = "This is a TEST": string s = "This is another TEST"; //

if(s = = strQbj) Console.Wr1teL1ne("Same info..."); else Console.WriteLineC'Not the same info..."): // - string newString = s + strObj; Console.WriteLineC's + strObj - {0}", newString}: // System.String // for tint k = 0; k < s.Length: k++) Console.WDteLineC'Char (0} is {!}". k. s[k]); return 0;

125

}

. , , , . newString : This Is another TESTThis is a TEST. ([]).

#, , C++, Java (escape characters):// - U, \\, \ string anotherString; anotherString = "Every programming book need V'Hello WorldV": Console.WriteLine("\t" + anotherString): anotherString = "c:\\CSharpProjects\\Strings\\string.cs": Console. WriteLineC'U" + anotherString}:

, , . 2.12. 2.12, V \" \\ \ \ \f \ \ . (Alert) (Backspace) (Form feed) (New line) (carnage Return) &

126

2 #

2.12 (} ,\V

(horizontal Tab) Unicode (Vertical tab) (NULL)

, # @ . (verbatim strings). :// @ string finalString - @"\n\tString file: 'C:\CSnarpProjects\Strings\string.cs'"; Console.WriteLine(fi nalString);

, , . 2.23. : , @ .'' 0:\CSharpBook\l.atis\ChapteF2\Strings\bm\Debuo'vStrina*,e)-- . --. Met the a n t e , . . , * sti-Obj = Ibis is nothef T E S T T h i s is a TEST Ewei'*f programming booh *-*-*** Marget is a s t a t i c method C l e a n i n g a car D o n ' t need to be r o t a t e d . . . Ihis car is already clean... Don't need to be rotated... This car is already clean... Tires have been rotated Cleaning a car Tires haue been rotated This car is already clean... Tires haue been rotated Press any key to continue

. 5.6.

, , , . , , . ,

244 5 # W a s h C a r ( ) RotateTI res() ServlceDept ( ); // // public class ServiceDept {// ! public void WashCar(Car ) { if(c.Dirty) Console.WriteLineC'Cleaning a car"); else Console.WnteLineC'This car is already c l e a n . . . " } ; / / T o public void RotateTiresCCar c) { IfCc.Rotate) Console.WriteLineC'Tlres have been rotated"); else Console.WriteLineC'Don't need to be rotated...");

i c > D:\C5harpBook\Labs\Chapter 5\CarDelegate\bin\Debug\CarDelegate.eHe WWHW* C a l l i n g : Uoid HashCar < C a r D e l e g a t e f l p p . C a r > ***** *** Calling: U o i d R o t a t e T i r e s CCai-Delegateflpp.CdiO *** > T e r y e t : CarDelegateflpp.SerwiceDept Cleaning a car D o n ' t n e e d to lie rotated.. . This car is a l r e a d y c l e a n . . , D o n ' t need to be rotated... T h i s car IE a l r e a d y c l e a n . . . Tires have been r o t a t e d Cleaning a car T ires have bee n r o t a t e d This cai- is dlreftdy c l e a n . . . T i r e s ha.ue been rotated Press any key to c o n t i n u e

. 5.7.

:// ServiceDept public static int Main(string[] args) I // Garage g = new Garage; II ServlceDept sd = new ServiceDeptO: // Car.CarDelegate wash = new Car.CarDelegate(sd.WashCar); Car.Car-Delegate rotate - new Car.CarDelegate(sd.RotateTires); MulticastDelegate d = wash + rotate; //

245g.ProcessCarsC(Car.Caruelegate)d);

return 0;}

To, , . 5.7 . CarDelegate Chapter 5.

, , #, , . , #. (events) Windows , , Button () Calendar (), , , . , , . , . , ( , .SpeedUpO) . ( , ), , i> . , . , . (AboutToBlow) , 10 . (Exploded) , , . # . , , event. : //

public class Car{

. // private boo! dead:// . , //

public delegate void EngineHand1er(string msg):

246

5 # // public static event EngineHandler Exploded;

public static event EngineHandler AboutToBlow;

( , ) , . , SpeedUpO, , :// public void SpeedUp(int delta) {

// , Exploded if (dead){

if (Exploded != null) ExplodedC1 Sorry, this car is dead..."):

else{

currSpeed += delta;

// ? AboutToBlow if(10 = - maxSpeed - currSpeed) if (AboutToBlow !- null) AboutToBlow( "Careful, approaching terminal speed!"); // ! ifCcrrSpeed >= maxSpeed) dead = true; else Console. WriteLineC'UCurrSpeed = {0]". currSpeed);

Car , . , .

, pub! i . add_, remove_. , Exploded : // * // add_Exploded() // remove_Exploded()//public static event EngineHandler Exploded:

add_XXXX() remove_XXXXC), , private.

247

. . (event sinks) - . , , . 5.8,F D:\CSharpBaDk\Labs\Chapter 5\CarEvents\bil

[>,

[I

HelpV

DACSharpBackALabsChapterSyCarEvents'ibirCiebuglCarEventsH MANIFEST V CarEvents ^ .class public auto ansi beforefieldinil E EngineHandler AboufToBlow: private static class CarEvents.Car/Engir Exploded : private static class CarEvents. CatfEngineHf currSpeed : private int32 dead : private bool maxSpeed : private 132 petName : private string theMusicBox: private class CarEvents.CarfRadio .ctor:voldO .ctor:vold(string,lnt32,lnt32) CrankTunes; vold(bool) SpeedUp : void(int32) add_AboutToBlow : void(class CarEvents. Car/EnglneH add_Exploded : void(class CarEvents. CariEngineHand remove_AboutToBlow:voicf(class CarEvents. a r/Engii

U remove_Exploded :void(class CarEvents.CarfEngineHAboutToBlow: CarEvents.CatfEnglneHandler Exploded : CarEvents.CarfEngineHandler .assembly CarEvents ,

. 5.8. # ,

, ( Expl oded About ToBlow) : , pri vate; add_XXXX{);

remove_XXXX(). , add_AboutToBlow, ( Del egate.Combi net)):.method public hidebysig specialname static void add AboutToBlow(class CarEvents.Car/EngineHandler ' v a l u e ' ) ell managed synchronized

248

5 * #

// Code size 22 (0x16) .maxstack 8 IL_0000: Tdsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow ILJJ005: ldarg.0 IL_0006: call class [mscorlib]System.Delegate [mscorlib]System.Delegate:iCombineCclass [mscorlibJSystem.Delegate, class [mscorli b]System.Delegate) IL_OOOb: castclass CarEvents.Car/EngineHandler IL 0010: stsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow ILJ015: ret } // Car::add_AboutToBlow

, , , renrave_AboutToB"low Del egate. RemoveO:.method public hidebysig specialname static void renrave_AboutToBlow(class CarEvents.Car/ EngineHandler 'value') cil managed synchronized!

// 22 (0x16) .maxstack 8 IL 0000: Idsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow IL~0005: Idarg.D IL_0006: call class [mscorlibJSystem.Delegate [mscorlibJSystem.Delegate::Remove(class [mscorlib]System.Delegate, class [mscorlIblSystem.Delegate) IL_OOOb: castclass CarEvents.Car/EngineHandler IL_0010: stsfld class CarEvents.Car/EngineHandler CarEvents.Car::AboutToBlow IL_0015: ret ) // Car::remove_AboutToBlow

IL [. addon] [, moveon] add_XXXX() removeJ(XXX

EngineHandler:i

.event CarEvents.Car/EngineHandler AboutToBlow .addon void CarEvents.Car::add_AboutToBlow(class CarEvents.Car/EngineHandler) .removeon void CarEvents.Car::remove_AboutToBlow(class CarEvents.Car/ EngineHandler) } // Car::AboutTo81ow

, , , , .

, , . , , , , . add_XXXX ( ) , , . # a d d _ X X X X ( ) remove_XXXX()

249

+= -=. :// // QbjectVariable.EventName += new ObjectVanable.DelegateName(functionToCall); // .Exploded +- new Car.EngineHandlerCOnBlowUp};

, , , -:// : // ObjectVariable.EventName -- new QbjectVariable.DelegateName(functionToCall); // Car.Exploede -- new Car.EngineHandler(OnBlowUp):

:// , public class CarApp { public static int Main(string[] args) ( Car cl - new CarC'SlugBug". 100, 10):

// Car.Exploded +- new Car.EngineHandler(QnBlowUp); Car.AboutToBlow +- new Car.EngineHandler(OnAboutToBlow): // ( ) fordnt 1 - 0: 1 < 10: 1++) cl.SpeedUp(20):

// .Exploded -= new Car.EngineHandler(OnBlowUp); Car.AboutToBlow -- new Car.EngineHandler(OnADoutToBlow);

// ! fordnt i = 0; i < 10: 1++) cl.Speedup(20); return 0:// OnBlowUp public static void OnBlowUpCstring s) { Console. WriteLineC'Message from car: {0}". s): // OnAboutToBlow public static void OnAboutToBlow (string s)

{

Console. WriteLineC'Message from car: {0}". s ) :

. 5.9. , - , :

250

5 #' -,D:\CSharpBook\LabsiChapter 5\CarEvents\bin\ > CurrSpeed = > CurrSpeed = 50 --> Curl-Speed = V0 Message frun car: Careful, approaching terminal speed? > CurrSpeed = 90 Mescaye from car: Sorry, this cai* s dead... Message from car: Sorry, this car s dead... Message frun car: Sorry, this car s dead-.. Message frori car: Sorry, this car s dead. . Message fron car: Sorry, this car s dead... Hress any hey Co continue

. 5.9. // public class CarApp public static int Main(string[] args} { II 1 = new CarC'SlugBug". 100, 10): // : .Exploded ** new Car.EngineHancjler(OnBlowUp); .Exploded -= new Car.EngineHandler(OnfllowUp2); Car.AboutToBlow +* new Car.EnglneHandler(OnAboutToBlow); // ( ) for(int i = 0: i < 10: i++) cl.SpeedUp(20); // Car.Exploded -= new Car.EngineHandler(OnBlowUp): Car.Exploded -- new Car.EngineHandler(OnBlowUp2); . Car.AboutToBlow -= new Car,EngineHandler(anAboutToBlow);

// Exploded public static void OnBlowUp(string s)

Console.Wr1teL1ne("Message from car: {0}", s):// Exploded public static void OnBlowUp2(string s) I Console.WriteLine("-> AGAIN I say: {0}". s): / / AboutToBlow public static void OnAboutToBlow(string s) Console.WriteLineC"Message from car: {0}", s):

!D:\C5harpBook\Labs\Chapter 5\CarE vents \\ > Curi-Speert = ~> CurrSpeed = 50 > CurrSpeed - 70 lessage f car: C CurrSpeed = 90 tiesiiaye f ron Crtr: K o r r y , tliii; car is dead. . . > f t G R I H I s a y : Sorry, this car is dead... Message f r o m c a r : Sorry, t h i s car is dead > f t G f l l H I s a y : Sorry, this car is d e a d . . . M e s s a g e f r o m c a r : Sorry, t h i s car is dead > H t ; n i N I s a y : Sorry, this car is dead M e s s a g e f r o m c a r : Sorry, this car is dead... > f t G f i l N I s a y : Sorry, this car iu d e a d . . . Mssage f r o p t c a r : Sorry, t l i i c car is dead. , . > A C h l N I s a y : Sorry, this car is d e a d . . . Ppe^r. any key to tint inue

. 5.10.

Exploded OnBlowUpO, OnBlowUpO. , . 5.10.

, , , , , . , - . : :// public class CarEventStik // OnBlowUp Exploded public void OnB1ovAJp(string s) { Console. WriteLinef "Message from car: {0}", s); // OnBlowUp2 public void GnBlowUp2(string s) { Console. WriteLine(""->AGAIN I say: {0}". s); // OnAboutloBlow AboutToBlow public void OrAboutToBlowCstring s ) 1 { Console.WriteLineC'Message from car: {0}". s)

!

, - , . CarEventSi nk:

252

5 #

II / CarEventSink public class CarApp {public static int Main(string[] args) ( Car cl - new CarC'SlugBug", 100. 10);

// CarEventSink sink = new CarEventSinkO; // Car.Exploded +- new Car.EngineHandler(sink.OnBlowllp); Car.Exploded +- new Car.EngineHand1er(sink.OnBlowUp2): Car.AboutToBlow +- new Car.EngineHandler(slnk.QnAboiJtToBlow); fordnt 1 - 0; 1 < 10; i++) cl.SpeedUp(20); / / Car.Exploded -- new Car.EngineHandler(sink.OnBlowUp): Car.Exploded -= new Car.EngineHandler(sink.QnBlowUp2); Car.AboutToBlow -- new Car.EngineHandler(sink.QnAboutToBlow); return 0;

, . 5.10. CarEvents Chapter 5.

(callback interfaces). . , , . # ( .NET). , . . - : - ( 10 ) . , . :// public interface IEng1neEvents { void AboutToBlowCstring msg);

void ExplodedCstring msg);

253

}

, , . , ( ) . , lEngineEvents, :// - public class CarEventSink : lEngineEvents public void AboutToBlowfstring msg) { Console.WriteLine(msg): } public void Exploded(string msg} { Console.WriteLine(msg); }

, , , ( ) . . , . , , , . - Advi seC). , . - UnadviseO. , , , , , . ArrayList , . :// #. // public class Car

{

// ArrayList itfConnections - new ArrayList:// public void AdviseCIEnglneEvents itfClientlmpl) { itfConnections.Add(itfClientImp!}; } public void UnadvisedEngineEvents itfClientlmpl)

.

254 5 #{

itf Connections. Remove t itf Client Imp!):

I

Car.SpeedUpO, Itf Connections: // , :class Car public void SpeedUptint delta)

i

// , Exploded // if(dead) {foreachUEngineEvents e in itfConnections) e.ExplodedC "Sorry, this car is dead..."):

} else

1

currSpeed += delta: // , // If * = maxSpeed - currSpeed} ( foreachCIEngineEvents e in itfConnections) e.AboutToBlowC1 Careful buddy! Gonna blow!"); / / A y iftcurrSpeed >= maxSpeed) dead = true: else Console. Writeline("\tCurrSpeed = { 0 } " . currSpeed);

, , :// public class CarApp { public static int Main(string[] args) { Car cl - new carC'SlugBug". 100, 10); // - CarEventSink sink = new CarEventSinkO; // Car -

XML 255cl.Advise(sink): // , forCint i-0: i < 10: cl.SpeedUp(20);

// cl.Unadvise(sink); return 0; (. 5.11) .!: 4D;\CShafpBook\Labs\Cnapter 5 \Event Interface1! ->Cur r Sliced =- 30 ->Curi>Speed Cun-Spted = 7 First s i n k -epoi'ting: C a r e f u l buddy? Other sink -sporting: Careful buddy! ?Curi-Speed = 9 First sinli 'epoi-t ing: Sorry, this car Other :;ink spurting: Sorry, t h i s car h'irst sink *e port Ing: Sorry, this car Other s i n k *(! p o r t i n g : Sorry, t h i s c.irI

bloirf Gonna blouT is dead... is dead... is dead. . , if: d e a d . . .

. 5.11. Eventlnterface Chapter 5.

XML XML #. Java, , , javadoc, Java HTML. , #, -: -, XML ( HTML), -, XML #, . : XML, HTML? XML . XML ( , HTML) , , XML . XML . , XML # . XML (///), C++ (//) (//... ). XML, , . 5.3.

256

5 #

5.3. XML XML, _

, ,

, XML - , . (see also)

__

_

XML . : /// /// - , /// XML /// public class SimpleCar { /// /// ? /// private bool hasSunroof - false: / / / / / / , /// / / / / / / public S1mpleCar(bool hasSunroof) (

this. hasSunroof - hasSunroof;

/ / / / / / /// / / / / / / public void OpenSunroofCbool state)

XMLiftstate = = true &S hasSunroof = = true) ' Console. WriteLineC'Put sunscreen on that bald head!"):

257

elseConsole.WriteLineC'Sorry,..you don't have a sunroof."):

:/// III /// public static void MainO SimpleCar = new SimpleCar(true); c.OpenSunroof(true);

.

, XML. #, XML /doc:. :esc /doc:s1mplecar.xm1 simplecar.cs

, XML Visual Studio.NET. Properties () Solution Explorer (. 5.12). Project Properties ( ). Configuration Properties ( ), Build ( ) XML XML Documentation File, XML.Solution f.'.iim. r - XmlDocCar

ocCar' (1 project)

] Assembly Info, cs ?) SimpleCar.es

. 5.12. Project Properties ( )

258

5 #

XML simplecar.xml Visual Studio.NET, , . 5.13.< Simple tar. ml Data Table;; Data: -IPJX.I

0XML

. 5.13. XML Visual Studio.NETT

XML, XML. , F, , . , XML, . 5.4. 5.4. , XML N

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

IF

1

XML HTML ( XSL) .NET. XML , - , HTML. , , .

259

HTML HTML . , , XML ( ). , Tools () Build Comment Web Pages ( web- ). , (. 5.14).Quild Comment Web Pages Build for entire Solution Build for selected Erojeets: XmlDocCaf

Save Web Pages in: D:\C5harpBook\Labs\Chapter5\XmlDDc

QK

Cancel

Help

. 5.14. HTML

HTML, . HTML . 5.15. XmlDocCar Chapter 5.

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

260

5 #

XmlDocCar.SimpleCar ClassThis is a simple Car which illustrates working with XML style documentation. Access: Public Base Classes: Object

hasSunroof

Do you have a sunroof? The ctor lets you set the sunroofedness. This method allows you to open your sunroof, Entry point to application.

QpenSunroof

Main

. 5.15. XmlDocCar

; , . #. , # Visual Studio.NET .

,

-, , : , . , , . # .NET . , , . , .NET , . .NET , . , .NET ( VI sual Basi . NET, #). , , .NET. , (private) , (shared), , .NET Global Assembly Cache (GAC, ). XML, .NET (, , ). , System. Th readi ng. Win32, , .NET .

262

6 ,

. -. - , , , , . , - (IDL, . .) , , , : * ? * ? , .NET . , .NET , (assembly). , , .

: (coclasses) ( ), ( [Unknown). DLL . . , , - , , , . , , , . . , , 10 MyCOMServer.dll 1.4. , /. 2.0. , . , . , DLL , DLL (DLL Hell). -, DLL, . , .NET DLL . .NET

263

, . , .NET . , .NET ( !) . , MyDotNETServer.dll 1.4, MyDotNETServer.dLl 2.0, . .

: . , CoIm'tializeO . COM (CoCreatelnstanceO, CoGetClassObjectO ) . , . -, , . - . : , , , - (Dl I Regi sterServer(} DLL W i n M a i n O EXE). - : COM (CLSID), (), (LIBID), (AppID) . , , -, - . : - , . , - , . , - 100 , - , 101 . , . .NET , .NET () . , . . .NET ( ). , HKEY_CLASSES_ROOTl

264 6 * ,

.NET, , , .NET. .NET . (DLL ), , ( ), (, , . .) (, ). , , .NET Win32. , (DllCanUnloadNowC),DllGetClassObject{},DllReg1sterServer()HD11Unreg1sterServerO), . .NET DLL, , D I l M a l n C ) . - , W l n M a i n C ) . - , - , COM DLL. .NET -. Wi nMa I n () ( Ma I n ) ), . .NET Win32 , .NET - , Microsoft (Microsoft Intermediate Language, MSIL IL). , . IL - . , .NET , Windows, . IL, .NET . . , .NET- Joystick, , , , , . .NET ( ) , . , .NET . , , , , , , ( , ). , , .NET .

.NET

265

. .NET. , ( DLL), . * -- . , . 6.1.

()

. 6.1.

, , . , , . , , , .NET . , . , . , , . 6.2. , , . #. , /addmodule #.

.NET, , , . (), (. 6.3).

266 , Foo.dll ( ) Bar.dll

1 Qaaz.dll

CompanyLogo.bmp

. 6.2.

Foo.dll Resource files

Bar.dll

Manifest

. 6.3. :

, . , , ( , , , ). . 6.4. System.Drawing.dll .NET. dll, , ( ILDasm.exe . 6.5).

.NETLogical View of an Assembly

267

Classes

Enumerations

Delegates

Interfaces

Resources

Structures

.6 .4. ;

Help D:WflNNTWicroeaft.'NEHFrameworklvl.0.2615*Svs!em Drawmg.dll

> MANIFEST V System.Drawing 9 Bystem.Drawlng.Design $-9 System.Drawing.Drawing2D Syslem.Drawing.lmaging 9 System.Drawing.Internal V System.Drawing.Printing u-V System.Drawing.Text Bitmap * Brush 0 Brushes--" ; CharacterRange .assembly System.DrawInQ

. 6.5. System.Drawing.dll

, , .NET.

, . , , -NET, , . , , , , . .NET , ! (, ) (private) . . < .

268 ,

, .NET . .NET, , #, Visual Basic.NET, .NET- . , .NET (Common Language Specification, CLS), , .NET- , . , , .NET , . , , ( , ). .NET .

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

, , . , , MyComServer.dll 1.0 2.4 , , , 2.4, 1.0. , , , , . , , , . , , , ( IDL) , . - , (, ), - . .NET -, , , -, , .

.

269

(version identifier), . , .NET . : ( informational version) ( compatibility version). , Myln teresti ngStri ng. , . : 1.0.70.3. , . ? (major version), 1. (minor version), 0. (build number), 70. (revision number), 3. , .NET , ( ). , , , .NET , .

.NET . .NET . , , , , . , , . .NET , , .

, .NET , .NET . , , . . (, XML) , . .

270

6 ,

, , .NET, #. CarLibrary. , Visual Studio.NET Class Library ( ), . 6.6.New Project project Types: . ") Visual Basic Projects !-3 C* Projects : C3 : - -Visualc + +

Projects Visual FoxPro Projects Setup and Deployment Projects Other Projects Visual Studio Solutions

Windows Application

Console Application

Control Class Library |Create a C# DLL. : Location: / ) CarLibrary '] D:K5harpBook\Labs\Chapter 6

ASP+ Web Application

Web Service

Browse...

Project will be created at D:\CShafpBook\Labs\Chapter 6\CarLibrary.OK

Cancel

Help

. 6.6. Class Library ( )

, , , protected. . TurboBoost( ). , EngineState. :// - Carl_ibrary.dll namespace CarLibrary

using System; public enum EngineState IengineAlive. engineDead

//

public abstract class

// -

// protected string petNarre: protected short currSpeed;

271protected short maxSpeed: protected EngineState egnState; public CarO {egnState * EngineState.engineAlive:} public Car(string name, short max. short curr) egnState * EngineState.EngineAlive; petName = name; maxSpeed = max; currSpeed = curr: public string PetName get { return petName; } set { petName = value; } 'public short CurrSpeed get { return currSpeed; } set { currSpeed = value: } public short MaxSpeed { get (return maxSpeed; } } public EngineState EngineState { get { return egnState; } } public abstract void TurboBoostO;

, , : Mini Van SportsCar. TurboBoostO -:namespace CarLibrary t using System; using System.Windows.Forms: // MessageBox // SportsCar public class SportsCar : Car // public SportsCarOf} public SportsCarCstring name, short max. short curr) : base (name, max, curr) {] // TurboBoostO public override void TurboBoostO MessageBox,ShowC'Ramming speed!", "Faster is better...");

// HiniVan public class Minivan : Car //

272 6 , public MiniVan(){}public MiniVanCstring name, short max, short curr) : base (name, max, curr}{} // TurboBoostO

{

/ / - egnState - EngineState.englneDead: MessageBox. ShowC" Time to call AM". "Your car is dead"):

TurboBoost ( ) , MessageBox System. Windows. Forms.dll. System, Windows. Forms. dLl, CarLibrary . Add Reference ( ) Project () (. 6.7).ftdd Reference NET JCOM | Projects] ' I Version 1.0.2411.0 1.0.2411.0 1.0.2411.0 1,0.2411,0 1.0.2411.0 1.0.2411.0 1.0.2411.0 1,0,2615.0 1.0.2411,0 7.0,0,0 7,0,0.0

Component Name

PathD:\WINNTlMtrosoFt.NET\Fra D \\ WINNTlMicrosof t , NET\Fra D : \ WINWUMitrosoft . NET\Fra D ; \WINNT\MicrosoFt . NET\Fra D : 1 WINNT\Microsof t , NET\Fra D; ( WINNTlMicrosof t .NET\Fra D : (wiNNT\M:rosof t . HE T\Fra D;lWINNT\Microsoft,AFra 0 : \WINNT\Mk:rosof t . WE T\Fra D : \WINNT\Microsof t -T\Fra D:\WINNT\MJcrosoFt, NET\Fra r):lWINNT\Mirrn':rVh.NFTIFrfl

M

System. Security System. Ser vlceProce ss , dD System. Web, oil System . Web. RegularExpressi , . System . Web. Services .dl System. Windows . Forms . dl 5ystern.Xml.dll TlbExpCode TlblrnpCode VSLancjProj vsmac rohierar chyLib ujhnmclifirtf vl

,;

-

n.n.n.n

~

Selected Components:

. 6.7.

System. Windows. Forms 8. , , , Windows . , MessageBox . , , .

# 273

# Sport sCar, Mini Van public, . . #, , Visual Basic.NET. #, , # Console Application ( #). Add References ( ), . 6.7, CarLibrary.dU, Browse (), CarLibrary.dll, , Visual Studio.NET CarUbrary.dLl Debug (. 6.8). D:\CbharpBook\Ubs\thapter 6\CStiarpCai-Client \bin\pe gie Edit View Favorites lools C^FoIders (^History

^Back

.',

Search

Address C3 D:\CSharpBook\Labs\Chapter 6\CSharpCarClien^bin\Debug

Debug

*, .

CarLibrary.,.. C5harpCar.., CSharpCar,..

CarLibrary.dll Application Extension

-, 1 i'[ 1 My Computer

Type: Application Extension Size; 6.00 KB

. 6.8. , , Debug

, , , . CarLibrary.dLl . # ;// namespace CSharpCarCHent { using System: // CarLlbrary using CarLibrary; public class CarClient public static tnt Main(string[] args)

274

6 , // SportsCar viper = new SportsCar'C Viper", 240, 40) viper.TurboBoostO : // - MiniVan mv = new MiniVanO; mv.TurboBoostO: return 0;

, . , . , .

Visual Basic.NET Visual Studio.NET , IL ( managed code): C#, Visual Basic.NET, JScript.NET Managed C++ (MC++). Visual Studio.NET , . Visual Basic . Windows Application Visual Basic Applications VBCarClient (. 6.9).cw Project

Iff s| Visual Basic Projects ) 4-, C,f 0"j-i-* , , "^ SI- Q Visual C++ Projects Visual FoxPro Projects : - CJ Setup and Deployment Projects - Other Projects '-Pi Visual Studio Solutions Web Application A project for creating a Windows user Interface application. : .ocatlon: | VBCarClient Web Service Web Control '

1 Class Library

]Windows

_d

.. := .

--

| D:\CSharpBook\Labs\Chapter \

|

Bjwse...

Project will be created at D:\CSharpBook\Labs\Chapter 6\ VBCarClient. ^MofR | OK j Cancel |

, 6.9. VB.NET Windows Application

Visual Basic.NET

275

Visual Basic 6.0, . VB.NET VB 6.0 : VB.NET Form, Form VB 6.O. , CarLibrary.dll , # (. ). . , , , . # u s i n g , VB.NET imports. VB.NET : #, a VB.NET ' , Imports System Imports Systemn.Collections Imports CarLibrary1

, . Button (), . 6.10VB Car Client

}Play wilh Sports Car;

Play with MJiiVan

. 6.10. VB.NET

, ( 1 i ck). IDE . :Protected Sub btnCar_Click(ByVal sender As Object. ByVal e As System.EventArgs) Handles btnCar.Click Dim sc As New SportsCarO sc.TurboBoostQ End Sub

:Protected Sub btnMiniVan_Click(ByVal sender As Object. ByVal e As System.EventArgs} Handles btnMiniVan.Click Dim sc As New MlniVanO sc.TurboBoostO End Sub

He , Visual Basic. - . , New. VB . Visual Basic.NET -

276 6 ,

! , , , , . . , #, .

.NET . VB. NET, # CarLi brary .SportsCar. , : VB.NET, #! VB 6.0 , VB.NET . VB. NET PerformanceCar. Project () Add Class ( ). . VB.NET Inherits. PerformanceCar # TurboBoost ) . VB.NET Overrides., VB.NET ' - Imports CarLibrary Imports System.Windows.Forms ' VB # SportsCar Public Class PerformanceCar Inherits CarLlbrary.SportsCar ' Overrides Sub TurboBoostO MessageBox.ShowC'Blisterlng speed". "VB PerformanceCar says") End Sub End Class1

VB.NET, PerformanceCar, Cl i ck :Protected Sub btnPreCarj;iick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPerfCar.Click Dim pc As new PerformanceCarO pc.PetName = "Hank" ' ' ? MessageBox.Show(pc.GetTypeO.BaseType.ToStringC), "Base class of Perf car") ' TurboBoostO pc.TurboBoost

End Sub

btnPreCar , . 6.11. , .

CarLibraryBase class of Perf car . CarLibrar y.SportsCarCK

277

. 6.11.

, .NET , .NET- . .NET- , , , $> . CarLibrary, CSharpCarClient VBCarClient Chapter 6.

CarLibrary CarLibrary , , . , ( ) . , .NET, , , .NET- . ? : ; ; , (); , , , , . .; (strong name) , , ; () , ( .NET 10). .NET- . , , . CarLibrary.dU. , ILDasm.exe. (. 6.12).

278 , F D:\CSliarpBook\l-abs\Chapter 6\i!e

.JJ3I*

$ew 1

MANIFEST 9 CarLibrary tfr.p car . E EngineState*

. assembly CarLlbrary

. 6.12. CarLibrary ILDasm.exef MANIFEST

.assembly extern mscorlib { .publickeytoken = (B"7 5 56 19 34 EO 89 ). .ver 1:0:2411:0 .assembly extern System.Windows.Forms I .publickeytoken = (? ? 5 56 19 34 EO 89 ) .vet 1:0:2411:0> .assembly CarLibrary

.custom instance void [mscorlib]Systetti.Reflection.Assi .custom instance void [mscorlib]System.Reflection.Asst .custom instance void [mscorlibJSystem.Reflection.Asst .custom instance void [mscorlib]System.Reflection.Ass .custom instance void [mscorlibJSystem.Reflection.Assi .custom instance void [mscorlib]System.Reflection,Assi .custom instance void [mscorlibJSyatem.Reflection.Assc .custom instance void [rnscorliblSystem.Reflection.Ass< ..custom instance void [mscorlib]System.Reflection.Asai .custom instance void [mscorlib]System.Reflection.Assi // The following custom attribute is added automai // .custom instance void [mscorlib] System, Diagnostic;_ .hash algorithm 0x00008004 .ver 1:0:454:30104 .module CacLibrary.dll

\ File bdlt Favorites lods Hefp ^Folders Q IJJJ Ig X

J="6ack * -

Search

D;\CSharpBook\Labs\Chapter6lC3harpCarClient\bin\Del)ug

DebugNO MO NO csharpcarclient.eHe.co nfig CONFIGFile

foo

CarLibrary....

CSharpCar...

NO NO MOcsharpcaiden t.exe.confio

UJ

I

CSharpCar.., \ZZ2 bytes j(gj My Computer ,

'

. 6.20. *.config ,

286 ,

, . , . IL [.assembly extern]:// .assembly extern Car-Library I

, System. Reflecti on .Assembly. Load()'. Assembly 7, , , , , . , . , , :/ / Assembly asm = Asembly.LoadC'CarLibrary"):

, , (assembly reference, AsmRef). , AsmRef (assembly resolver), .NET. , (, C:\MyApp), . , (, C:\MyApp\Bin, C:\MyApp\TooLs . .). , , . , .NET AsmRef . , AsmRef ( ), : 1. . , ( ) . 2. , . , . 3. ( , ), TypeLoad Except I on. . 6.21.

(As