Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Beginning Visual C#
PREMIUM
Số trang
946
Kích thước
16.6 MB
Định dạng
PDF
Lượt xem
1442

Beginning Visual C#

Nội dung xem thử

Mô tả chi tiết

Beginning Visual C#

Karli Watson

David Espinosa

Zach Greenvoss

Christian Nagel

Jacob Hammer Pedersen

Jon D. Reid

Matthew Reynolds

Morgan Skinner

Eric White

Wrox Press Ltd. ©

© 2002 Wrox Press

All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form

or by any means, without the prior written permission of the publisher, except in the case of brief quotations

embodied in critical articles or reviews.

Beginning Visual C#

Karli Watson

David Espinosa

Zach Greenvoss

Christian Nagel

Jacob Hammer Pedersen

Jon D. Reid

Matthew Reynolds

Morgan Skinner

Eric White

Wrox Press Ltd. ©

© 2002 Wrox Press

All rights reserved. No part of this book may be reproduced, stored in a retrieval system or transmitted in any form

or by any means, without the prior written permission of the publisher, except in the case of brief quotations

embodied in critical articles or reviews.

The author and publisher have made every effort in the preparation of this book to ensure the accuracy of the

information. However, the information contained in this book is sold without warranty, either express or implied.

Neither the authors, Wrox Press, nor its dealers or distributors will be held liable for any damages caused or alleged

to be caused either directly or indirectly by this book.

Beginning Visual C# is a revised edition of Beginning C# (Wrox Press, ISBN 1-86100-498-2).

Published by Wrox Press Ltd,

Arden House, 1102 Warwick Road, Acocks Green,

Birmingham, B27 6BH, UK

Printed in the United States

ISBN 1-86100-758-2

Trademark Acknowledgments

Wrox has endeavored to provide trademark information about all the companies and products mentioned in this

book by the appropriate use of capitals. However, Wrox cannot guarantee the accuracy of this information.

Credits

Authors

Karli Watson

David Espinosa

Zach Greenvoss

Christian Nagel

Jacob Hammer Pedersen

Jon D. Reid

Matthew Reynolds

Morgan Skinner

Eric White

Authors (1st Edition)

Marco Bellinaso

Ollie Cornes

Commissioning Editor (1st Edition)

Julian Skinner

Managing Editor

Louay Fatoohi

Technical Editors

Mankee Cheng

Matthew Cumberlidge

Douglas Paterson

Project Manager

Claire Robinson

Author Agent

Charlotte Smith

Production Coordinator

Sarah Hall

Cover

Natalie O'Donnell

Indexers

Andrew Criddle

Michael Brinkman (1st Edition)

Fiona Murray (1st Edition)

Technical Reviewers

Cristian Darie

Karli Watson

Technical Reviewers (1st Edition)

Kenneth Avellino

Ramesh Balaji

Christopher Blexrud

Brandon Bohling

Richard Bonneau

Paul Brazdzionis

Beth Breidenbach

Andreas Christiansen

Steve Danielson

Scott Hanselman

Ben Hickman

Mark Horner

Deepak Kumer

Ron Landers

Don Lee

Shaun Mcaravey

Angela Mallet

Jason Montgomery

Johan Normén

Aruna Panangipally

Phil Powers-DeGeorge

Jawaharlal Puvvala

Matthew Reynolds

Scott Robertson

Kristy Saunders

Keyur Shah

Helmut Watson

Donald Xie

Proofreaders

Fiona Berryman

Chris Smith

About the Authors

Karli Watson

Karli Watson is an in-house author for Wrox Press with a penchant for multicolored clothing. He started out with the

intention of becoming a world famous nanotechnologist, so perhaps one day you might recognize his name as he

receives a Nobel Prize. For now, though, Karli's computing interests include all things mobile, and upcoming

technologies such as C#. He can often be found preaching about these technologies at conferences, as well as

after hours in drinking establishments. Karli is also a snowboarding enthusiast, and wishes he had a cat.

Thanks go to the Wrox team, both for helping me get into writing, and then dealing with the results when I

started. Finally, and most importantly, thanks to my wife, Donna, for continuing to put up with me.

David Espinosa

David Espinosa is a Senior Programmer and owner of Espinosa Consulting. Born in Barcelona, Spain, David moved

to the United States at an early age. He attended the University of Nevada and received a Bachelor of Arts degree

in Political Science.

David concentrates on Microsoft technologies and tools. In 1999, he worked with Microsoft as a Lead Author for the

Desktop Visual FoxPro Certification Exam. Recently, David has been focusing on e-commerce and data integration

solutions and works for the a manufacturing company based out of Reno, Nevada.

I would like to dedicate my work to Mom and Dad, who sacrificed so much so I could have a better chance.

I would also like to dedicate my work to my three favorite girls in the world: Cynthia, Jayme, and Emily. Thank

you for all your support.

Zach Greenvoss

Zach Greenvoss, MCSD is a Senior Consultant with Magenic Technologies, a Microsoft Gold Certified consulting

firm in Northern California. He specializes in middle-tier architecture and implementation, utilizing various

technologies including COM+, MSMQ, BizTalk, and XML. Before Magenic, Zach worked at the Defense Manpower

Data Center in Monterey California, where he developed client-server applications for the Department of Defense.

Zach and his wife Amanda enjoy globetrotting, caving, gaming, and playing with their two cats. He can be reached

at [email protected].

I would like to thank my wife Amanda for all her patience, love, and understanding of the time required to both

work and write. I would also like to thank Kay Rigg for his mentorship and guidance: without you I would not

be where I am today. Finally, I am proud to say that I am a CSU Monterey Bay graduate - Go Otters!

Christian Nagel

Christian Nagel works as a trainer and consultant for Global Knowledge, the largest independent information

technology training provider. Christian started his computing career with PDP 11 and VAX/VMS platforms. Since

then he has used a variety of languages and platforms, including Pascal, C, X-Windows, Motif, C++, Java,

COM/ATL, COM+, and currently C# and .NET. With his profound knowledge of Microsoft technologies - he's

certified as Microsoft Certified Trainer (MCT), Solution Developer (MCSD), and Systems Engineer (MCSE) - he

enjoys teaching others programming and architecting distributed solutions. As founder of the .NET User Group

Austria and as MSDN Regional Director he is speaker at European conferences (TechEd, VCDC), and is contacted

by many developers for coaching, consulting, and teaching customized courses and boot camps. You will find

Christian's web site at http://christian.nagel.net/.

I would like to thank the people at Wrox who got me started writing books, and Christian Seidler who supports

my activities at Global Knowledge. Special thanks are also sent to the people at Microsoft, primarily to Alex

Holy in Vienna for his organization of Visual Studio events and for his support of the .NET user community.

Finally, and most importantly, I would like to thank my wife Elisabeth for her love and support.

Jacob Hammer Pedersen

Jacob Hammer Pedersen is a systems developer at ICL Invia - a member of the Fujitsu Group.

He pretty much started programming when he was able to spell the word 'BASIC', which, incidentally is the

language he's primarily using today. He started programming the PC in the early 90s, using Pascal, but soon

changed his focus to C++, which still holds his interest. In the mid 90s his focus changed again, this time to Visual

Basic. In the summer of 2000 he discovered C# and has been happily exploring it ever since.

Primarily working on the Microsoft platforms, other expertise includes MS Office development, COM, COM+ and

Visual Basic .Net.

A Danish citizen, he works and lives in Aarhus, Denmark.

Jon D. Reid

Jon is the Chief Technology Officer for Micro Data Base Systems, Inc. (www.mdbs.com), maker of the TITANIUM

Database Engine and GURU Expert System tool. His primary current activity is developing database tools for the

Microsoft .NET environment. He was editor for the C++ and Object Query Language (OQL) components of the

Object Data Management Group (ODMG) standard, and has co-authored other Wrox titles including ADO.NET

Programmer's Reference and Professional SQL Server 2000 XML. When not working, writing, or bicycling, he

enjoys spending time with his wife and two young sons. Jon would like to thank his family and the team at Wrox for

their support and encouragement.

Matthew Reynolds

After working with Wrox Press on a number of projects since 1999, Matthew is now an in-house author for Wrox

Press writing about and working with virtually all aspects of Microsoft .NET. He's also a regular contributor to Wrox's

ASPToday, C#Today and Web Services Architect. He lives and works in North London and can be reached on

[email protected].

Thanks very much to the following in their support and assistance in writing this book: Len, Edward, Darren,

Alex, Jo, Tim, Clare, Martin, Niahm, Tom, Ollie, Amir, Gretchen, Ben, Brandon, Denise, Rob, Waggy, Mark,

Elaine, James, Zoe, Faye, and Sarah. And, also thanks to my new friends at Wrox, which include Charlotte,

Laura, Karli, Dom S, Dom L, Ian, Kate, Joy, Pete, Helen, John, Dave, Adam, Craig, Jake, Julian, and Paul.

Morgan Skinner

I started my computing at a tender age on a ZX80 at school, where I was underwhelmed by some code my teacher

had put together and decided I could do better in assembly language. After getting hooked on Z80 (much better

than those paltry three registers in 6502 land!) I graduated through the school ZX81s to my own ZX Spectrum.

Since then I've used all sorts of languages and platforms, including VAX Macro Assembler (way cool!), Pascal,

Modula2, Smalltalk, x86 assembly language, PowerBuilder, C/C++, Visual Basic, and currently C#. I've managed to

stay in the same company for nearly 12 years, largely down to the diversity of the job and a good working

environment.

In my spare time I'm a bit of a DIY nut, I spend lots of money on bicycles, and 'relax' by fighting weeds on my

allotment.

I can be reached by e-mail at [email protected].

Eric White

Eric White is an independent consultant, specializing in managing offshore development with some hotshot

developers in India. Having written well over a million lines of code, Eric has over 20 years experience in building

Management Information Systems, accounting systems, and other types of fat-client and n-tier database

applications. Eric has particular interest in Object-Oriented design methodologies, including use case analysis, UML,

and design patterns. After years of working with too many varieties of technologies to list, he is currently specializing

in C#, VB.NET, ASP.NET, ADO.NET, XML, COM+, GDI+, SQL Server, and other Microsoft technologies.

He loves meeting new people and traveling to far-flung places, and is equally at ease wandering around the streets

of Bangalore, London, and San Francisco. When he is not in front of a computer, he loves hiking in the mountains

of Colorado and India. He can be reached at [email protected].

Beginning Visual C#

byKarli Watsonet al. ISBN:0764543822

Wrox Press 2003 (903 pages)

By using this book, you’ll come to understand the fundamentals

of the C# language and learn to program the .NET Framework;

the book will help you succeed—from your first steps in the

language up to where you are ready to write real world C#

applications.

Table of Contents Back Cover

Table of Contents

Beginning Visual C#

Introduction

Chapter 1 - Introducing C#

Chapter 2 - Writing a C# Program

Chapter 3 - Variables and Expressions

Chapter 4 - Flow Control

Chapter 5 - More About Variables

Chapter 6 - Functions

Chapter 7 - Debugging and Error Handling

Chapter 8 - Introduction to Object-Oriented Programming

Chapter 9 - Defining Classes

Chapter 10 - Defining Class Members

Chapter 11 - More About Classes

Chapter 12 - Events

Chapter 13 - Using Windows Form Controls

Chapter 14 - Advanced Windows Forms Features

Chapter 15 - Using Common Dialogs

Chapter 16 - Introduction to GDI+

Chapter 17 - Deploying Windows Applications

Chapter 18 - Getting At Your Data

Chapter 19 - Data Access with ADO.NET

Chapter 20 - Working With Files

Chapter 21 - .NET Assemblies

Chapter 22 - Attributes

Chapter 23 - ASP.NET Applications

Chapter 24 - Web Services

Appendix A - Setting the PATH Environment Variable

Appendix B - Installing MSDE

Appendix C - Further References

Index

List of Try It Outs

Introduction

byKarli Watsonet

al.

Wrox Press 2003

Introduction

Why should I learn C#? If you've bought this book, you've probably answered that question for yourself anyway, but

it's worth reiterating. C# is Microsoft's brand new language, designed for its brand new platform, the .NET

Framework. As such, C# is likely to be the language of choice for developing applications in the Microsoft world.

That alone would make C# a great choice as a first language to learn. But, perhaps more importantly, C# is a very

elegantly designed language, which encourages good programming practice (in particular with regard to object￾oriented programming). C# is descended directly from the powerful but complex C++ language, and inherits most of

the power without the complexity. C# has also been deeply influenced by other languages, including Java and

Delphi, and its fans believe that it has been able to take the best of these languages - while avoiding their mistakes.

This book has been designed to teach you C# from first principles, without assuming any prior programming

experience. We'll give you a thorough grounding in the syntax of the C# language itself, and then we'll look at the

most common different types of applications you can build with C# - Windows applications, ASP.NET web

applications, and web services. It's important to stress from the outset that C# programming cannot be separated

from .NET programming (in fact, the C# compiler comes as part of the .NET Framework), and everything you do in

C# will rely very heavily on the .NET Framework. Therefore, this book goes beyond the mere syntax of the C#

language and shows you how to use the .NET classes from within C# to build real applications. As a result, once

you've learned C#, you won't have too much difficulty picking up other .NET languages, such as Visual Basic .NET

or Managed C++.

Who Is This Book For?

This book is aimed at relatively inexperienced programmers who want to learn how to build applications using C#.

Developers who have a little experience with earlier languages such as Visual Basic will also find this book helpful

as a hands-on tutorial to C#. This book is for everyone who's tired of C# books that assume you've got ten-plus

years' experience of writing C++ programs!

Important This is a Wrox Beginning… series book, so we will aim to teach you everything you need to know

from scratch. If you already have experience of programming in C++, VB, or Java, you may be

more comfortable starting at a somewhat quicker pace with the natural follow-up title Professional

C# 2nd Edition (Wrox Press, ISBN 1-86100-704 3).

This book will be ideal for two types of beginner:

You're a beginner to programming and you've chosen C# as your first language. As we said earlier, C# is an

excellent language to learn programming through, and this book will help you through the challenge of learning

some strange new concepts!

You have some experience programming in another language, but you're a beginner to .NET programming.

.NET represents a revolution in programming concepts, and the fundamental importance of object-oriented

programming (OOP) to .NET can be confusing if you're not familiar with this technique. If you're coming to C#

from a language which doesn't support (or only partially supports) OOP, you will appreciate the entire section

dedicated to OOP in this book.

Introduction

byKarli Watsonet

al.

Wrox Press 2003

What Does This Book Cover?

This book was written using Version 1.0 of the .NET Framework, released in January 2002, and Version 1.0 of

Visual Studio .NET, released in February 2002. These versions are the release versions of these products, and no

major changes are expected in the near future.

The book is divided into seven main sections:

Getting Started

In the first two chapters we quickly introduce the major concepts you need to understand before writing a C#

application, and then go on to create a very simple C# program using Visual Studio .NET to do most of the hard

work for us.

C# Language Basics

7 introduce the basic building blocks of the C# language. This section looks at how we store data in C# variables,

how we control the flow of our program with conditional branches and loops, and how we structure code with

functions.

Programming with Objects

Objects and the principles of object-oriented programming (OOP) play a fundamental role in C#, so 12 will

introduce the notion of OOP and the philosophy behind it, and look at how we use objects within our C# code.

Working with Windows Forms

The first sections concentrate mostly on creating simple console applications in order to give you a thorough

grounding in the C# language itself. In this section, we go beyond those to look in detail at how we create real

Windows applications in C#.

Programming on the .NET Framework

As already mentioned, almost everything we do in C# is totally dependent on the .NET Framework. This section

looks at some important topics where we need to use classes from the .NET Framework, including accessing

databases and working with files on the local machine or network. We also take a more detailed look at two

features specific to .NET programming – assemblies (the actual unit of deployment of a .NET program), and

attributes (a feature of .NET that allows us to provide additional information about parts of our program).

C# and the Web

Once we've come so far, we'll take a quick look at a whole new topic, but one that's integral to the whole idea of the

.NET Framework – programming for the Internet. In this last section of the book we look at ASP.NET and web

services. ASP.NET allows us to write dynamic web pages in C#, and web services enable applications to exchange

information across the Internet.

Important Most of the chapters in the book have a series of exercises at the end, to help you as you learn

C#. The answers to these exercises can be found on the P2P web site at

http://p2p.wrox.com. We'll tell you how to register for P2P at the end of this introduction.

Introduction

byKarli Watsonet al.

Wrox Press 2003

What Do I Need to Use This Book?

Obviously, the most important thing you need to write C# programs is the C# compiler itself. This comes with the .NET Framework SDK, which can be downloaded

from Microsoft's site the following URL:

http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/MSDN-FILES/027/000/976/msdncompositedoc.xml

This is the current link, but may be subject to change. (We've broken the link up in two lines here for formatting purposes – the URL should be entered as one

continuous string). Be warned that this currently weighs in at a hefty 131 MB, so it will take a while to download! This runs on Windows 2000, Windows XP, and

Windows NT4, and contains all you need to write all types of C# applications. A minimal version of the .NET Framework can be installed on Windows 95, 98, and

ME, but this installation does not include many of the tools you will need.

However, in this book we will be making heavy use of the Visual Studio .NET development environment, which simplifies writing C# code in many ways, but is

particularly useful for writing Windows applications because it contains a visual form designer. If you are not using Visual Studio .NET, then you will not be able to

get full value from this book.

Version 1.0 of Visual Studio .NET is available in three editions (Professional, Enterprise Developer, and Enterprise Architect), any of which will do for the code in

this book. Full information is available at http://msdn.microsoft.com/vstudio/ , including the system requirements. Like the .NET Framework SDK,

Visual Studio.NET also runs on Windows 2000, XP, and NT4.

Alternatively, and if you are on a tighter budget, you might like to check out Microsoft Visual C# .NET Standard Edition, a C# only developer environment has many

of the features of Visual Studio .NET – but not all of them. Because of the feature limitations of Visual C# .NET Standard Edition compared to Visual Studio .NET,

not every aspect of the book can be used from Visual C# .NET Standard Edition, and we've highlighted these areas. If you are using Visual C# .NET Standard

Edition, remember that the C# compiler has not been restricted – this is separate from the development environment – it is only features of the development

environment that are limited.

Important

This book is intended for users of Visual Studio .NET or Visual C# .NET Standard Edition.

Introduction

byKarli Watsonet

al.

Wrox Press 2003

Conventions

We've used a number of different styles of text and layout in this book to help differentiate between the different

kinds of information. Here are examples of the styles we used and an explanation of what they mean.

Code has several styles. If it's a word that we're talking about in the text - for example, when discussing a for

(...) loop, it's in this font. If it's a block of code that can be typed as a program and run, then it's also in a gray box:

for (int i=0; i<10; i++)

{

Console.WriteLine(i);

}

Sometimes we'll see code in a mixture of styles, like this:

for (int i=0; i<10; i++)

{

Console.Write("The next number is: ");

Console.WriteLine(i);

}

In cases like this, the code with a white background is code we are already familiar with; the line highlighted in gray

is a new addition to the code since we last looked at it.

Advice, hints, and background information comes in this type of font.

Important Important pieces of information come in boxes like

this.

Bullets appear indented, with each new bullet marked as follows:

Important words are in a bold type font.

Words that appear on the screen, or in menus like the File or Window, are in a similar font to the one you would

see on a Windows desktop.

Keys that you press on the keyboard like Ctrl and Enter, are in italics.

Introduction

byKarli Watsonet

al.

Wrox Press 2003

Customer Support

We always value hearing from our readers, and we want to know what you think about this book: what you liked,

what you didn't like, and what you think we can do better next time. You can send us your comments, either by

returning the reply card in the back of the book, or by e-mail to [email protected]. Please be sure to mention the

book title in your message.

How to Download the Sample Code for the Book

When you visit the Wrox site, http://www.wrox.com/, simply locate the title through our Search facility or by using one

of the title lists. Click on Download in the Code column, or on Download Code on the book's detail page.

When you click to download the code for this book, you are presented with a page with three options:

If you are already a member of the Wrox Developer Community (if you have already registered on ASPToday,

C#Today, or Wroxbase), you can log in with your usual username and password combination to receive your

code.

If you are not already a member, you are asked if you would like to register for free code downloads. In addition

you will also be able to download several free articles from Wrox Press. Registering will allow us to keep you

informed about updates and new editions of this book.

The third option is to bypass registration completely and simply download the code.

Registration for code download is not mandatory for this book, but should you wish to register for your code

download, your details will not be passed to any third party. For more details, you may wish to view our terms and

conditions, which are linked from the download page.

Once you reach the code download section, you will find that the files that are available for download from our site

have been archived using WinZip. When you have saved the files to a folder on your hard drive, you will need to

extract the files using a de-compression program such as WinZip or PKUnzip. When you extract the files, the code

is usually extracted into chapter folders. When you start the extraction process, ensure your software (WinZip,

PKUnzip, etc.) is set to use folder names.

Errata

We've made every effort to make sure that there are no errors in the text or in the code. However, no one is perfect

and mistakes do occur. If you find an error in one of our books, like a spelling mistake or a faulty piece of code, we

would be very grateful for feedback. By sending in errata you may save another reader hours of frustration, and of

course, you will be helping us provide even higher quality information. Simply e-mail the information to

[email protected], where your information will be checked and, if correct, posted to the errata page for that title, or

used in subsequent editions of the book.

To find errata on the web site, go to http://www.wrox.com/, and simply locate the title through our Advanced Search or

title list. Click on the Book Errata link, which is below the cover graphic on the book's detail page.

E-mail Support

If you wish to directly query a problem in the book with an expert who knows the book in detail then e-mail

[email protected], with the title of the book and the last four numbers of the ISBN in the subject field of the e-mail. A

typical e-mail should include the following things:

The title of the book, last four digits of the ISBN (7582), and page number of the problem in the Subject

field

Your name, contact information, and the problem in the body of the message

We won't send you junk mail. We need the details to save your time and ours. When you send an e-mail message,

it will go through the following chain of support:

Customer Support - Your message is delivered to our customer support staff, who are the first people to read it.

They have files on most frequently asked questions and will answer anything general about the book or the

web site immediately.

Editorial - Deeper queries are forwarded to the technical editor responsible for that book. They have experience

with the programming language or particular product, and are able to answer detailed technical questions on

the subject.

The Authors - Finally, in the unlikely event that the editor cannot answer your problem, they will forward the

request to the author. We do try to protect the author from any distractions to their writing; however, we are

quite happy to forward specific requests to them. All Wrox authors help with the support on their books. They

will e-mail the customer and the editor with their response, and again all readers should benefit.

The Wrox Support process can only offer support to issues that are directly pertinent to the content of our published

title. Support for questions that fall outside the scope of normal book support, is provided via the community lists of

our http://p2p.wrox.com/ forum.

p2p.wrox.com

For author and peer discussion join the P2P mailing lists. Our unique system provides programmer to

programmer™ contact on mailing lists, forums, and newsgroups, all in addition to our one-to-one e-mail support

system. If you post a query to P2P, you can be confident that it is being examined by the many Wrox authors and

other industry experts who are present on our mailing lists. At p2p.wrox.com you will find a number of different lists

that will help you, not only while you read this book, but also as you develop your own applications. Particularly

appropriate to this book are the beginning_c_sharp and c_sharp (for more advanced discussion) lists in the .NET

category of the web site.

To subscribe to a mailing list just follow these steps:

1. Go to http://p2p.wrox.com/

2. Choose the appropriate category from the left menu bar

3. Click on the mailing list you wish to join

4. Follow the instructions to subscribe and fill in your e-mail address and password

5. Reply to the confirmation e-mail you receive

6.

Tải ngay đi em, còn do dự, trời tối mất!