1. Trang chủ
  2. » Công Nghệ Thông Tin

C 5 0 programmers reference

962 141 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 962
Dung lượng 17,98 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

If you read a book like C# 5.0 All-in-One for Dummies Bill Sempf et al., 2013, For Dummies or my book Stephens’ C# Programming with Visual Studio 2010 24-Hour Trainer Rod Stephens, 2010,

Trang 3

C# 5.0 PROGRAMMER’S REFERENCE

INtROduCtION .xxxiii

▶ PARt I thE C# ECOSyStEM ChAPtER 1 The C# Environment 3

ChAPtER 2 Writing a First Program 11

ChAPtER 3 Program and Code File Structure 27

▶ PARt II C# LANGuAGE ELEMENtS ChAPtER 4 Data Types, Variables, and Constants 53

ChAPtER 5 Operators 99

ChAPtER 6 Methods 121

ChAPtER 7 Program Control Statements 151

ChAPtER 8 LINQ 169

ChAPtER 9 Error Handling 205

ChAPtER 10 Tracing and Debugging 231

▶ PARt III ObjECt-ORIENtEd PROGRAMMING ChAPtER 11 OOP Concepts 245

ChAPtER 12 Classes and Structures 269

ChAPtER 13 Namespaces 303

ChAPtER 14 Collection Classes 317

ChAPtER 15 Generics 343

▶ PARt IV INtERACtING wIth thE ENVIRONMENt ChAPtER 16 Printing 359

ChAPtER 17 Configuration and Resources 393

ChAPtER 18 Streams 411

ChAPtER 19 File System Objects 425

ChAPtER 20 Networking 445

Continues

Trang 4

ChAPtER 23 ADO NET 509

ChAPtER 24 XML 533

ChAPtER 25 Serialization 563

ChAPtER 26 Reflection 581

ChAPtER 27 Cryptography 601

▶ PARt VI APPENdICES APPENdIx A Solutions to Exercises 625

APPENdIx b Data Types 733

APPENdIx C Variable Declarations 737

APPENdIx d Constant Declarations 741

APPENdIx E Operators 743

APPENdIx F Method Declarations 749

APPENdIx G Useful Attributes 753

APPENdIx h Control Statements 757

APPENdIx I Error Handling 761

APPENdIx j LINQ 763

APPENdIx K Classes and Structures 773

APPENdIx L Collection Classes 777

APPENdIx M Generic Declarations 783

APPENdIx N Printing and Graphics 785

APPENdIx O Useful Exception Classes 799

APPENdIx P Date and Time Format Specifiers 803

APPENdIx Q Other Format Specifiers 807

APPENdIx R Streams 813

APPENdIx S Filesystem Classes 821

APPENdIx t Regular Expressions 835

APPENdIx u Parallel Programming 843

Trang 5

APPENdIx V XML 849

APPENdIx w Serialization 859

APPENdIx x Reflection 865

INdEx 877

Trang 7

Programmer’s reference

c# 5.0

Trang 9

Rod Stephens

Programmer’s reference

c# 5.0

Trang 10

Indianapolis, IN 46256

www.wiley.com

Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with

respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose No warranty may be created or extended by sales or pro- motional materials The advice and strategies contained herein may not be suitable for every situation This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services

If professional assistance is required, the services of a competent professional person should be sought Neither the lisher nor the author shall be liable for damages arising herefrom The fact that an organization or Web site is referred to

pub-in this work as a citation and/or a potential source of further pub-information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand Some material included with dard print versions of this book may not be included in e-books or in print-on-demand If this book refers to media such

stan-as a CD or DVD that is not included in the version you purchstan-ased, you may download this material at support.wiley.com For more information about Wiley products, visit www.wiley.com.

http://book-Library of Congress Control Number: 2014930410

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are

trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other countries, and may not be used without written permission All other trademarks are the property of their respective owners John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

Trang 11

AbOut thE AuthOR

ROd StEPhENS started out as a mathematician, but while studying at MIT, he discovered how much fun programming is and has been programming profes-sionally ever since During his career, he has worked on an eclectic assortment

of applications in such fields as telephone switching, billing, repair dispatching, tax processing, wastewater treatment, concert ticket sales, cartography, and training for professional football players

Rod has been a Microsoft Visual Basic Most Valuable Professional (MVP) for more than 10 years and has taught introductory programming at ITT Technical Institute

He has written more than two dozen books that have been translated into languages from all over the world, and more than 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java

Rod’s popular C# Helper website (www.CSharpHelper.com) receives almost a million post visits per year and contains thousands of pages of tips, tricks, and example programs for C# programmers, as

well as example code for this book His VB Helper website (www.vb-helper.com) contains similar material for Visual Basic programmers

You can contact Rod at RodStephens@CSharpHelper.com or RodStephens@vb-helper.com

AbOut thE tEChNICAL EdItOR

bRIAN hOChGuRtEL has been doing NET development for more than 10 years, and actually started

his NET experience with Rod Stephens when they wrote the Wiley book Visual Basic NET and

XML in 2002 Currently Brian works with C#, SQL Server, and SharePoint at Riverside Technology

in Fort Collins, CO

Trang 13

dEVELOPMENt ANd ASSEMbLy

Mary Beth Wakefield

dIRECtOR OF COMMuNIty MARKEtING

Trang 17

PARt I: thE C# ECOSyStEM

#line 34

#pragma 36

Which edition of Visual studio should You Use? xxxv

conventions xxxviii

errata xl

p2p.wrox.com xl

PARt I: thE C# ECOSyStEM

Trang 18

summary 48 exercises 48

PARt II: C# LANGuAGE ELEMENtS

ChAPtER 4: dAtA tyPES, VARIAbLES, ANd CONStANtS 53

Name 62Attributes 62Accessibility 63

Initialization 65

Arrays 67Collections 68

Trang 20

summary 166 exercises 166

from 173where 174orderby 175select 175

join 178

Trang 21

summary 240

exercises 241

Trang 22

classes 245 encapsulation 248 Inheritance 250

abstract 261sealed 262

Polymorphism 263 summary 266 exercises 266

classes 270

attributes 270accessibility 271

events 290

Trang 23

CONTENTS

Trang 24

Iterators 338 summary 339 exercises 340

summary 354 exercises 355

PARt IV: INtERACtING wIth thE ENVIRONMENt

registry 397

Trang 25

summary 443

exercises 444

Trang 26

summary 462 exercises 463

PARt V: AdVANCEd tOPICS

BackgroundWorker 491

TPL 492Parallel For 492Parallel ForEach 494Parallel Invoke 495

Trang 28

summary 597 exercises 597

randomness 603

summary 619 exercises 619

PARt VI: APPENdICES

Trang 32

APPENdIx P: dAtE ANd tIME FORMAt SPECIFIERS 803

Trang 35

whEN It COMES tO PROGRAMMING, a little learning can indeed be a dangerous thing If you

read a book like C# 5.0 All-in-One for Dummies (Bill Sempf et al., 2013, For Dummies) or my book Stephens’ C# Programming with Visual Studio 2010 24-Hour Trainer (Rod Stephens, 2010,

Wrox), after only a few weeks you can easily think you know everything there is to know about programming

I clearly remember when I finished my first programming class The language we used was UCSD Pascal, and after only one class, I knew it quite well I knew how to use the language, how to draw simple graphics, and how to read and write files I was quite sure that with enough work I could write just about any program imaginable

Since then I’ve had plenty of opportunities to realize just how wrong I was I’ve worked on projects

in about a dozen different programming languages, each with its own strengths and sies I’ve worked on elegantly architected systems where adding new features was a breeze, and I’ve worked on badly designed 50,000 plus line monstrosities where you might need to study the code for

idiosyncra-a week before chidiosyncra-anging idiosyncra-a single line for feidiosyncra-ar of breidiosyncra-aking everything else Since then I’ve idiosyncra-also studied complexity theory and learned that there are literally thousands of provably hard (NP-complete) pro-grams that you cannot solve in a reasonable amount of time (I talk about some of them in my book

Essential Algorithms: A Practical Approach to Computer Algorithms, Rod Stephens, 2013, Wiley.)

Even by itself, C# is a complex and powerful programming language It includes all the language tures that you would expect in any high-level language such as structures and classes, methods, com-plex error handling (try, catch, and finally), branching statements (if-then and switch), several kinds of loops (for, foreach, and while), and several ways to break out of loops (break and return)

fea-In addition to the complexities of the language itself, C# provides many auxiliary features that make

it even more powerful and more complicated Features let you execute query-like operations on arrays, use parallel processing, serialize and deserialize objects, and let a program inspect pieces of code to learn about the objects that it is using

Finally, the environment that contains C# brings its own complexity The NET Framework contains more than 10,000 classes that give you access to libraries for cryptography, expression matching, interacting with the operating system, networking, and much more

This book describes as much of that complexity as possible It explains the pieces of the C# language

in detail It explains the syntax, data types, and control statements that go into C# applications This book also describes some of the pieces of the NET Framework that are most useful for building com-plex applications

This book does not cover every possible topic related to C#, but it does cover the majority of the technologies that developers need to build sophisticated applications

Trang 36

whO ShOuLd REAd thIS bOOK

This book is intended for intermediate and advanced programmers who have already programmed

in C# or some other language This book describes C# in detail but it does so quickly and assumes you already understand basic programming concepts If you’re a beginner, you can still use this book to learn to program in C#, but it will be a bit harder If you get stuck, feel free to e-mail me

at RodStephens@CSharpHelper.com and I’ll try to put you back on the right track

One of the main reasons this book assumes you know programming basics is it’s hard to find a simple order in which to present topics in depth For example, declaring and using variables is one

of the most basic concepts in programming (This book covers that early in Chapter 4, “Data Types, Variables, and Constants.”) However, in C# variable declarations are different depending on whether they are inside a class’s method (In some languages methods are also called procedures, subproce-dures, routines, subroutines, or functions.) If you already know what a method is, then the book can cover variables in depth If you are unfamiliar with methods, a book can present only the basics

of variable declarations, then cover classes, and finally return to the topic of variables This book assumes you know basics such as what a variable is and what methods are, so it can quickly move through topics without a lot of repeating and backtracking

If fundamentals such as variable declarations, data types, classes, and arrays are familiar to you, you should have no problem with this book The index and reference appendices should be particularly useful in helping you remember the syntax for performing various C# tasks such as creating a class or making a generic method

If you don’t know what data types are, what a for loop is, and what an if statement does, you can probably pick those things up as you go along, but you may need to go back and reread a few chapters after you get the hang of things

APPROACh

A program can interact with the user in many ways It can read and write text in a console window

It can use Windows Forms and controls to provide a more graphical interface A program can use Windows Presentation Foundation (WPF) controls to build an interface that is even more richly graphical and interactive than Windows Forms interfaces Recently, a Windows Store program can use controls similar to those used in a WPF application to run in the Windows 8 operating system Some programs provide no interface for the user and instead provide tools and services for other programs to use behind the scenes

Building applications that use these different approaches takes a lot of work The steps you take to build a WPF application are different from those you use to build a console application However,

no matter which kind of application you build, behind the user interface sits a bunch of good old C# code You use the same syntax to create classes, loops, methods, and variables whether you’re building Windows Forms applications or WPF applications The same C# language enables you

to build applications to run in a console window, on the Windows desktop, in Windows 8, in a browser, or even in Windows Phone

Trang 37

This book focuses on the C# programming language rather than on user interface design and struction Chapter 2, “Writing a First Program,” explains how to start with different kinds of applica-tions so that you can make applications to test the code, but the main focus is on the code behind the user interface

con-NOtE The main exception to this is Chapter 16, “Printing,” because printing

works differently in the different kinds of applications.

This book also describes methods a program can use to interact with its environment For example, the techniques and classes a program uses to create printouts or manipulate files aren’t actually part

of the C# language, but they are essential for many applications

Finally, this book describes some advanced subjects that are useful in many applications These include such topics as using regular expressions to match patterns, parallel programming, serialization, XML, databases, and cryptography

whICh EdItION OF VISuAL StudIO ShOuLd yOu uSE?

Visual Studio is the integrated development environment that is most often used to write C# grams Because this book focuses on the C# language and not on user interface issues, you can use

pro-it wpro-ith any edpro-ition of Visual Studio You can use one of the free Express edpro-itions or one of the more complete Professional, Premium, or Ultimate editions

NOtE To read about or download one of the Visual Studio Express Editions,

You can use other editions of Visual Studio to study C# programming For example, you could use Visual Studio Express 2013 for Windows, which can build Windows Store applications If you do, the C# code you write behind the scenes will be the same as the code you would write for Windows Desktop but building the user interface will be very different

Trang 38

The C# language and the NET Framework change from time to time but the basics remain the same That means much of this book’s material applies to other versions of C# as well as different editions of Visual Studio For example, there are some differences between C# 4.0 and C# 5.0, but the two versions are mostly the same That means you can use this book even if you have an older version of Visual Studio installed, such as Visual Studio 2010, as long as you understand that a few things may not work (The async and await keywords are the biggest differences.)

hOw thIS bOOK IS ORGANIzEd

The chapters in this book are divided into five parts plus appendices

Part I: the C# Ecosystem

Chapters 1 through 3 explain how C# programs fit into the Visual Studio environment They explain how C# code is converted into code that the computer can execute and how that conversion happens They also explain what files go into a C# application and what those files contain

Chapter 2 briefly explains how you can write simple console, Windows Forms, and WPF tions that can invoke C# code The rest of the book focuses on that code and mostly ignores user interface issues

applica-Part II: C# Language Elements

Chapters 4 through 10 explain the bulk of the C# language and the objects that support it They explain data types (string, float, and arrays), operators (+, *, and %), program control statements (if, while, and for), and error handling They also explain how to edit and debug C# code

Although Language-Integrated Query (LINQ) it is not strictly part of the C# language, it is closely tied

to the language, so Chapter 8, “LINQ,” covers it That chapter also covers Parallel LINQ (PLINQ), a parallel version of LINQ that can provide improved performance on multicore systems

Part III: Object-Oriented Programming

Chapters 11 through 15 explain fundamental concepts in object-oriented programming (OOP) with C# They explains how to define classes and inheritance hierarchies, use collection classes, and build generic classes and methods

Part IV: Interacting with the Environment

Chapters 16 through 20 explain how an application can interact with its environment They show how the program can create printouts, use configuration files, manipulate the filesystem, and down-load information from the Internet

Trang 39

Part V: Advanced topics

Chapters 21 through 27 cover more advanced topics that are useful in many advanced applications They include such topics as recognizing patterns in text, parallel programming, using databases, serialization, reflection, and encrypting and decrypting data

Part VI: Appendices

Appendix A, “Solutions to Exercises,” provides outlines of solutions to the exercises described at the end of each chapter Programs that implement many of the solutions are available for download

on the book’s website This appendix shows the most interesting parts of many of the programs, but to save space I omitted some of the less interesting details Download the examples from

www.wrox.com/go/csharp5programmersref to see all the code

The book’s other appendices provide a categorized reference of the C# language You can use them

to quickly review the syntax of a particular command or refresh your memory of what a particular class can do The chapters earlier in the book give more context, explaining how to perform specific tasks and why one approach might be better than another The appendices provide a brief summary

hOw tO uSE thIS bOOK

If you are an advanced C# programmer, you may want to skim the language basics covered in the first parts of the book You still may find a few new details, so you might not want to skip these chapters entirely, but most of the basic language features are the same as in previous versions of C#

Each chapter ends with a set of exercises you can use to test your understanding of the material covered in the chapter Sometimes exercises point to more in-depth topics that don’t fit well in the chapter’s text Even if you’re an advanced C# developer, you may want to read the exercises to make sure you didn’t miss anything

Intermediate programmers and those with less C# experience should take these chapters a bit more slowly The chapters in Part III, “Object-Oriented Programming,” cover particularly tricky topics Learning all the variations on inheritance and interfaces can be rather confusing If you are unfamil-iar with these topics, plan to spend some extra time on those chapters

Particularly if you have experience with some other programming language but not C#, you should spend some extra time on these first ten or so chapters because they set the stage for the material that follows It will be a lot easier for you to follow a discussion of file management or regular expressions

if you are not confused by the error-handling code that the examples take for granted

Programming is a skill best learned by doing You can pick up the book and read through it quickly

if you like (well, as quickly as you can, given how long it is), but the information is more likely to stick if you open Visual Studio and experiment with some programs of your own

Throughout your work, you can refer to the appendices to get information on specific classes, controls, and syntax For example, you can turn to Appendix R, “Streams,” to quickly find classes you can use

Trang 40

to manipulate files and directories If you need more information, you can go back to Chapter 19, “File System Objects,” or check the online help If you just need to refresh your memory of the basic classes and their methods, however, scanning Appendix R will be faster

NOtE Technically, you can build C# programs without Visual Studio It’s

uncommon, harder than using Visual Studio, and doesn’t let you use Visual

Studio’s amazing programming and debugging features, so this book doesn’t

dis-cuss it For more information, search the Internet for C# without Visual Studio.

Much of C# 5 is compatible with earlier versions of C#, so if you’re using an older version of Visual Studio, you may be able to make most of this book’s examples work with your system You cannot load the example programs directly into your version of Visual Studio, however You need to open the source code files in an editor such as WordPad and copy and paste the significant portions of the code into your program

➤ Code is presented in the following two different ways:

I use a monofont type for code examples.

I use bolded type to emphasize code that's particularly important in the present context.

Ngày đăng: 12/03/2019, 08:12

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN