Professional C# Third Edition phần 10 pot

137 279 0
Professional C# Third Edition phần 10 pot

Đ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

The for Loop Now let’s discuss the for loop, introduced in the previous code snippet. What we have here is the C# equivalent of this Visual Basic code: Dim I As Integer For I = 1 To 3 listBox1.Items.Add “Details of the Employee” Next The idea of the For loop in Visual Basic is that you start off by initializing a variable, called the loop con- trol variable, and each time you go round the loop, you add something to the loop control variable until it exceeds a final value. This is quite useful, but gives you almost no flexibility in how the loop works. Although you can change the value of the increment, or even make the increment negative, by using the Step facility, the loop always works by counting, and the test of whether the loop exits is always whether the variable has reached a preset minimum or maximum value. In C# the for loop generalizes this concept. The basic idea of the for loop in C# is this: At the beginning of the loop you do something, at each step of the loop you do something else in order to move to the next iteration, and in order to determine when to exit from the loop, you perform some test. The follow- ing table provides a comparison between the Visual Basic and C# versions of this loop. Loop Visual Basic C# At start of loop Initialize the loop control variable. Do something. To test whether to exit loop Check whether the loop control Test some condition. variable has reached a certain value. At end of each iteration Increment the loop control variable. Do something. This might look a bit vague, but it does give you a lot of flexibility! For example, in C#, instead of adding a quantity to the loop control variable at each iteration, you might multiply its value by some number. Or instead of adding on a fixed amount you might add some number that you’ve read in from a file and which changes with each iteration. The test doesn’t have to be a test of the value of the loop control variable. It could be a test of whether you have reached the end of the file. What this adds up to is that, by a suitable choice of the start action, test, and action at the end of each iteration, the for loop can effectively perform the same task as any of the other loops in Visual Basic ( For, For Each, Do, and While). Alternatively the loop can work in some manner for which there is no simple equivalent in Visual Basic. The C# for loop really gives you complete freedom to control the loop in whatever manner is appropriate for the task at hand. We should point out, however, that C# also does support foreach, do, and while loops. Now let’s look at the syntax. The C# version of the previous for loop looks like this: for (int I=0 ; I<3 ; I++) { this.listBox1.Items.Add(Employees[I].Name); this.listBox1.Items.Add(Employees[I].ToString()); this.listBox1.Items.Add(“”); } 1220 Appendix B 557599 AppB_BC02.qxd 4/28/04 10:49 AM Page 1220 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com As you can see, the for statement itself takes three different items inside its parentheses. These items are separated by semicolons: ❑ The first item is the action that is performed right at the start of the loop in order to initialize the loop. In this case we declare and initialize the loop control variable. ❑ The next item is the condition that will be evaluated to determine whether the loop should exit. In this case our condition is that I must be less than 3. The loop continues as long as this condi- tion is true and exits as soon as the condition evaluates to false. The condition will be evalu- ated at the beginning of each iteration, so that if it turns out to be false right at the start, the statement inside the loop does not get executed at all. ❑ In the third item is the statement that is executed at the end of each iteration of the loop. Visual Basic loops always work by incrementing some number. Even though the syntax looks unfamiliar, once you’ve familiarized yourself with it, you can use the for loop in very powerful ways. For example, if you want to display all the integer powers of 2 that are less than 4000 in a list box, you can write this: for (int I = 2 ; I<4000 ; I*=2) listBox1.Items.Add(I.ToString()); You can achieve the same result in Visual Basic, but it wouldn’t be as easy; for this particular example, you might want to opt for a while loop in Visual Basic. Other C# Features We have now completed examining the code samples. The remainder of his appendix will briefly exam- ine a couple of features of C# that you need to be aware of when making the transition from Visual Basic to C#, and which we haven’t yet discussed; in particular some of the C# concepts relating to data types and operators. Data Types As we have indicated, the data types available in C# do differ in detail from those available in Visual Basic. Furthermore, all C# data types have features that you would normally associate with an object. For example, every type, even simple types such as int and float, supports the calling of methods. (Incidentally, this feature does not cause any loss of performance.) Although the types available in C# are slightly different from Visual Basic types, most of the types that you are familiar with in Visual Basic do have equivalents in C#. For example, the Visual Basic Double type translates to double in C#; The C# equivalent of the Date type is the.NET base class, DateTime, which implements a huge number of methods and properties to allow you to extract or set the date using different formats. One exception, however, is Variant, for which there is no equivalent in C#. The Variant type is a very generic type, which to some extent exists only in order to support scripting languages that are not aware of any other data types. The philosophy of C#, however, is that the language is strongly typed. The idea is that if, at each point in the program, you have to indicate the data type you are referring to, at least one 1221 C# for Visual Basic 6 Developers 557599 AppB_BC02.qxd 4/28/04 10:49 AM Page 1221 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com major source of runtime bugs is eliminated. Because of this, a Variant type isn’t really appropriate to C#. However, there are still some situations in which you do need to refer to a variable without indicating what type that variable is, and for those cases C# does have the object type. C#’s object is analogous to Object in Visual Basic. However, Object specifically refers to a COM object, and therefore can only be used to refer to objects, which in Visual Basic terms means to reference data types. For example, you can- not use an object reference to refer to an Integer or to a Single type. In C#, by contrast, an object0 method can be used to refer to any .NET data type, and since all data types are .NET data types, this means that you can legitimately convert anything to an object, including int, float, and all the prede- fined data types. To this extent, object in C# does perform a similar role to Variant in Visual Basic. Value and reference types In Visual Basic there is a sharp distinction between value types and reference types. Value types include most of the predefined data types: Integer, Single, Double, and even Variant (though strictly speak- ing Variant can also contain a reference). Reference types are any object, including class modules that you define and ActiveX objects. As you will have noticed through the samples in this appendix, C# also makes the distinction between value and reference types. However, C# is more flexibility to the extent that it permits you, when defining a class, to specify that that class should be a value type. You do this by declaring the class as something called a struct. As far as C# is concerned, a struct is basically a special type of class that is represented as a value rather than a reference. The overhead involved in instantiat- ing structs and destroying them when we are finished with them is less than that involved when instan- tiating and destroying classes. However, C# does restrict the features supported by structs. In particular, you cannot derive classes or other structs from structs. The reasoning here is that structs are intended to be used for really lightweight, simple objects, for which inheritance isn’t really appropriate. In fact, all the predefined classes in C#, such as int, long, float, and double are actually .NET structs, which is why we can call methods such as ToString() against them. The data type string, however, is a refer- ence type and so is really just a class. Operators We need to say a couple of words about operators in C#, because they do differ somewhat from Visual Basic operators, and this can catch you off guard if you are used to the Visual Basic way of working. In Visual Basic there are really two types of operator: ❑ The assignment operator, =, which assigns values to variables ❑ All the other operators, such as +, -,*, and /, which each return some value There is an important distinction here in that none of the operators, apart from =, has any effect in terms of modifying any value. On the other hand, = assigns a value but does not return anything. There are no operators that do both. In C#, this categorization simply does not exist. The rule in C# is that all operators return a value, and some operators also assign some value to a variable. We have already seen an example of this when we examined the addition assignment operator, +=: int A=5, B=15; A+=B; // performs an arithmetic operation AND assigns result (20) to A 1222 Appendix B 557599 AppB_BC02.qxd 4/28/04 10:49 AM Page 1222 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com += returns a value as well as assigning the value. It returns the new value that has been assigned. Because of this we could actually write: int A=5, B=15; int C = (A+=B); This will have the results that both A and C will be assigned the value 20. The assignment operator, =, also returns a value. It returns the value that has been assigned to the variable on the left side of the expression. This means that you can write code like this: C = (A = B); This code sets A equal to whatever value is in B, and then sets C to this same value too. You can also write this statement more simply as: C = A = B; A common use of this type of syntax is to evaluate some condition inside an if statement, and simulta- neously set a variable of type bool (the C# equivalent of Boolean in Visual Basic) to the result of this condition, so we can reuse this value later: // assume X and Y are some other variables that have been initialized bool B; if ( B = (X==Y) ) DoSomething(); This code looks daunting at first sight, but it is quite logical. Let’s break it down. The first thing the com- puter will do is check the condition X==Y. Depending on whether X and Y contain the same data, this will either return true or false and this value will be assigned to the variable B. However, since the assignment operator also returns the value that has just been assigned to it, the complete expression B = (X==Y) will also return this same value (true or false). This return value will then be used by the if clause to determine whether to execute the conditional DoSomething() statement. The result of this code is that the condition X==Y is tested to determine whether the conditional statements should be exe- cuted, and at the same time we have stored the results of this test in the variable B. The ternary operator We do not have space in this appendix to go over all the various operators that are available in C#. They are detailed in Chapter 2 of this book. However, we will mention the ternary operator (also known as the conditional operator) because it has a very unusual syntax. The ternary operator is formed from the two symbols ? and :. It takes three parameters and is actually equivalent to an IIf statement in Visual Basic. It is used syntactically like this: // B, X and Y are some variables or expressions. B is a Boolean. B ? X : Y The way it works is that the first expression (the one before the ? symbol) is evaluated. If it evaluates to true, then the result of the second expression is returned, but if it evaluates to false then the result of 1223 C# for Visual Basic 6 Developers 557599 AppB_BC02.qxd 4/28/04 10:49 AM Page 1223 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com the third expression is returned instead. This provides an extremely compact syntax for conditionally setting the value of variable. For example, we can write: string animal = (legs==8) ? “octopus” : “dog”; which yields the same result as: string animal; if (legs==8) animal=”octopus”; else animal=”dog”; With the Visual Basic Iif function, this can be achieved with: strAnimal = IIf(intLegs = 8, “octopus”, “dog”) Summary In this appendix, we have presented a brief introduction to C# through the eyes of a Visual basic program- mer. We have found quite a few differences in syntax. In general, C# syntax allows most statements to be expressed in a more compact way. We have also found many similarities between the languages; for exam- ple in their use of classes (or class modules in VB), value and reference types, and many of the syntactical structures. However, we have also seen how C# supports many powerful features, particularly those related to inheritance and classic object-oriented programming that are not available in Visual Basic. Appendix A of this book contains an introduction to object-oriented programming, which is key to any serious C# development effort. Making the transfer from Visual Basic to C# does require a fair bit of learning, but is well worth it, because the methodology of C# allows you to code not only any application that you could have devel- oped in Visual Basic, but also a wide range of other applications that would be too difficult, if not impos- sible, to design in a good, well-structured, and maintainable manner in Visual Basic. With C# you also get the added bonus of the .NET runtime and all its associated benefits. 1224 Appendix B 557599 AppB_BC02.qxd 4/28/04 10:49 AM Page 1224 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com C# for Java Developers At first glance, Java developers might not get particularly excited about C# code, because of the syntactical similarity between it and Java. However, look more closely and you will see subtle yet significant differences: features such as operator overloading, indexers, delegates, properties, and type safe enumerations in C#. This appendix focuses on applying much-loved Java programming tricks to C# code, highlighting features that C# adds to the picture, and pointing out tricks that C# cannot do (although you won’t find many of those). Of course, we assume that as a reader of this appendix, you are a professional Java developer; so we will not go into too much detail when describing the Java language. Starting Out Let’s take a look at the infamous “Hello World!” example in Java: public class Hello { public static void main(String args []) { System.out.println(“Hello world! This is Java Code!”); } } The corresponding C# code for this is as follows: using System; public class Hello { public static void Main(string [] args) { System.Console.WriteLine(“Hello world! This is C# code!”); } } 557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1225 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The first thing that you’ll notice is that the two appear to be very similar syntactically and both lan- guages are case-sensitive. C# is object-oriented like Java, and all functionality must be placed inside a class (declared by the keyword class). These classes can contain methods, constructors, and fields just as Java classes can, and a C# class can inherit methods and fields from another class or interface as in Java. The implementation of classes and methods is similar in both languages. C# code blocks are enclosed by braces just as in Java. The entry point to a C# application is the static Main() method, as required by the compiler (similar to Java but note the uppercase “M”). Also note that only one class in the application can have a Main() method. Similar to Java, the static keyword allows for the method to be called without creating an instance of the class first. For the Main() method in C# you have the choice of either a void or int return type. void specifies that the method does not return a value and int specifies that it returns an integer type. The using keyword in C# corresponds to the import keyword in Java. Therefore, in the C# code above, we are essentially importing the C# equivalent of a class package called System. In C#, a class package is called a namespace, and we will look more closely at these in the next section. Note that although we have written it with a lowercase s here, in C# the string type can also be written with a capital S as String. You will also notice that the array rank specifier ( []) has been shifted from in front of the args variable in the Java example, to between the string type and args variable in the C# sample. In fact, this specifier can occur before or after the variable in Java. However, in C#, the array rank specifier must appear before the variable name because an array is actually a type of its own indi- cated by type []. We’ll discuss arrays in more depth a bit later. Finally, as you might expect, the names of methods tend to differ between the languages. For example, in Java we would use System.out.println() to display text in the command console. The equivalent to this method in C# is System.Console.WriteLine(). Compiling and Running C# Code In Chapter 2, we noted that like Java code, C# source code is compiled in two stages: first to Intermediate Language (IL), and then to native code. To run the previous C# code, you need to save it with an appropriate filename (for example, HelloWorld) and file extension .cs, and then compile it to IL using the csc command: csc HelloWorld.cs The next step is to compile the IL to native code and run the example. To do this, just type the name of the file, without the extension (as we would with Java code): HelloWorld Hello world! This is C# code! Namespaces While Java classes reside in logical divisions referred to as packages, C# (and other managed) classes are grouped together into namespaces. Packages and namespaces differ significantly in their implementation. A Java class that you want to make part of the com.samples package, for example, must have package com.samples; as the first line of code in the file. This is, of course, excluding any comments. Any code 1226 Appendix C 557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1226 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com within that file automatically becomes a part of the specified package. Also, a Java package name is asso- ciated with the folder containing the class file in that they must have the same name. The com.samples package must therefore be in class files that exist in the com/samples folder. Let’s take a look at some examples of how packages work in Java: package java2csharp.javasamples; public class Hello { public static void main(String args []) { System.out.println(“Hello world! This is Java Code!”); } } The following list provides examples of how the previous code could be referenced or executed. This list assumes that the class file has been made available to the JRE: ❑ From the command line: java java2csharp.javasamples.Hello ❑ As a direct reference in the code: public class Referencer { java2csharp.javasamples.Hello myHello = new java2csharp.samples.Hello(); ❑ By utilizing the import directive one could omit fully qualified package names, so Referencer could also be written as: import java2csharp.javasamples.*; public class Referencer { Hello myHello = new Hello(); } Wrapping a class in a namespace is achieved in C# by using the namespace keyword with an identifier, and enveloping the target class in brackets. Here is an example: namespace java2csharp.csharpsamples { using System; public class Hello { public static void Main(string [] args) { System.Console.WriteLine(“Hello world! This is C# code!”); } } } As you can see, we delimit layers of namespaces using the . operator, as in Java. Note that C# does not require an asterisk (*) needed in C#—applying the using directive implicitly imports all elements of the specified namespace. You will also have noticed the major difference from Java here: the use of name- space parentheses in which we place classes associated with the namespace. The advantage of using the parentheses like this is that we then disassociate package names from directory structures: feasibly we 1227 C# for Java Developers 557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1227 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com could place a file containing this namespace anywhere within the directory as long as the CLR recog- nizes it. Therefore, it also enables us to call the file containing these classes anything we wish (it doesn’t have to be the same name as the class as in Java); we can have more than one public class defined per file; and we can split the classes defined in this namespace into different files in different parts of the directory structure, as long as the namespace declaration appears in each of the files. We can also introduce multiple namespaces in the same file with no restriction. We could, for example, add the definition of a new class and place it in a new namespace in the same file and still not be outside the bounds of the language: namespace java2csharp.csharpsamples { using System; public class Hello { public static void Main(string [] args) { System.Console.WriteLine(“Hello world! This is C# code!”); } } } namespace java2csharp.morecsharpsamples { using System; public class AnotherHello { public static void Main(string [] args) { System.Console.WriteLine(“Hello again! This is more C# code!”); } } } As we pointed out in the previous section, classes from a particular namespace can be imported into another namespace with the using keyword. We can see that we import classes from the System name- space (the top level .NET Base Class namespace) into both namespaces above. We can also import classes from other namespaces directly into our classes by referring to the imported class using its full name (namespace included), in a similar way to using direct referencing of classes in Java code. Namespaces may also be defined within other namespaces. This type of flexibility is impossible in Java without having to create a subdirectory. We could change the previous example so that the AnotherHello class is in the java2csharp.csharpsamples.hellosamples namespace: namespace java2csharp.csharpsamples { namespace hellosamples { using System; public class AnotherHello { public static void Main(string [] args) 1228 Appendix C 557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1228 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com { System.Console.WriteLine(“Hello again! This is more C# code!”); } } } } Java classes are part of a package; all classes created are part of the default package. C# mimics this func- tionality. Even if you do not declare one, a default namespace is created for you. It is present in every file and available for use in named namespaces. Just as in Java you cannot change package information, in C# namespaces cannot be modified either. Packages can span multiple files in the same folder; name- spaces can span multiple files in any number of folders, and even multiple assemblies (the name given to code libraries in .NET), as discussed in Chapter 13. Note that the default accessibility for types inside a namespace is internal. You must specify types as public if you want them available without full qualification; however, we strongly advise against this practice. No other access modifiers are allowed. In Java, internal package types may also be marked as final or abstract or not marked at all (this default access makes them available only to consumers inside the package). Access modifiers are discussed later in this appendix. One final feature of namespaces not available to Java packages is that they may be given a using alias. using aliases make it very easy to qualify an identifier to a namespace or class. The syntax is simple. Suppose you had a namespace Very.Very.Long.NameSpace.Name. You could define and use a using alias (here VVLNN) for the namespace as follows: using VVLNN = Very.Very.Long.Namespace.Name; Declaring Variables C# follows a similar scheme of variable declaration to Java, where the declaration consists of a datatype keyword and followed by the name of the variable to hold that datatype. For example, to declare an integer ( int) variable called myInt, we would use the following code: int myInt; Identifiers are the names we give to classes, objects, class members, and variables. Raw keywords, dis- cussed in the next section, can neither be Java nor C# identifiers; however, in C# you can use keywords as variable names by prefixing the name with @. Note that this exception is only with keywords and does not allow the breaking of any other rules. Although identifiers may have letters and numbers, the first letter of the identifier in both C# and Java must not be a number. Here are some valid and invalid examples of variable declaration: int 7x; //invalid, number cannot start identifier int x7; //valid, number may be part of identifier int x; //valid int x$; //invalid, no symbols allowed int @class; //valid, prefix @ allows it to be used as an identifier int @7k; //invalid, prefix @ only works for keywords 1229 C# for Java Developers 557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1229 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... C while the corresponding names in the C# examples do not Also, Hungarian notation is often used for variable names in the C++ samples only Terminology You should be aware that a couple of language constructs have a different terminology in C# from that in C++ Member variables in C++ are known as fields in C# while functions in C++ are known as methods in C# In C#, the term function has a more general... parameter, or as an out parameter This is illustrated by the following code: public static void Main(string[] args) { int a = 10; Console.WriteLine(a); AddOne(a); Console.WriteLine(a); } public static void AddOne(int a) { a++; } This produces the following output in both C# and Java: 10 10 Because a is passed by value, the value that is passed is not tied to the value a in Main() Consequently, incrementing... called Although we cannot override a method in C# unless the method was originally declared as virtual, C# also introduces a new concept, method hiding This allows developers to redefine super-class members in the child class and hide the base class implementation even if the base member is not declared virtual C# uses the new modifier to accomplish this 1248 C# for Java Developers Simpo PDF Merge and... C# namespaces provide a much more flexible way of grouping related classes C# filenames are not bound to the classes within them as they are in Java, nor are namespace names bound to folders as package names are in Java C# also provides a rich set of built-in value types, including type-safe enumerations, structures, and the built-in primitives that offer a robust alternative to Java’s primitives C#. .. override keywords, and C# provides properties as an alternative to get() and set() methods as a way to access safely internal fields 1252 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com C# for C++ Developers This appendix is intended for developers who are already familiar with C++ and want to see what the differences are between C++ and C# We will survey the C# language, noting... Conventions for This Appendix Note that in this appendix we adopt an additional convention when displaying code; C# code will always be displayed with gray shading: // this is C# code class MyClass : MyBaseClass { If we want to highlight any new or important C# code, it will be displayed in bold: // this is C# code class MyClass : MyBaseClass // we’ve already seen this bit { int X; // this is interesting However,... and the relationship between the two do not differ much between Java and C# You will also find that interfaces, and how they are used, are not very different in the two languages We will look at classes and class inheritance in C# in more depth later in this document Strings can also be used the same way in either C# or Java C# also introduces a new type of reference type called a delegate Delegates... and Split Unregistered Version - http://www.simpopdf.com Java developers will immediately spot that C# operators are very similar to Java’s However, there are a few significant differences To determine whether an object belongs to a given class or any of the parent classes Java uses the instanceof operator The C# equivalent of instanceof is the is operator It returns true if the runtime type of the... statement for for (int i = 0; i . enumerations in C#. This appendix focuses on applying much-loved Java programming tricks to C# code, highlighting features that C# adds to the picture, and pointing out tricks that C# cannot do. [] 1237 C# for Java Developers 557599 AppC_BC03.qxd 4/28/04 10: 49 AM Page 1237 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Java developers will immediately spot that C#. the result of 1223 C# for Visual Basic 6 Developers 557599 AppB_BC02.qxd 4/28/04 10: 49 AM Page 1223 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com the third expression

Ngày đăng: 13/08/2014, 15:21

Mục lục

  • The Common Language Runtime

    • Advantages of Managed Code

    • A Closer Look at Intermediate Language

      • Support for Object Orientation and Interfaces

      • Distinct Value and Reference Types

      • Error Handling with Exceptions

      • Chapter 2: C# Basics

        • Before We Start

        • Our First C# Program

          • The Code

          • Compiling and Running the Program

          • Predefined Data Types

            • Value Types and Reference Types

            • The Main() Method

              • Multiple Main() Methods

              • Passing Arguments to Main()

              • More on Compiling C# Files

              • Using Comments

                • Internal Comments Within the Source Files

                • The C# Preprocessor Directives

                  • #define and #undef

                  • #if, #elif, #else, and #endif

                  • C# Programming Guidelines

                    • Rules for Identifiers

                    • Chapter 3: Objects and Types

                      • Classes and Structs

                      • Structs

                        • Structs Are Value Types

                        • Chapter 4: Inheritance

                          • Types of Inheritance

                            • Implementation Versus Interface Inheritance

                            • Calling Base Versions of Functions

                            • Abstract Classes and Functions

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

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

Tài liệu liên quan