Essential C# 3.0 FOR NET FRAMEWORK 3.5 PHẦN 1 docx

88 1.7K 0
Essential C# 3.0 FOR NET FRAMEWORK 3.5 PHẦN 1 docx

Đ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

Praise for Essential C# 3.0 “In a time when you can search online for any reference material, Essential C# 3.0 is the one book I still bother to carry in my bag Any developer can hit F1 for help with the language syntax; this book, however, arms me with the knowledge to make better design and coding decisions (and the confidence to say so) You know when a book has more than twenty pages of index that it’s got depth covered, and although Essential C# 3.0 has introductory chapters, it progresses effortlessly into the lesser known corners of the language, which makes this book indispensible to any level of C# developer.” —Troy Magennis, C# MVP and creator of HookedOnLINQ.com “If you are new to C#, as I was, Mark’s book is an excellent way to start His approach takes you step by step through the structure and syntax of the language, making it easy to understand how things work I found the code samples extremely helpful and supportive of the concepts being discussed.” —Robert Stokesbary, senior consultant, Option Explicit “This book expands on the concepts introduced in Essential C# 2.0 to include C# 3.0 enhancements One great aspect of this book is that it not only covers the new 3.0 enhancements in great detail, but it also shows where it makes sense to utilize these new features over the existing 2.0 features While I have been programming C# for many years, I find myself referring to this book often and always seem to find something new buried in the pages This is a must-read for both the C# newbie as well as the C# seasoned veteran.” —Michael Stokesbary, senior software engineer, Itron Inc Praise for the First Edition “Essential C# 2.0 pulls off a very difficult task The early chapters are comprehensible by beginning developers, while the later chapters pull no punches and provide the experienced developer with the detailed information they need to make the most of C# 2.0 Starting with the first chapter, Mark has successfully interwoven tidbits of information useful to even the most advanced developer while keeping the book approachable.” —Chris Kinsman, chief architect, Vertafore, Microsoft Regional Director “How refreshing! This book deals with C# thoroughly, rather than skimming over the whole NET framework It is valuable to newcomers and professionals alike.” —Jon Skeet, C# MVP “Essential C# 2.0 is a one-stop shop for an experienced programmer looking to ramp up on one of the hottest languages around today Mark delivers an intelligent and detailed tour of C#, providing newcomers to the language with a solid foundation of skill on which to build their next generation of applications.” —Stephen Toub, technical editor, MSDN Magazine “This book provides complete, up-to-date coverage of all the programming constructs in C# Masterfully organized, it allows beginning programmers to get on board and leads more experienced programmers into the world of structured programming Because of its unwavering focus on the essential programming constructs of C#—such as generics, delegates, and much more—this book is indispensable For programmers who want to solve their day-to-day programming issues using the latest features this modern programming language has to offer, this book is indispensable.” —Narendra Poflee, IT integration specialist, Itron Inc “Essential C# 2.0 is an ideal book for all programmers interested in C# If you are a beginner, you will quickly learn the basics of C# programming and become familiar with the concepts The flow of the text is easy to follow and does a great job of not repeating concepts that have already been covered For the experienced programmer, this book has priceless nuggets embedded within its pages, making it a great read for programmers who are already familiar with C# This will be a book that I will keep next to my computer for years to come.” —Michael Stokesbary, software engineer, Itron Inc Essential C# 3.0 Microsoft NET Development Series John Montgomery, Series Advisor Don Box, Series Advisor Brad Abrams, Series Advisor The award-winning Microsoft NET Development Series was established in 2002 to provide professional developers with the most comprehensive and practical coverage of the latest NET technologies It is supported and developed by the leaders and experts of Microsoft development technologies, including Microsoft architects, MVPs, and leading industry luminaries Books in this series provide a core resource of information and understanding every developer needs to write effective applications Titles in the Series Brad Abrams, NET Framework Standard Library Annotated Reference Volume 1: Base Class Library and Extended Numerics Library, 978-0-321-15489-7 James S Miller and Susann Ragsdale, The Common Language Infrastructure Annotated Standard, 978-0-321-15493-4 Brad Abrams and Tamara Abrams, NET Framework Standard Library Annotated Reference, Volume 2: Networking Library, Reflection Library, and XML Library, 978-0-321-19445-9 Christian Nagel, Enterprise Services with the NET Framework: Developing Distributed Business Solutions with NET Enterprise Services, 978-0-321-24673-8 Chris Anderson, Essential Windows Presentation Foundation (WPF), 978-0-321-37447-9 Bob Beauchemin and Dan Sullivan, A Developer’s Guide to SQL Server 2005, 978-0-321-38218-4 Brian Noyes, Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with NET, 978-0-321-26892-1 Brian Noyes, Smart Client Deployment with ClickOnce: Deploying Windows Forms Applications with ClickOnce, 978-0-321-19769-6 Adam Calderon, Joel Rumerman, Advanced ASP.NET AJAX Server Controls: For NET Framework 3.5, 978-0-321-51444-8 Fritz Onion with Keith Brown, Essential ASP.NET 2.0, 978-0-321-23770-5 Eric Carter and Eric Lippert, Visual Studio Tools for Office: Using C# with Excel, Word, Outlook, and InfoPath, 978-0-321-33488-6 Steve Resnick, Richard Crane, Chris Bowen, Essential Windows Communication Foundation: For NET Framework 3.5, 978-0-321-44006-8 Eric Carter and Eric Lippert, Visual Studio Tools for Office: Using Visual Basic 2005 with Excel, Word, Outlook, and InfoPath, 978-0-321-41175-4 Scott Roberts and Hagen Green, Designing Forms for Microsoft Office InfoPath and Forms Services 2007, 978-0-321-41059-7 Steve Cook, Gareth Jones, Stuart Kent, Alan Cameron Wills, Domain-Specific Development with Visual Studio DSL Tools, 978-0-321-39820-8 Neil Roodyn, eXtreme NET: Introducing eXtreme Programming Techniques to NET Developers, 978-0-321-30363-9 Krzysztof Cwalina and Brad Abrams, Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable NET Libraries, Second Edition, 978-0-321-54561-9 Chris Sells and Michael Weinhardt, Windows Forms 2.0 Programming, 978-0-321-26796-2 Joe Duffy, Concurrent Programming on Windows, 978-0-321-43482-1 Dharma Shukla and Bob Schmidt, Essential Windows Workflow Foundation, 978-0-321-39983-0 Sam Guckenheimer and Juan J Perez, Software Engineering with Microsoft Visual Studio Team System, 978-0-321-27872-2 Guy Smith-Ferrier, NET Internationalization: The Developer’s Guide to Building Global Windows and Web Applications, 978-0-321-34138-9 Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, Peter Golde, The C# Programming Language, Third Edition, 978-0-321-56299-9 Will Stott and James Newkirk, Visual Studio Team System: Better Software Development for Agile Teams, 978-0-321-41850-0 Alex Homer and Dave Sussman, ASP.NET 2.0 Illustrated, 978-0-321-41834-0 Paul Yao and David Durant, NET Compact Framework Programming with C#, 978-0-321-17403-1 Joe Kaplan and Ryan Dunn, The NET Developer’s Guide to Directory Services Programming, 978-0-321-35017-6 Paul Yao and David Durant, NET Compact Framework Programming with Visual Basic NET, 978-0-321-17404-8 Mark Michaelis, Essential C# 3.0: For NET Framework 3.5, 978-0-321-53392-0 For more information go to informit.com/msdotnetseries/ Essential C# 3.0 For NET Framework 3.5 Mark Michaelis Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals The NET logo is either a registered trademark or a trademark of Microsoft Corporation in the United States and/or other countries and is used under license from Microsoft The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests For more information, please contact: U.S Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the United States please contact: International Sales international@pearson.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Michaelis, Mark Essential C# 3.0 : for NET Framework 3.5 / Mark Michaelis p cm Includes index ISBN 978-0-321-53392-0 (pbk : alk paper) C# (Computer program language) Microsoft NET Framework I Title QA76.73.C154M5235 2008 006.7’882—dc22 2008023595 Copyright © 2009 Pearson Education, Inc All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must 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 regarding permissions, write to: Pearson Education, Inc Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax (617) 671 3447 ISBN-13: 978-0-321-53392-0 ISBN-10: 0-321-53392-5 Text printed in the United States on recycled paper at Courier in Stoughton, Massachusetts First printing, August 2008 To my family: Elisabeth, Benjamin, Hanna, and Abigail This page intentionally left blank Contents at a Glance Contents xi Figures xxiii Tables xxv Foreword xxvii Preface xxxi Acknowledgments xliii About the Author xlv Introducing C# Data Types 31 Operators and Control Flow 83 Methods and Parameters 147 Classes 195 Inheritance 261 Interfaces 295 Value Types 321 Well-Formed Types 347 10 Exception Handling 389 11 Generics 405 12 Delegates and Lambda Expressions 445 ix Common Intermediate Language and ILDASM The /text portion is used so that the output appears on the command console rather than in a new window Similarly, the Mono disassembler implementation, which defaults to the command console, is shown in Output 1.9 OUTPUT 1.9: >monodis HelloWorld.exe The stream of output that results by executing these commands is a dump of CIL code included in the HelloWorld.exe program Note that CIL code is significantly easier to understand than machine code For many developers, this may raise a concern because it is easier for programs to be decompiled and algorithms understood without explicitly redistributing the source code As with any program, CLI based or not, the only foolproof way to prevent disassembly is to disallow access to the compiled program altogether (for example, only hosting a program on a web site instead of distributing it out to a user’s machine) However, if decreased accessibility to the source code is all that is required, there are several obfuscators These obfuscators open up the IL code and munge the code so that it does the same thing but in a way that is much more difficult to understand This prevents the casual developer from accessing the code and instead creates assemblies that are much more difficult and tedious to decompile into comprehensible code Unless a program requires a high degree of algorithm security, these obfuscators are generally sufficient ADVANCED TOPIC CIL Output for HelloWorld.exe Listing 1.18 shows the CIL code created by ILDASM Listing 1.18: Sample CIL Output // Metadata version: v2.0.50727 assembly extern mscorlib { publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // z\V.4 27 28 Chapter 1: Introducing C# ver 2:0:0:0 } assembly HelloWorld { custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute:: ctor(int32) = ( 01 00 08 00 00 00 00 00 ) custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ct or() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // T WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows .hash algorithm 0x00008004 ver 0:0:0:0 } module HelloWorld.exe // MVID: {49C96993-E12B-4DD2-A127-34909F7C9A15} imagebase 0x00400000 file alignment 0x00000200 stackreserve 0x00100000 subsystem 0x0003 // WINDOWS_CUI corflags 0x00000001 // ILONLY // Image base: 0x02EA0000 class private auto ansi beforefieldinit HelloWorld extends [mscorlib]System.Object { method private hidebysig static void Main() cil managed { entrypoint // Code size 13 (0xd) maxstack IL_0000: nop IL_0001: ldstr "Hello My name is Inigo Montoya." IL_0006: call void [mscorlib]System.Console::WriteLine(string) IL_000b: nop IL_000c: ret } // end of method HelloWorld::Main method public hidebysig specialname rtspecialname instance void ctor() cil managed { // Code size (0x7) maxstack IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method HelloWorld::.ctor } // end of class HelloWorld Summary The beginning of the listing is the manifest information It includes not only the full name of the disassembled module (HelloWorld.exe), but also all the modules and assemblies it depends on, along with their version information Perhaps the most interesting thing that you can glean from such a listing is how relatively easy it is to follow what the program is doing compared to trying to read and understand machine code (assembler) In the listing, an explicit reference to System.Console.WriteLine() appears There is a lot of peripheral information to the CIL code listing, but if a developer wanted to understand the inner workings of a C# module (or any CLI-based program) without having access to the original source code, it would be relatively easy unless an obfuscator is used In fact, several free tools are available (such as Lutz Roeder’s Reflector for NET) that can decompile from CIL to C# automatically SUMMARY This chapter served as a rudimentary introduction to C# It provided a means of familiarizing you with basic C# syntax Because of C#’s similarity to C++ style languages, much of what I presented here might not have been new material However, C# and managed code have some distinct characteristics, such as compilation down to CIL Although it is not unique, another key characteristic is that C# is entirely object-oriented Even things such as reading and writing data to the console are objectoriented Object orientation is foundational to C#, and you will see this throughout this book The next chapter examines the fundamental data types that are part of the C# language, and discusses how you can use these data types with operands to form expressions 29 This page intentionally left blank Data Types 1’ S HelloWorld program, you got a feel for the C# language, its structure, basic syntax characteristics, and how to write the simplest of programs This chapter continues to discuss the C# basics by investigating the fundamental C# types F ROM CHAPTER Declaring Instantiating Assigning Using Strings as Arrays Explicit Cast Implicit Cast Without Casting Value Types Reference Types Integer Types Arrays Numeric Types Floating-Point Types Decimal Type Literal Values Conversions Data Types Categories of Types More Types Boolean Type Character Type Strings null and void Until now, you have worked with only a few primitive data types, with little explanation In C#, thousands of types exist, and you can combine types to create new types A few types in C#, however, are relatively simple and are considered the building blocks of all other types These types are predefined types or primitives The C# language’s primitive types include eight integer types, two floating-point types, a high-precision type, one 31 Chapter 2: Data Types 32 Boolean type, and a character type This chapter investigates these primitives, looks more closely at the string type, and introduces arrays Fundamental Numeric Types The basic numeric types in C# have keywords associated with them These types include integer types, floating-point types, and a decimal type to store large numbers with a high degree of accuracy Integer Types There are eight C# integer types This variety allows you to select a data type large enough to hold its intended range of values without wasting resources Table 2.1 lists each integer type TABLE 2.1: Integer Typesa a Type Size Range (Inclusive) BCL Name Signed sbyte bits –128 to 127 System.SByte Yes byte bits to 255 System.Byte No short 16 bits –32,768 to 32,767 System.Int16 Yes ushort 16 bits to 65,535 System.UInt16 No int 32 bits –2,147,483,648 to 2,147,483,647 System.Int32 Yes uint 32 bits to 4,294,967,295 System.UInt32 No long 64 bits –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 System.Int64 Yes ulong 64 bits to 18,446,744,073,709,551,615 System.UInt64 No a There was significant discussion among language designers and CLI designers about which types should be in the CLS Ultimately, the decision was made to support only one type, signed or unsigned, per length The C# designers insisted that although signed types for all lengths were acceptable in general, the byte type was an exception because unsigned bytes were more useful and common In fact, it was argued, signed bytes could potentially cause programming problems In the end, the C# team’s perspective won out and the unsigned byte was included in the CLS instead of the signed byte Fundamental Numeric Types Included in Table 2.1 (and in Tables 2.2 and 2.3) is a column for the full name of each type All the fundamental types in C# have a short name and a full name The full name corresponds to the type as it is named in the Base Class Library (BCL) This name is the same across all languages and uniquely identifies the type within an assembly Because of the fundamental nature of primitive types, C# also supplies keywords as short names or abbreviations to the full names of fundamental types From the compiler’s perspective, both names are exactly the same, producing exactly the same code In fact, an examination of the resultant CIL code would provide no indication of which name was used Language Contrast: C++—short Data Type In C/C++, the short data type is an abbreviation for short int In C#, short on its own is the actual data type Floating-Point Types (float, double) Floating-point numbers have varying degrees of precision If you were to read the value of a floating-point number to be 0.1, it could very easily be 0.099999999999999999 or 0.1000000000000000001 or some other number very close to 0.1 Alternatively, a large number such as Avagadro’s number, 6.02E23, could be off by 9.9E9, which is something also exceptionally close to 6.02E23, considering its size By definition, the accuracy of a floating-point number is in proportion to the size of the number it contains Accuracy, therefore, is determined by the number of significant digits, not by a fixed value such as ±0.01 C# supports the two floating-point number types listed in Table 2.2 Binary numbers appear as base 10 (denary) numbers for human readability The number of bits (binary digits) converts to 15 decimal digits, with a remainder that contributes to a sixteenth decimal digit as expressed in Table 2.2 Specifically, numbers between 1.7 * 10307 and less than * 10308 have only 15 significant digits However, numbers ranging from * 10308 to 1.7 * 10308 will have 16 significant digits A similar range of significant digits occurs with the decimal type as well 33 34 Chapter 2: Data Types TABLE 2.2: Floating-Point Types Type Size Range (Inclusive) BCL Name Significant Digits float 32 bits 1.5 ì 10ã45 to 3.4 ì 1038 System.Single double 64 bits 5.0 ì 10ã324 to 1.7 ì 10308 System.Double 15–16 Decimal Type C# contains a numeric type with 128-bit precision (see Table 2.3) This is suitable for large and precise calculations, frequently financial calculations TABLE 2.3: decimal Type Type Size Range (Inclusive) BCL Name Significant Digits decimal 128 bits 1.0 ì 10ã28 to approximately 7.9 ì 1028 System.Decimal 2829 Unlike floating-point numbers, the decimal type maintains exact precision for all denary numbers within its range With the decimal type, therefore, a value of 0.1 is exactly 0.1 However, although the decimal type has greater precision than the floating-point types, it has a smaller range Thus, conversions from floating-point types to the decimal type may result in overflow errors Also, calculations with decimal are slightly slower ADVANCED TOPIC Floating-Point Types and Decimals Dissected Unless they are out of range, decimal numbers represent denary numbers exactly In contrast, the floating-point representation of many denary numbers introduces a rounding error The difference between the decimal type and the C# floating-point types is that the exponent of a decimal type is a denary and the exponent of floating-point types is binary Fundamental Numeric Types The exponent of a decimal is ±N * 10k where • N is a positive integer represented by 96 bits • k is given by -28

Ngày đăng: 12/08/2014, 16:21

Từ khóa liên quan

Mục lục

  • Essential C# 3.0

  • Contents

  • Figures

  • Tables

  • Foreword

  • Preface

  • Acknowledgments

  • About the Author

  • 1 Introducing C#

    • Hello, World

      • Compiling and Running the Application

      • C# Syntax Fundamentals

        • C# Keywords

        • Type Definition

        • Main

        • Whitespace

        • Working with Variables

          • Data Types

          • Declaring a Variable

          • Assigning a Variable

          • Using a Variable

          • Console Input and Output

            • Getting Input from the Console

            • Writing Output to the Console

            • Comments

Tài liệu cùng người dùng

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

Tài liệu liên quan