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

expert c 5.0

609 4,8K 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 609
Dung lượng 22,52 MB

Nội dung

Rahman Shelve in .NET User level: Advanced www.apress.com SOURCE CODE ONLINE BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Expert C# 5.0 Expert C# 5.0 takes your understanding of the C# language to the next level. It close- ly examines familiar elements in forensic detail to reveal how they really work. Key language features that you already know, such as Enums, Strings, and Collections, are teased apart and examined under the twin microscopes of MSIL (Intermediate Language) and the Windbg debugger to show you what’s really going on behind the scenes as your code is compiled and passed to the CLR. Led by an expert programmer, you’ll: • Learn the detailed workings behind common language elements such as Enum, readonly, Anonymous, and Func • Understand how to work with Strings and StringBuilder in the most effective way • Master exception management far beyond the basics • See how components such as LINQ and Async interact with the C# language beneath the surface • Architect better-crafted applications that work in the most efficient and reliable way possible • Gain insight to identify and fix stubborn, hard to diagnose coding faults If you’re already experienced with writing managed applications and want to learn more about how to get the best from the language at an advanced level, then Expert C# 5.0 is the book for you. It offers a deep investigation of C#, which will enable you to become a true master of the language. RELATED www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info iii Contents at a Glance n About the Author xii n About the Technical Reviewer xiii n Acknowledgments xiv n Chapter 1: Reintroducing C#:-A Detailed Look at the Language We All Know 1 n Chapter 2: C# Objects in Memory 85 n Chapter 3: Parameters 109 n Chapter 4: Methods 137 n Chapter 5: Automatic Property Declaration 157 n Chapter 6: Enum 175 n Chapter 7: Delegate 187 n Chapter 8: Event 213 n Chapter 9: Foreach and Iterator 233 n Chapter 10: The String Data Type 255 n Chapter 11: Collections Explained 285 n Chapter 12: Linq in C# 349 n Chapter 13: Exception Management 455 n Chapter 14: Asynchrony 497 n Chapter 15: Diagnostic Tools in .NET 555 n Index 587 www.it-ebooks.info xiv Acknowledgments It has been a long journey writing this book, and I want to thank many people, especially my acquisition editor, Ewan Buckingham, from Apress, who made publication of this book possible. Every person at Apress who was involved with this book did an excellent job, and I thank them all. I would especially like to express my appreciation to my development editor, Jonathan Hassell, as well as James Markham, who gave me many great suggestions and improved the quality of the book. I also thank my copy editor, Mary Bearden, who did a great job editing this book. I also express my thanks to my coordinating editor, Katie Sullivan. Lastly and most importantly, I thank my technical editor, Todd Meister, who did a fabulous job and provided many excellent suggestions. Looking back on this year, when I was writing articles for the codeproject.com, a few members suggested that I should write a book. Especially Sander Rossel, who recommended I get in touch with Apress. Marcelo Oliveira is another member from codeproject.com who inspired me to write this book. My thanks to both Sander and Marcelo. I also give special thanks to my parents for their support and best wishes through this process. I also thank my sister and sister-in-law. Lastly, I am grateful to my wife for her support, passion, and understanding and for letting me work late nights and over weekends. www.it-ebooks.info 1 n n n CHAPTER 1 Reintroducing C#:-A Detailed Look at the Language We All Know This chapter will discuss the basics of the C# language. It begins with an example of a square number generator program to explain the basic structure of a C# program, how the C# compiles a C# program, and then explains Just-in-Time compilation. You will learn about the lexical element of the C# language, different types such as value and reference types, variables, parameters, and statements, and about the interface, enum, and delegate classes. Square Number Using the C# Listing 1-1 shows a simple program that calculates the square of a given number and displays the squared number as output. Listing 1-1. Square Number Program using System; /* importing namespace */ namespace Ch01 /* namespace declaration */ { class Program /* class declaration*/ { static void Main(string[] args) /* method declaration */ { PowerGenerator pg = new PowerGenerator(); pg.ProcessPower(); } /* end of method declaration */ } /* end of class declaration */ public class PowerGenerator { const int limit = 3; /* constant declaration */ const string original = "Original number", www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW 2 square = "Square number"; public void ProcessPower() { Console.WriteLine("{0,16}{1,20}", original, square); /* statement*/ for (int i = 0; i <= limit; ++i) /* iteration statement*/ { Console.Write("{0,10}{1,20}\n", i, Math.Pow(i, 2)); } } } } /* end of namespace declaration */ A C# program consists of statements, and each of these statements executes sequentially. In Listing 1-1, the Pow method from the Math class processes the square of a number, and the Write method from the Console class displays the processed square number on the console as output. When Listing 1-1 is compiled using the C# compiler csc.exe and executes the executable, it will produce the output: Original number Square number 0 0 1 1 2 4 3 9 Listing 1-1 contains a class called a program inside the namespace Ch01. A namespace is used to organize classes, and classes are used to organize a group of function members, which is called a method. A method is a block of statement defined inside curly braces {}, such as {statement list} inside a class, for example: static void Main( string[] args ){……} An int literal 3 and the string literals “Original number” and “Square number” are used in the program to define three variables. In Listing 1-1, the iteration statement for is used to iterate through the processing. A local variable i is declared in the for loop as a loop variable. The following section will explore the compilation process of a C# program. Compilation of a C# Program The C# compiler compiles the C# source code into the module, which is finally converted into the assembly. The assembly contains the Intermediate Language (IL) code along with the metadata information about the assembly. All of this happens in the compile time of the program. Figure 1-1 demonstrates the compilation process of a C# program. www.it-ebooks.info 3 cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW The common language runtime (CLR) works with the assembly. It loads the assembly and converts it into the native code to execute the assembly, as demonstrated in Figure 1-1. When the CLR executes a program, it executes the program method by method, and before it executes any method (unless the method has already been Jitted), the JITTER needs to convert it into the native code. The compiler refers to the Just-in-Time (JIT) compiler of the CLR, which is responsible for compiling the IL code into the native instructions for execution. The CLR retrieves the appropriate metadata information of the method from the assembly, extracts the IL code for the method, and allocates a block of memory onto the Heap, where the JITTER will store the JITTED native code for that method. The following section will explore the Jitting process to convert IL code into the native code. Jitting a C# Program Figure 1-1 shows that in runtime the JIT compiler, which is part of the CLR, compiles the IL code into the native code. Let’s analyze Listing 1-1 to see how the IL code of the method is converted into the native code. 1. Step 1: When the CLR loads the assembly produced from Listing 1-1, the methods of the Program class and PowerGenerator class will not yet be Jitted by the JITTER. In Figure 1-2, you can see that the Main method of the Program class and ProcessPower method of the PowerGenerator class has not yet been JITTED, as shown by its Not JITTED yet status. Sometime later, the JITTER converts the IL code of the Main method into the native code, and the status of the method Figure 1-1. The compilation process of a C# program www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW 4 description table of the Main method shows the JITTED address stored in the Heap. The contents of this address will contain the JITTED native code for the Main method. 2. Step 2: The JITTER still has not generated the native code for the ProcessPower method because the status of the ProcessPower method shows Not JITTED yet as the status and the status of the ProcessPower method shows NONE for JIT status, as described in Figure 1-2. Figure 1-2. Jitting process of the assembly in Listing 1-1 www.it-ebooks.info 5 cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW 3. Step 3: Sometime later, the JITTER converts the IL code of the ProcessPower method into the native code and the native code is stored in the Heap. The method description table of the ProcessPower method in Figure 1-2 shows the address of the native code for the ProcessPower method. The contents of the native code that are stored in the Heap, as shown in Figure 1-2, were extracted using the following commands: !u –n 004c0050 !u –n 004c00e8 n Note: The IL code shown in Figure 1-1 was decompiled using the ildasm.exe. The windbg.exe was used to explore different runtime information while the executable from Listing 1-1 executes. You can explore more detail about the ildasm.exe and windbg.exe tools in Chapter 15. In Figure 1-2, a different debugging command used, which is also discussed in Chapter 15. In addition to the ildasm.exe and windbg.exe tools, the .NET Reflector tool is used to explore the IL/C# code for the assembly. Understanding the C# Language This section explores the C# language. You will learn the syntax and usage of the identifiers, keywords, and literals. You will explore the different types used in C#, such as value type and reference type, how to declare a variable, and how many different types of variables can be used in a program. You will also learn about different types of statements that can be declared in C#, and, finally, you will learn about classes, types of classes, constructors, fields, and methods. Identifiers Identifiers are names used in the application to identify a namespace, class, method, variable, delegate, interface, and so on. Figure 1-3 demonstrates the possible forms of the identifiers. Figure 1-3. Possible forms of the identifier declaration Figure 1-3 demonstrates the possible combination of the characters and digits used to define an identifier. • An identifier is composed of the Unicode characters or it can start with an underscore character or characters (_) along with other characters, such as _ identifier or _iden77tifier, or \u005F\u005FIdentifier (compiled as __Identifier). www.it-ebooks.info cHAPteR 1 n ReintRoducing c#:-A detAiled look At tHe lAnguAge We All knoW 6 • An identifier can start with the at sign (@) as its prefix, such as @int (as used in Listing 1-2), and it is referred to as the verbatim identifier. To use a keyword as an identifier, the @ needs to be the prefix for the keyword. • Unicode escape is used to define an identifier, such as “cl\u0061ss,” when the C# compiler compiles “cl\u0061ss” as a class. Listing 1-2 shows the usage of the identifier in a program. Listing 1-2. Example of the Identifier using System; /* Ch01 is the identifier to name the namespace*/ namespace Ch01 { /* Program is the identifier to name the class */ class Program { /* Main is the identifier to name the method */ static void Main(string[] args) { /* a and _a is the identifier to name the variable */ int a = 10, _a = 20; /* Verbatim identifier - start with an @ prefix */ int @int = 10; Console.WriteLine("{0}\t{1}\t{2}", a,_a, @int); } } } This program will produce the output: 10 20 10 The decompiled IL code (decompiled using the ildasm.exe) of Listing 1-2 shows how the variable names, such as a, _a, and @int, are compiled by the C# compiler: .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 4 .locals init ( [0] int32 a, /* a compiled as a */ [1] int32 _a, /* _a compiled as _a */ [2] int32 int) /* @int compiled as int */ /* Code removed */ } The IL code shows that the variables a and _a are compiled as they are defined in the C# source code, but the @int is compiled as int, where the C# compiler eliminates the @ character from the verbatim identifier. www.it-ebooks.info [...]... the real literal declaration Character Literal A character literal represents a single character and consists of a character in single quotes: 'a character' For example: 'M' 'R' When declaring a character literal that contains a backslash character (\), it must be followed by one of the escape sequence characters, as shown in Table 1-4 Table 1-4 Escape Sequences Escape sequence Character name \’ Single... describes on the above table.*/ charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral charLiteral = = = = = = = = = = = = '\''; '\"'; '\\'; '\0'; '\a'; '\b'; '\f'; '\n'; '\r'; '\t'; '\x4'; '\v'; /* /* /* /* /* /* /* /* /* /* /* /* \ \ \ \ \ \ \ \ \ \ \ \ character character character character character character character... \ \ \ \ \ \ \ \ \ character character character character character character character character character follows follows follows follows follows follows follows follows follows by by by by by by by by by 0 a b f n r t x v */ */ */ */ */ */ */ */ */ /* If you declare a string literal as shows below, the C# compiler * shows compile time error as \ does not follows any escape character */ //stringLiteral=... keywords available for use in C# Table 1-1 Keywords for C# abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public 7 www.it-ebooks.info w readonly... character character character character character character follows follows follows follows follows follows follows follows follows follows follows follows by by by by by by by by by by by by ' " \ 0 a b f n r t x v */ */ */ */ */ */ */ */ */ */ */ */ /* If you declare a character literal as shows below, the C# compiler * shows compile time error as \ does not follows any escape character */ //char... quote \\ Backslash \0 Null \a Alert \b Backspace \f Form feed \n New line \r Carriage return \t Horizontal tab \v Vertical tab For example: 10 www.it-ebooks.info CHAPTER 1 ■ Reintroducing C# :-A Detailed Look at the Language We All Know /* declare a char variable */ char charLiteral; /* assign variety of the escape characters on multiple lines * Each of the escape character will produce respective output... System.Collections; namespace Ch01 { class MainClass { static void Main(string[] args) { ArrayList al = new ArrayList(); al.Add( "C# "); Console.WriteLine(al.Count); Console.WriteLine(al[0]); } } } /* 1 */ /* C# */ This program will produce the output: 1 C# Associative Arrays Arrays can be indexed by strings if they are created by the class Hashtable (discussed in detail in Chapter 11) in the namespace System.Collections,... literal that contains a backslash character in regular string literal, the character must be followed by one of the ', ", \, 0, a, b, f, n, r, t, x, v characters, which is demonstrated in Table 1-4 For example: /* declare a string variable */ string stringLiteral; /* assign variety of the escape characters on multiple lines * Each of the escape character will produce respective output as * describes on... the CLR calls the ConvertAndIncrease method of the converter object, it will create a block of memory to store arguments, local variables, and others, which it refers to as the Stack for that method Figure 1-10 shows the Stack information for the Main method while the CLR executes the ConvertAndIncrease method Figure 1-10 Stack state of the Main method Heap The C# stores objects of the reference type... Literal with \ "; /* Compiler error */ Comments C# language supports comments in the source code in the following forms: • Single line: Single line comment starts with // followed by characters except for the new line character • Multiline: Multiline comment starts with /* and ends with */ In between the /* and */, it contains characters that are treated as comments by the C# compiler For example: . L _00 00: nop L _00 01: ldc.i4 0x16d L _00 06: stloc .0 L _00 07: ldc.i4 0x16e L _00 0c: stloc.1 L _00 0d: ret } } The decompiled IL code shows that the C# eliminates the comments used in the C# . –9,223,372 ,03 6, 854 ,7 75, 808 9,223,372 ,03 6, 854 ,7 75, 807 Table 1-6. Unsigned Integral Size in bits Type Range/Precision 8 byte 0 255 16 ushort 0 65, 5 35 32 Uint 0 4,294,967,2 95 64 ulong 0 18,446,744 ,07 3, 709 ,55 1,6 15 Table. instance void .ctor() cil managed www.it-ebooks.info cHAPteR 1 n ReintRoducing c# :-A detAiled look At tHe lAnguAge We All knoW 14 { .maxstack 8 L _00 00: ldarg .0 L _00 01: call instance void

Ngày đăng: 05/05/2014, 11:23

Xem thêm

TỪ KHÓA LIÊN QUAN

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

TÀI LIỆU LIÊN QUAN