1. Trang chủ
  2. » Tất cả

microsoft-visual-c-step-by-step-9th-edition-pdfpdf-9th-edition-978-1-5093-0776-0

1,5K 1 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 1.515
Dung lượng 38,76 MB

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

Nội dung

Acknowledgments About the Author Introduction PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT VISUAL STUDIO 2017 Chapter 1 Welcome to C# Beginning programming with the Visual Studio

Trang 3

Ninth Edition

John Sharp

Trang 4

Published with the authorization of Microsoft Corporation by: Pearson Education, Inc.

Copyright © 2018 by Pearson Education, Inc.

All rights reserved This publication is protected by copyright, and permissionmust be obtained from the publisher prior to any prohibited reproduction, storage

in a retrieval system, or transmission in any form or by any means, electronic,mechanical, photocopying, recording, or likewise For information regardingpermissions, request forms, and the appropriate contacts within the PearsonEducation Global Rights & Permissions Department, please visit

www.pearsoned.com/permissions/ No patent liability is assumed with respect tothe use of the information contained herein Although every precaution has beentaken in the preparation of this book, the publisher and author assume no

responsibility for errors or omissions Nor is any liability assumed for damagesresulting from the use of the information contained herein

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied The information provided is on an

“as is” basis The author, the publisher, and Microsoft Corporation shall haveneither liability nor responsibility to any person or entity with respect to any loss

or damages arising from the information contained in this book

Trang 5

For information about buying this title in bulk quantities, or for special salesopportunities (which may include electronic versions; custom cover designs; andcontent particular to your business, training goals, marketing focus, or brandinginterests), please contact our corporate sales department at

Trang 6

Acquisitions Editor

Trang 7

Development Editor

Trang 8

Managing Editor

Trang 9

Senior Project Editor

Trang 10

Copy Editor

Trang 11

Indexer

Trang 12

Proofreader

Trang 13

Technical Editor

Trang 14

Editorial Assistant

Trang 15

Cover Designer

Twist Creative, Seattle Compositor

Trang 16

codemantra

Trang 17

Acknowledgments About the Author Introduction

Trang 18

Platform appCHAPTER 27 Accessing a remote database from a Universal Windows Platform

app

Index

Trang 19

Acknowledgments About the Author Introduction

PART I INTRODUCING MICROSOFT VISUAL C# AND MICROSOFT

VISUAL STUDIO 2017 Chapter 1 Welcome to C#

Beginning programming with the Visual Studio 2017 environmentWriting your first program

Using namespacesCreating a graphical application

Examining the Universal Windows Platform appAdding code to the graphical application

SummaryQuick reference

Chapter 2 Working with variables, operators, and expressions

Understanding statementsUsing identifiers

Identifying keywordsUsing variables

Naming variablesDeclaring variablesSpecifying numeric valuesWorking with primitive data types

Unassigned local variables

Trang 20

Operators and typesExamining arithmetic operatorsControlling precedence

Using associativity to evaluate expressionsAssociativity and the assignment operatorIncrementing and decrementing variables

Prefix and postfixDeclaring implicitly typed local variablesSummary

Quick reference

Chapter 3 Writing methods and applying scope

Creating methods

Declaring a methodReturning data from a methodUsing expression-bodied methodsCalling methods

Specifying the method call syntaxReturning multiple values from a methodApplying scope

Defining local scopeDefining class scopeOverloading methodsWriting methods

Refactoring codeNesting methodsUsing optional parameters and named arguments

Defining optional parametersPassing named arguments

Trang 21

SummaryQuick reference

Chapter 4 Using decision statements

Declaring Boolean variablesUsing Boolean operators

Understanding equality and relational operatorsUnderstanding conditional logical operatorsShort-circuiting

Understanding switch statement syntax Following the switch statement rules

SummaryQuick reference

Chapter 5 Using compound assignment and iteration statements

Using compound assignment operators

Writing while statements Writing for statements

Understanding for statement scope Writing do statements

SummaryQuick reference

Chapter 6 Managing errors and exceptions

Trang 22

Unhandled exceptionsUsing multiple catch handlersCatching multiple exceptionsFiltering exceptions

Propagating exceptionsUsing checked and unchecked integer arithmetic

Writing checked statementsWriting checked expressionsThrowing exceptions

Using throw exceptions Using a finally block

SummaryQuick reference

PART II UNDERSTANDING THE C# OBJECT MODEL

Chapter 7 Creating and managing classes and objects

Understanding classificationThe purpose of encapsulationDefining and using a classControlling accessibility

Working with constructorsOverloading constructorsDeconstructing an objectUnderstanding static methods and data

Creating a shared field

Creating a static field by using the const keyword

Understanding static classes

Static using statements

Trang 23

Quick reference

Chapter 8 Understanding values and references

Copying value type variables and classesUnderstanding null values and nullable types

The null-conditional operatorUsing nullable types

Understanding the properties of nullable types

Using ref and out parameters

Creating ref parameters Creating out parameters

How computer memory is organized

Using the stack and the heap

The System.Object class

BoxingUnboxingCasting data safely

The is operator The as operator The switch statement revisited

SummaryQuick reference

Chapter 9 Creating value types with enumerations and structures

Working with enumerations

Declaring an enumerationUsing an enumerationChoosing enumeration literal valuesChoosing an enumeration’s underlying typeWorking with structures

Trang 24

Understanding structure initializationCopying structure variables

SummaryQuick reference

Chapter 10 Using arrays

Declaring and creating an array

Declaring array variablesCreating an array instancePopulating and using an array

Creating an implicitly typed arrayAccessing an individual array elementIterating through an array

Passing arrays as parameters and return values for a methodCopying arrays

Using multidimensional arrays

Creating jagged arraysAccessing arrays that contain value typesSummary

Quick reference

Chapter 11 Understanding parameter arrays

Overloading—a recapUsing array arguments

Declaring a params array Using params object[ ] Using a params array

Comparing parameter arrays and optional parameters

Trang 25

Declaring new methodsDeclaring virtual methods

Declaring override methods Understanding protected access

Creating extension methodsSummary

Quick reference

Chapter 13 Creating interfaces and defining abstract classes

Understanding interfaces

Defining an interfaceImplementing an interfaceReferencing a class through its interfaceWorking with multiple interfaces

Explicitly implementing an interfaceInterface restrictions

Defining and using interfacesAbstract classes

Abstract methodsSealed classes

Sealed methodsImplementing and using an abstract classSummary

Trang 26

Chapter 14 Using garbage collection and resource management

The life and times of an object

Writing destructorsWhy use the garbage collector?

How does the garbage collector work?

RecommendationsResource management

Disposal methodsException-safe disposal

The using statement and the IDisposable interface Calling the Dispose method from a destructor

Implementing exception-safe disposalSummary

Quick reference

PART III DEFINING EXTENSIBLE TYPES WITH C#

Chapter 15 Implementing properties to access fields

Implementing encapsulation by using methodsWhat are properties?

Using propertiesRead-only propertiesWrite-only propertiesProperty accessibilityUnderstanding the property restrictionsDeclaring interface properties

Replacing methods with propertiesGenerating automatic properties

Initializing objects by using properties

Trang 27

Chapter 16 Handling binary data and using indexers

What is an indexer?

Storing binary valuesDisplaying binary valuesManipulating binary valuesSolving the same problems using indexersUnderstanding indexer accessors

Comparing indexers and arraysIndexers in interfaces

Using indexers in a Windows applicationSummary

Creating a generic class

The theory of binary treesBuilding a binary tree class by using genericsCreating a generic method

Defining a generic method to build a binary treeVariance and generic interfaces

Covariant interfacesContravariant interfacesSummary

Quick reference

Trang 28

What are collection classes?

The List<T> collection class The LinkedList<T> collection class The Queue<T> collection class The Stack<T> collection class The Dictionary<TKey, TValue> collection class The SortedList<TKey, TValue> collection class The HashSet<T> collection class

Using collection initializers

The Find methods, predicates, and lambda expressions

The forms of lambda expressionsComparing arrays and collections

Using collection classes to play cardsSummary

Quick reference

Chapter 20 Decoupling application logic and handling events

Understanding delegates

Examples of delegates in the NET Framework class libraryThe automated factory scenario

Trang 29

Implementing the factory by using a delegateDeclaring and using delegates

Lambda expressions and delegates

Creating a method adapterEnabling notifications by using events

Declaring an eventSubscribing to an eventUnsubscribing from an eventRaising an event

Understanding user interface events

Using eventsSummary

Using query operators

Querying data in Tree<TItem> objects

LINQ and deferred evaluationSummary

Quick reference

Chapter 22 Operator overloading

Understanding operators

Operator constraints

Trang 30

Implementing operatorsUnderstanding conversion operators

Providing built-in conversionsImplementing user-defined conversion operatorsCreating symmetric operators, revisited

Writing conversion operatorsSummary

Tasks, threads, and the ThreadPool

Creating, running, and controlling tasks

Using the Task class to implement parallelism Abstracting tasks by using the Parallel class When not to use the Parallel class

Canceling tasks and handling exceptions

The mechanics of cooperative cancellationUsing continuations with canceled and faulted tasksSummary

Trang 31

Using PLINQ to parallelize declarative data access

Using PLINQ to improve performance while iteratingthrough a collection

Canceling a PLINQ querySynchronizing concurrent access to data

Locking dataSynchronization primitives for coordinating tasksCanceling synchronization

The concurrent collection classesUsing a concurrent collection and a lock to implementthread-safe data access

SummaryQuick reference

Chapter 25 Implementing the user interface for a Universal Windows

Platform app

Features of a Universal Windows Platform appUsing the Blank App template to build a Universal WindowsPlatform app

Implementing a scalable user interfaceApplying styles to a UI

Summary

Trang 32

Creating a ViewModelAdding commands to a ViewModelSearching for data using Cortana

Providing a vocal response to voice commandsSummary

Reporting errors and updating the UISummary

Quick reference

Index

Trang 33

Well, here we are again, in what appears to have become a biennial event;such is the pace of change in the world of software development! As I glance at

a few elite souls, then the market for C# books would have disappeared after thefirst couple of editions of this tome Thus cheered, I power up my laptop, mymind mocking the bygone era when such processing power could have navigatedmany hundreds of Apollo spacecraft simultaneously to the moon and back, andget down to work on the latest edition of this book!

Despite the fact that my name is on the cover, authoring a book such as this isfar from a one-man project I’d like to thank the following people who haveprovided unstinting support and assistance throughout this exercise

First, Trina MacDonald at Person Education, who took on the role of

prodding me into action and ever-so-gently tying me down to well-defined

deliverables and hand-off dates Without her initial impetus and cajoling, thisproject would not have got off the ground

Next, Rick Kughen, the tireless copy editor who ensured that my grammarremained at least semi-understandable, and picked up on the missing words andnonsense phrases in the text

Then, David Franson, who had the unenviable task of testing the code andexercises I know from experience that this can be a thankless and frustratingtask at times, but the hours spent and the feedback that results can only make for

Trang 34

As ever, I must also thank Diana, my better half, who keeps me supplied withcaffeine-laden hot drinks when deadlines are running tight Diana has been long-suffering and patient, and has so far survived my struggle through nine editions

of this book; that is dedication well beyond the call of duty She has recentlytaken up running I assumed it was to keep fit, but I think it is more likely so shecan get well away from the house and scream loudly without my hearing her!And lastly, to James and Frankie, who have both now flown the nest James istrying to avoid gaining a Yorkshire accent while living and working in Sheffield,but Frankie has remained closer to home so she can pop in and raid the kitchenfrom time to time

Trang 35

John Sharp is a principal technologist for CM Group Ltd, a software

development and consultancy company in the United Kingdom He is well

versed as a software consultant, developer, author, and trainer, with more than 35years of experience, ranging from Pascal programming on CP/M and C/Oracleapplication development on various flavors of UNIX to the design of C# andJavaScript distributed applications and development on Windows 10 and

Microsoft Azure He also spends much of his time writing courseware for

Microsoft, focusing on areas such as Data Science using R and Python, Big Dataprocessing with Spark and CosmosDB, and scalable application architecturewith Azure

Trang 36

Microsoft Visual C# is a powerful but simple language aimed primarily atdevelopers who create applications built on the Microsoft NET Framework.Visual C# inherits many of the best features of C++ and Microsoft Visual Basicbut few of the inconsistencies and anachronisms, which results in a cleaner andmore logical language

C# 1.0 made its public debut in 2001

C# 2.0, with Visual Studio 2005, provided several important new features,including generics, iterators, and anonymous methods

C# 3.0, which was released with Visual Studio 2008, added extensionmethods, lambda expressions, and most famously of all, the Language-Integrated Query facility, or LINQ

C# 4.0 was released in 2010 and provided further enhancements that

improved its interoperability with other languages and technologies Thesefeatures included support for named and optional arguments and the

dynamic type, which indicates that the language runtime should implement

late binding for an object An important addition to the NET Framework,and released concurrently with C# 4.0, were the classes and types thatconstitute the Task Parallel Library (TPL) Using the TPL, you can buildhighly scalable applications that can take full advantage of multicore

processors

C# 5.0 added native support for asynchronous task-based processing

through the async method modifier and the await operator.

C# 6.0 was an incremental upgrade with features designed to make lifesimpler for developers These features include items such as string

interpolation (you need never use String.Format again!), enhancements to

the ways in which properties are implemented, expression-bodied

methods, and others

C# 7.0 adds further enhancements to aid productivity and remove some ofthe minor anachronisms of C# For example, you can now implement

Trang 37

multiple values in the form of tuples, the use of out parameters has been simplified, and switch statements have been extended to support pattern-

and type-matching There are other updates as well, which are covered inthis book

It goes without saying that Microsoft Windows 10 is an important platformfor running C# applications, but now you can also run code developed by usingC# on other operating systems, such as Linux, through the NET Core runtime.This opens up possibilities for writing code that can run in multiple

environments Additionally, Windows 10 supports highly interactive applicationsthat can share data and collaborate as well as connect to services running in thecloud The key notion in Windows 10 is Universal Windows Platform (UWP)apps—applications designed to run on any Windows 10 device, whether a fullyfledged desktop system, a laptop, a tablet, or even an IoT (Internet of Things)device with limited resources Once you have mastered the core features of C#,gaining the skills to build applications that can run on all these platforms is

important

Voice activation is another feature that has come to the fore, and Windows 10includes Cortana, your personal voice-activated digital assistant You can

integrate your own apps with Cortana to allow them to participate in data

searches and other operations Despite the complexity normally associated withnatural-language speech analysis, enabling your apps to respond to Cortana’srequests is surprisingly easy; I cover this in Chapter 26 Also, the cloud has

become such an important element in the architecture of many systems—rangingfrom large-scale enterprise applications to mobile apps running on portable

devices—that I decided to focus on this aspect of development in the final

chapter of the book

The development environment provided by Visual Studio 2017 makes thesefeatures easy to use, and the many new wizards and enhancements included inthe latest version of Visual Studio can greatly improve your productivity as adeveloper I hope you have as much fun working through this book as I hadwriting it!

Who should read this book

This book assumes that you are a developer who wants to learn the fundamentals

Trang 38

as ADO.NET, ASP.NET, Azure, or Windows Communication Foundation If yourequire more information on any of these items, you might consider readingsome of the other titles available from Microsoft Press

Organization of this book

This book is divided into four sections:

Part I, “Introducing Microsoft Visual C# and Microsoft Visual Studio2017,” provides an introduction to the core syntax of the C# language andthe Visual Studio programming environment

Part II, “Understanding the C# object model,” goes into detail on how tocreate and manage new types in C# and how to manage the resourcesreferenced by these types

Part III, “Defining extensible types with C#,” includes extended coverage

of the elements that C# provides for building types that you can reuseacross multiple applications

Part IV, “Building Universal Windows Platform applications with C#,”describes the universal Windows 10 programming model and how you canuse C# to build interactive applications for this model

Finding your best starting point in this book

This book is designed to help you build skills in a number of essential areas You

Trang 39

New to object-oriented

programming

1 Install the practice files as described in theupcoming section, “Code samples.”

2 Work through the chapters in Parts I, II, and IIIsequentially

3 Complete Part IV as your level of experienceand interest dictates

Familiar with procedural

programming languages,

such as C, but new to C#

1 Install the practice files as described in theupcoming section, “Code samples.”

2 Skim the first five chapters to get an overview

of C# and Visual Studio 2017, and thenconcentrate on Chapters 6 through 22

3 Complete Part IV as your level of experienceand interest dictates

Migrating from an object-oriented language such as

C++ or Java

1 Install the practice files as described in theupcoming section, “Code samples.”

2 Skim the first seven chapters to get anoverview of C# and Visual Studio 2017, andthen concentrate on Chapters 8 through 22

3 For information about building UniversalWindows Platform applications, read Part IV.Switching from Visual

Basic to C#

1 Install the practice files as described in theupcoming section, “Code samples.”

2 Work through the chapters in Parts I, II, and IIIsequentially

3 For information about building UniversalWindows Platform applications, read Part IV

4 Read the Quick Reference sections at the end

of the chapters for information about specificC# and Visual Studio 2017 constructs

Trang 40

working through the

exercises

1 Use the index or the table of contents to findinformation about particular subjects

2 Read the Quick Reference sections at the end

of each chapter to find a brief review of thesyntax and techniques presented in the chapter

Most of the book’s chapters include hands-on samples that let you try out theconcepts you just learned No matter which sections you choose to focus on, besure to download and install the sample applications on your system

Conventions and features in this book

This book presents information by using conventions designed to make theinformation readable and easy to follow

Each exercise consists of a series of tasks, presented as numbered steps (1,

2, and so on) listing each action you must take to complete the exercise.Boxed elements with labels such as “Note” provide additional information

or alternative methods for completing a step successfully

Text that you type (apart from code blocks) appears in bold

A plus sign (+) between two key names means that you must press thosekeys at the same time For example, “Press Alt+Tab” means that you holddown the Alt key while you press the Tab key

System requirements

You will need the following hardware and software to complete the practiceexercises in this book:

Windows 10 (Home, Professional, Education, or Enterprise) version 1507

or higher

The most recent build of Visual Studio Community 2017, Visual StudioProfessional 2017, or Visual Studio Enterprise 2017 (make sure that youhave installed any updates) As a minimum, you should select the

following workloads when installing Visual Studio 2017:

• Universal Windows Platform development

Ngày đăng: 08/10/2021, 21:04