1420 Professional C# 2012 and .NET 4.5

 0  0  1588  2019-03-15 19:05:38 Laporkan dokumen yang dilanggar

www.it-ebooks.info

  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. The fact that an organization or Web site is referred toin this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make.

CHAPTER 2 Core C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 CHAPTER 3 Objects and Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 CHAPTER 4 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 CHAPTER 5 Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 CHAPTER 6 Arrays and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 CHAPTER 7 Operators and Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 CHAPTER 8 Delegates, Lambdas, and Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 CHAPTER 9 Strings and Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209 CHAPTER 10 Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 CHAPTER 11 Language Integrated Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 CHAPTER 12 Dynamic Language Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313 CHAPTER 13 Asynchronous Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 CHAPTER 14 Memory Management and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 CHAPTER 15 Refl ection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 CHAPTER 16 Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 ⊲ PART II VISUAL STUDIO CHAPTER 17 Visual Studio 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417 CHAPTER 18 Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467 ⊲ PART III FOUNDATION CHAPTER 19 Assemblies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487 0 Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 1 Tasks, Threads, and Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 Continued

  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. The fact that an organization or Web site is referred toin this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make.

ABOUT THE AUTHORS

  Christian speaks at international conferences such as TechEd, Basta!, and TechDays, and he founded INETA Europe to support . MORGAN SKINNER began his computing career at a young age on the Sinclair ZX80 at school, where he was underwhelmed by some code a teacher had written and so began programming in assembly language.

ABOUT THE TECHNICAL EDITORS

  DAVID FRANSON has been a professional in the fi eld of networking, programming, and 2D and 3D com- 2D Artwork and 3D Modeling for Game Artists, The Dark puter graphics since 1990. He is the author of Side of Game Texturing, and Game Character Design Complete.

DON REAMEY

MITCHEL SELLERS

  402Nested try Blocks 402User-Defi ned Exception Classes 404 Catching the User-Defi ned Exceptions 405 Throwing the User-Defi ned Exceptions 407Defi ning the User-Defi ned Exception Classes 410 Caller Information411 Summary 413xxiii CONTENTS PART II: VISUAL STUDIO CHAPTER 17: VISUAL STUDIO 2012 417 Working with Visual Studio 2012 417 Project File Changes420 Visual Studio Editions420 Visual Studio Settings 421Creating a Project 421Multi-Targeting the . NET is designed to provide an environment within which you can develop almost any application to run on Windows, whereasC# is a programming language designed specifi cally to work with the .

THE SIGNIFICANCE OF .NET AND C#

  Microsoft could not go on forever extending the same develop- ment tools and languages, always making them more and more complex to satisfy the confl icting demandsof keeping up with the newest hardware and maintaining backward compatibility with what was around when Windows fi rst became popular in the early 1990s. Microsoft has extended C++ and made substantial changes to Visual Basic to turn it into a more powerful language to enable code written in eitherof these languages to target the .

ADVANTAGES OF .NET

  For Visual Basic 6 and earlier versions, the main strength of the language was that it was simple to under- stand and made many programming tasks easy, largely hiding the details of the Windows API and the COM lii INTRODUCTION component infrastructure from the developer. Microsoft has gotten around this by adding yet more Microsoft-specifi c keywords to C++ andby completely revamping Visual Basic to the current Visual Basic 2012, a language that retains some of the basic VB syntax but that is so different in design from the original VB that it can be considered, for all prac-tical purposes, a new language.

WHAT YOU NEED TO WRITE AND RUN C# CODE

WHAT THIS BOOK COVERS

  NOTE Notes indicate notes, tips, hints, tricks, or and asides to the current discussion.lv INTRODUCTION As for styles in the text: ➤ We highlight new terms and important words when we introduce them.➤ We show keyboard strokes like this: Ctrl+A.➤ We show fi lenames, URLs, and code within the text like so: persistence.properties.➤ We present code in two different ways: We use a monofont type with no highlighting for most code examples. When at the site, simply locate the book’s title (either by using theSearch box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

P2P.WROX.COM

  The forums offer a subscription feature to e-mail you topics of interest of your lvi INTRODUCTION choosing when new posts are made to the forums. At http://p2p.wrox.com you can fi nd a number of different forums to help you not only as you read this book, but also as you develop your own applications.

2. Read the terms of use and click Agree

  If you want to have new messages from a particular forum e-mailed to you, click theSubscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, read the P2P FAQs for answers to questions about how the forum software works as well as many common questions specifi c to P2P and Wrox books.

CHAPTER 2: Core C# ⊲ CHAPTER 3: Objects and Types ⊲ CHAPTER 4: Inheritance ⊲ CHAPTER 5: Generics ⊲ CHAPTER 6: Arrays and Tuples ⊲ CHAPTER 7: Operators and Casts ⊲ CHAPTER 8: Delegates, Lambdas, and Events ⊲ CHAPTER 9: Strings and Regular Expressions ⊲ CHAPTER 10: Collections ⊲ CHAPTER 11: Language Integrated Query ⊲ CHAPTER 12: Dynamic Language Extensions ⊲ CHAPTER 13: Asynchronous Programming ⊲ CHAPTER 14: Memory Management and Pointers ⊲ CHAPTER 15: Refl ection ⊲ CHAPTER 16: Errors and Exceptions

  ➤ Compiling and running code that targets . NET➤ Advantages of Microsoft Intermediate Language (MSIL)➤ Value and reference types➤ Data typing➤ Understanding error handling and attributes➤ Assemblies, .

THE RELATIONSHIP OF C# TO .NET

  This book emphasizes that the C# language must be considered in parallel with the . The architecture and methodologies of C# refl ect the underlying methodologies of .

2. In many cases, specifi c language features of C# actually depend on features of .NET or of the .NET base classes

  ➤ It is a language based on the modern object-oriented design methodology, and when designing itMicrosoft learned from the experience of all the other similar languages that have been around since object-oriented principles came to prominence 20 years ago. NET but not by C#, and you mightbe surprised to learn that some features of the C# language are not supported by .

THE COMMON LANGUAGE RUNTIME

  NETFramework, you can simply add the following line to the beginning of your code: #using <mscorlib.dll> You can also pass the fl ag /clr to the compiler, which then assumes that you want to compile to managed code and will hence emit IL instead of native machine code. For example, even if code runs under theadministrator account, you can use code-based security to indicate that the code should still not be permitted to perform certain types of operations that the administrator account would normally be allowed to do, suchas read or write to environment variables, read or write to the registry, or access the .

APPLICATION DOMAIN:

  This is a signifi cant break from the old COM way to do things, in which the GUIDs of the components and interfaces had to be obtained from the registry, and in some cases, the details of themethods and properties exposed would need to be read from a type library.getting out of synchronization, which would prevent other software from using the component successfully. Although Chapter 3 is nominally dedicated to the subject of base classes, after you have completed the coverage of the syntax of the C# language, most of the rest of this book shows you how to use variousclasses within the .

CREATING .NET APPLICATIONS USING C#

  More often, however, you can use C# to create applications that use many of the technologies associated with . As this is a C# book, there are many chapters showing you how to use this language to build the latest in webapplications.

Chapter 39 , “Core ASP.NET” covers the foundation of ASP.NET ASP.NET Web Forms To make web page construction easy, Visual Studio 2012 supplies Web Forms. Web pages can be built

  NET Web Forms provide a rich functionality with controls that do not create only simple HTML code, but with controls that do input validation using both JavaScript and server-side validation logic, grids, datasources to access the database, offer Ajax features for dynamically rendering just parts of the page on the client and much more. You can also fi ndWCF-based technologies such as WCF Data Services and Message Queuing with WCF in Chapter 44,“WCF Data Services” and Chapter 47, “Message Queuing.” Windows Workfl ow Foundation The Windows Workfl ow Foundation (WF) was introduced with the release of the .

THE ROLE OF C# IN THE .NET ENTERPRISE ARCHITECTURE

  After a database schema has been established for a new project, C# presents an excellent medium for implementing a layer of data access objects, each of which could provide insertion, updates, and deletionaccess to a different database table. You learned about the characteristics of IL, particularly its strong data typing and object orientation, and how these characteristics infl uence the languages that target .

FUNDAMENTAL C#

  This chapter gives you a good start in that direction by providing a basic understanding of the fundamentals of C#programming, which is built on in subsequent chapters. By the end of this chapter, you will know enoughC# to write simple programs (though without using inheritance or other object-oriented features, which are covered in later chapters).

YOUR FIRST C# PROGRAM

  However, because the aim of Part I is to teach the C# language, we are going to keep things simple and avoid relying on Visual Studio 2011until Chapter 17, “Visual Studio 2011.” Instead, we present the code as simple fi les that you can type in using any text editor and compile from the command line. After it has been declared, you can assign a value to the variable using the assignment operator, =: i = 10; You can also declare the variable and initialize its value at the same time: int i = 10; If you declare and initialize more than one variable in a single statement, all the variables will be of the same data type: int x = 10, y =20; // x and y are both ints To declare variables of different types, you need to use separate statements.

CHAPTER 2 CORE C# This code simply prints out the numbers from 0 to 9, and then back again from 9 to 0, using two for loops. The important thing to note is that you declare the variable i twice in this code, within the same method. You can do this because i is declared in two separate loops, so each i variable is local to its own loop. Here’s another example:

  WriteLine(j);return; }} } This code will compile even though you have two variables named j in scope within the Main() method: the j that was defi ned at the class level, and doesn’t go out of scope until the class is destroyed (when theMain() method terminates and the program ends); and the j defi ned in Main(). In the previous example, you are accessing a staticfi eld (you’ll learn what this means in the next section) from a static method, so you can’t use an instance of the class; you just use the name of the class itself: Predefi ned Data Types 31❘ ..public static void Main() {int j = 30; Console.

PREDEFINED DATA TYPES

  If a variable is a reference, it is possible to indicate that it does not refer to any object by setting its value to null: y = null; If a reference is set to null, then clearly it is not possible to call any nonstatic member functions or fi elds against it; doing so would cause an exception to be thrown at runtime. To specify which of the other integer types the value should take, you can append one of the following characters to the number: uint ui = 1234U; long l = 1234L;ulong ul = 1234UL; You can also use lowercase u and l, although the latter could be confused with the integer 1 (one).

ESCAPE SEQUENCE CHARACTER

  For example, in Chapter 7, “Operators and Casts,” you will see how you can use the object type to box a value object on the stack to move it to the heap; object references are also useful in refl ection, when codemust manipulate objects whose specifi c types are unknown. WriteLine("s2 is now " + s2);return 0; }} The output from this is as follows: s1 is a string s2 is a strings1 is now another string s2 is now a string Changing the value of s1 has no effect on s2, contrary to what you’d expect with a reference type!

FLOW CONTROL

  This section looks at the real nuts and bolts of the language: the statements that allow you to control the fl ow of your program rather than execute every line of code in the order it appears in the program. The compiler enforces this restriction by fl agging everycase clause that is not equipped with a break statement as an error: Control cannot fall through from one case label ('case 2:') to another Although it is true that fall-through behavior is desirable in a limited number of situations, in the vast majority of cases it is unintended and results in a logical error that’s hard to spot.

THE MAIN() METHOD

  Although it is common to specify the public modifi er explicitly, because by defi nition the method must be called from outside the program, it doesn’t actually matter what accessibility level you assign to the entry-point method — it will run even if you mark the method as private. However, you can explicitly tell the compiler which of these methods to use as the entry point for the program by using the /main switch, together with the full name (including namespace) of the class to whichthe Main() method belongs: csc DoubleMain.cs /main:Wrox.

MORE ON COMPILING C# FILES

OPTION OUTPUT

  /t:exe A console application (the default)/t:library A class library with a manifest/t:module A component without a manifest If you want a nonexecutable fi le (such as a DLL) to be loadable by the . If the /out option isn’t specifi ed, the compiler bases the name of the output fi le on the name of theinput C# fi le, adding an extension according to the target type (for example, exe for a Windows or console application, or dll for a class library).

CONSOLE I/O

  Each The result of the preceding is as follows: 940 Console I/O❘ 51 marker contains a zero-based index for the number of the parameter in the following list. WriteLine("{0} plus {1} equals {2}", i, j, i + j); The preceding code displays the following: 10 plus 20 equals 30 You can also specify a width for the value, and justify the text within that width, using positive values for right justifi cation and negative values for left justifi cation.

STRING DESCRIPTION

  WriteLine("{0:#.00}", d); This displays as .23 because the # symbol is ignored if there is no character in that place, and zeros are either replaced by the character in that position if there is one or printed as a zero. */ Everything in a single-line comment, from the // to the end of the line, is ignored by the compiler, and everything from an opening /* to the next */ in a multiline comment combination is ignored.

TAG DESCRIPTION

  (Syntax is verifi ed by the compiler.)<summary> Provides a short summary of a type or member<typeparam> Used in the comment of a generic type to describe a type parameter<typeparamref> The name of the type parameter<value> Describes a property To see how this works, add some XML comments to the MathLibrary.cs fi le from the previous “More onCompiling C# Files” section. To get the compiler to generate the XML documentation for an assembly, you specify the /doc option when you compile, together with the name of the fi le you want to be created: csc /t:library /doc:MathLibrary.xml MathLibrary.cs The compiler will throw an error if the XML comments do not result in a well-formed XML document.

THE C# PREPROCESSOR DIRECTIVES

  It is also possible to nest #if blocks: #define ENTERPRISE #define W2K// further on in the file #if ENTERPRISE// do something #if W2K// some code that is only relevant to enterprise // edition running on W2K#endif #elif PROFESSIONAL// do something else #else// code for the leaner version #endif CHAPTER 2❘ NOTE Unlike the situation in C++, using #if is not the only way to compile codeconditionally. Because of this, it’s almost always a good idea to create a top-level namespace with the name of your company and then nest successive namespaces that narrow down the technology, group, or departmentyou are working in or the name of the package for which your classes are intended.

CREATING AND USING CLASSES

  However,we assume that you are already familiar with the underlying principles of using classes — for example, that you know what a constructor or a property is. This chapteris largely confi ned to applying those principles in C# code.

CLASSES AND STRUCTS

  An int, for instance, is passed by value to a method, and any changes that the method makes to the value of that int do not change the value CHAPTER 3❘ of the original int object. To defi ne a property in C#, use the following syntax: public string SomeProperty {get {return "This is the property value."; }set {// do whatever needs to be done to set the property.} } The get accessor takes no parameters and must return the same type as the declared property.

CHAPTER 3 OBJECTS AND TYPES Access Modifi ers for Properties C# does allow the set and get accessors to have differing access modifi ers. This would allow a

  In the following example,because a one-parameter constructor is defi ned, the compiler assumes that this is the only constructor you want to be available, so it will not implicitly supply any others: public class MyNumber {private int number; public MyNumber(int number){ this.number = number;} } This code also illustrates typical use of the this keyword to distinguish member fi elds from parameters of the same name. This is useful in two situations: ➤ If your class serves only as a container for some static members or properties, and therefore should never be instantiated ➤ If you want the class to only ever be instantiated by calling a static member function (this is the so-called “class factory” approach to object instantiation) Static Constructors One novel feature of C# is that it is also possible to write a static no-parameter constructor for a class.

ANONYMOUS TYPES

  As mentioned earlier in this chapter, the only thing you need to change in the code to defi ne a type as a struct instead of a class is to replace the keyword class with struct: struct Dimensions {public double Length; public double Width;} Defi ning functions for structs is also exactly the same as defi ning them for classes. Note, however, that when passing a struct as a parameter to a method, you can avoid this performance loss bypassing it as a ref parameter — in this case, only the address in memory of the struct will be passed in, which is just as fast as passing in a class.

WEAK REFERENCES

  For example, if you have a class called MyClass() and you createa reference to objects based on that class and call the variable myClassVariable as follows, as long as myClassVariable is in scope there is a strong reference to the MyClass object: MyClass myClassVariable = new MyClass(); Partial Classes❘ 83 This means that the garbage collector cannot clean up the memory used by the MyClass object. A weak reference allows the object to be created and used, but if the garbage collector happens to run(garbage collection is discussed in Chapter 14), it will collect the object and free up the memory.

PARTIAL CLASSES

  However, in situations in which multiple developers need access to the sameclass, or, more likely, a code generator of some type is generating part of a class, having the class in multiple fi les can be benefi cial. If any of the following keywords are used in describing the class, the same must apply to all partials of the same type: ➤ public ➤ private ➤ protected ➤ internal ➤ abstract ➤ sealed ➤ new ➤ generic constraints Nested partials are allowed as long as the partial keyword precedes the class keyword in the nested type.

STATIC CLASSES

  By using the static keyword, the compiler can verify that instance membersare never accidentally added to the class. The syntax for a static class looks like this: static class StaticUtilities {public static void HelperMethod() {} } An object of type StaticUtilities is not needed to call the HelperMethod().

THE OBJECT CLASS

  Object.)The practical signifi cance of this is that, besides the methods, properties, and so on that you defi ne, you also have access to a number of public and protected member methods that have been defi ned for the Objectclass. Some fairly strict requirements exist for how you implement your overload,which you learn about when you examine dictionaries in Chapter 10, “Collections.” ➤ Equals() (both versions) and ReferenceEquals() — As you’ll note by the existence of three different methods aimed at comparing the equality of objects, the .

EXTENSION METHODS

  If you have the source for the class, then inheritance, which is covered in Chapter 4, is a great way to add functionality to your objects. You have also seen that C# adds some newfeatures not present in the OOP model of some other languages — for example, static constructors provide a means of initializing static fi elds, whereas structs enable you to defi ne types that do not require the useof the managed heap, which could result in performance gains.

Dokumen baru
Aktifitas terbaru
Penulis
Tags

1381 Professional C 4 0 And Net

652 Professional Asp Net 4 In C And Vb

1426 Professional Visual Basic 2012 And Net 4 5 Programming

Network Programming Net With C Sharp And Vb Net

Asp Net C Professional Values And Ethics Eternal Crest Professional And Classy Edteacher Professional Learning And Development

1420 Professional C# 2012 and .NET 4.5

Gratis

Feedback