Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 81 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
81
Dung lượng
808,6 KB
Nội dung
Enter the contractor’s name: Matt Hebron Enter ‘c’ for Contractor, ‘e’ for Employee then press ENTER: Z =========================== Contractor: Amber Jones Employee: Bejamin Andrews Employee: Jacob Sams Contractor: Matt Hebron Person: Not an Employee or Contractor =========================== This is a long listing compared to what you have been seeing. This listing only partially implements everything it could do. One of today’s exercises will have you expand on this listing. The purpose of the listing is to enable you to enter people into the program. This is set up to take five people; however, you could have the user enter people until a set value is entered. The program prompts you to enter either an ‘e’ or a ‘c’ to indicate whether the person is an employee or a contractor. Based on what you enter, it gives you a custom prompt to enter the person’s name. You could also ask for additional information; how- ever, this hasn’t been done here. If the user enters a value other than an ‘e’ or ‘c’, the program fills the person’s name with an error message. You most likely would want different logic than this. You should also notice that although the program prompts for lowercase ‘e’ or ‘c’, uppercase letters also work. Most of the code should be familiar to you. The classes defined in this listing have been scaled back to a minimum amount of code. Lines 26 and 45 were left in the listing as comments. You will be asked to use these data members in one of today’s exercises. In Line 63, you see the beginning of the Main method for this application. Lines 69–102 contain a do while that loops for each person being entered. Lines 71–75 contain a nested do while, which prompts the user to enter either an ‘e’ or a ‘c’ to indicate the type of person being entered. Using a ReadLine in Line 74, the user’s answer is obtained. Users who press Enter are prompted again. When a value is entered, if else statements are used to determine what processing should occur. In Line 77, only the first character of the text entered by the user is reviewed. The first character is stored in the 0 position of the string—buffer[0]. 380 Day 10 ANALYSIS Reusing Existing Code with Inheritance 381 10 If the value entered starts with a c, Lines 79–84 are executed. In Line 79, the user is asked to enter a contractor’s name. The Write method is used instead of WriteLine so that the reader can enter the name on the same line as the prompt. If you use WriteLine, a car- riage return, line feed occurs and the user must enter the name on the next line. In Line 80, the name is retrieved using the ReadLine method. In Line 82, a contractor object is created named contr. This object is initialized with the name obtained from the ReadLine method. In Line 83, this new object is then assigned to the myCompany array. Because myCompany is an array of Person,thecontr variable is assigned to the array as a Person type. Because Person is a base type for Contractor, you can do this, as you learned earlier today. In Lines 106–123, the program again loops through the myCompany array. This time, each element in the array is printed to the screen. In Line 110, the element in the array is checked to see whether it is an Employee. If it is, a custom output for employees is dis- played. If not, the if statement in Line 115 is checked to see whether it is a Contractor. If so, a message is printed. If not, a message is printed indicating that it is just a Person. Line 124 prints a dashed line to help format the output. The program then ends. Using is and as enables you to store different data types in a single array, provided that they work with the same base class. Because all objects inherit from Object, you will always have a base class that works in this manner. This listing illustrates key features of object-oriented programming. Summary Today’s lesson was long; however, it is also one of the most important. In today’s lesson, you learned about inheritance. You learned how to create base classes and how to derive from them. Additionally, you learned different keywords—such as abstract, virtual, and protected—that can impact what you can do with a base class and a derived class. You also learned how to seal a class to prevent inheritance. Later in the day, you learned how to work with objects using types other than their own. You learned that an object can be assigned or accessed using a type in any of its base classes. Additionally, you learned that you can cast an object to a different type using the as keyword. The as keyword operates similarly to a cast operation, except that, with an error, a null is set instead of an exception being thrown. You also learned that you can use the is keyword to evaluate what type an object is. Q&A Q Can you inherit from a base class written in a language other than C#? A Yes. One of the features of .NET is that classes can inherit from classes written in other languages. This means that your C# classes can be derived from classes of other languages. Additionally, programmers of other languages can use your C# classes as base classes. Q Today’s lesson presented an example of assigning a derived class to a base class in Listing 10.3. Can you assign a base class to a derived class? A Yes, if you are careful. In Listing 10.3, a base class was assigned an object from a derived class. Although only the items available via the base class constructs can be used, the other portions of the derived class are not lost. It is possible to assign a derived class the value of a base class if you know that the base class was assigned an object of the derived class’s type. This assignment is done with a cast. In Listing 10.3, it would not be an error to do the following after Line 55: Employee you = (Employee) Brad; This is valid because Brad was assigned with an Employee object. If Brad was not an Employee object, this line of code would throw an invalid cast exception, (System.InvalidCastException). Q What is data or method hiding? A Data or method hiding occurs when you create a method or data element in a derived class that replaces a base method or data element. This occurs when the new keyword is used to create the new class. Q What are upcasting and downcasting? A Downcasting is forcing an object to a type of a class derived from it. Upcasting is casting an object to a data type of a base class. Upcasting is considered safe to do and is an implicit operation in C#. Downcasting is considered unsafe. To downcast, you must explicitly force the conversion. Q What is composition? Is it an object-oriented term? A Many people confuse inheritance with composition, but they are different. With composition, one object is used within another object. Figure 10.4 is a composition of many circles. This is different from the sphere in the previous example. The sphere is not composed of a circle; it is an extension of the circle. To summarize the difference between composition and inheritance, composition occurs when one class (object) has another within it. Inheritance occurs when one class (object) is an expansion of another. 382 Day 10 Reusing Existing Code with Inheritance 383 10 Workshop The Workshop provides quiz questions to help you solidify your understanding of the material covered and exercises to provide you with experience in using what you’ve learned. Try to understand the quiz and exercise answers before continuing to tomorrow’s lesson. Answers are provided on the CD. Quiz 1. In C#, how many classes can be used to inherit from to create a single new class? 2. Which of the following is the same as a base class? a. Parent class b. Derived class c. Child class 3. What access modifier is used to protect data from being used outside a single class? What access modifier will enable data to be used by only a base class and classes derived from the base class? 4. How is a base class’s method hidden? FIGURE 10.4 A snowman made of circles. 5. What keyword can be used in a base class to ensure that a derived class creates its own version of a method? 6. What keyword is used to prevent a class from being inherited? 7. Name two methods that all classes have. 8. What class is the ultimate base class from which all other classes are derived? 9. What does boxing do? 10. What is the as keyword used for? Exercises 1. Write a method header for declaring a constructor for the ABC class that receives two arguments, ARG1 and ARG2, that are both integers. This constructor should call a base constructor and pass it to the ARG2 integer. This should be done in the method header: public ABC( int ARG1, int ARG2) : base( ARG2 ) { } 2. Modify the following class to prevent it from being used as a base class: 1: class aLetter 2: { 3: private static char A_ch; 4: 5: public char ch 6: { 7: get { return A_ch; } 8: set { A_ch = value; } 9: } 10: 11: static aLetter() 12: { 13: A_ch = ‘X’; 14: } 15: } 3. Bug Buster: There is a problem with the following code. Which lines are in error? // Bug Buster // Class definition for Person would need to be included here class NameApp { public static void Main() { 384 Day 10 Reusing Existing Code with Inheritance 385 10 Person me = new Person(); Object you = new Object(); me = you; System.Console.WriteLine(“Type: {0}”, me.GetType()); } } 4. On Your Own: Modify Listing 10.9 to set the value of hireyear or company. Print these values, when appropriate, with the output that is displayed. DAY 11 WEEK 2 Formatting and Retrieving Information The last few days, you covered a lot of hard-core C# development topics that will be critical to your development of professional-level applications. Before trudging into additional hard-core topics, today’s lesson offers some diversion. Today you… • Review the difference between input and output. • Discover more of the formatting options available when displaying infor- mation in the console. • Get a detailed explanation of reading information from the console. • Learn how to parse information read from the console. • Format and work with strings. • Examine the concept of streams. • Manipulate basic file information. Understanding Console Input and Output You’ve seen the terms input and output. In today’s lesson, you step back and focus on providing output in a much better presentation format. Additionally, you learn a little more about getting information from your users via input from the console. You also learn a lot more about strings in today’s lessons. The Write and WriteLine meth- ods actually do string formatting behind the scenes. In today’s lesson, you learn how to format these strings using other methods. Formatting Information When displaying information, it is often easiest to convert the information to a string first. As you have already seen, the Write and WriteLine methods for the Console class use strings for displaying output. Additionally, the .NET Framework provides a number of methods and specifiers that can be used with strings. A specifier indicates that informa- tion is to be formatted. Format specifiers can be used with any string. The following sections cover a number of format specifiers. This includes specifiers for working with each of the following: • Standard numeric formats • Currency • Exponential numbers • Exponentials • Custom numeric formats • Dates and times • Enumerators You can use these format specifiers in several ways. The most obvious way is to use the specifiers with the Write and WriteLine methods to provide additional formatting. You also can use the format specifiers when calling the ToString method. As you learned in yesterday’s lesson, the Object class contains a ToString method. As you know, because all classes are derived from Object, all objects have access to a ToString method. In 388 Day 11 Today’s lesson contains much more reference information than most of the other days in this book. You should find this reference material valuable. Note [...]... hold the string that the listing will be building In Line 11, a string is created named buffer that will be used to get information from the user This information is obtained in Lines 15, 24, and 33 using the ReadLine method in Console The first value obtained is the first name This is appended into the name StringBuilder object Because name was empty, this is placed at the beginning The length of the. .. value in Line 22 The character value is then appended to the string Input After the entry of characters is completed, Line 27 prints the full value of the Input string All the characters were stored, in addition to the carriage returns and line feeds Note For Windows and Web applications, you obtain information differently On Days 16 20, you learn more about obtaining data on these platforms Using the. .. this listing so that a blank line ends the input The answer is provided on the CDROM, “Answers.” Using the Convert Class The key to using information read in by the Read and ReadLine methods is not in just getting the data, but in converting it to the format that you want to use This can be meshing the text in a string to a different string value or converting it to a different data type The System... formatting and displaying information In addition to producing output, you need to have more flexibility in obtaining input—information entered into your program You have seen the Read and ReadLine methods of the Console class used in this book The following sections provide more information on obtaining input from Console and converting it to a more usable format Note Starting on Day 16, “Creating Windows... This listing initializes and prints two variables In Lines 9–10, two float variables are created One is a very small decimal value, and the other is a simple number In Lines 12–13, these values are written to the console The first placeholder in each of these lines displays the floating-point value as a fixed-point number using the F specifier The second placeholder prints the same variable in the general... resulting full name is displayed in Line 41 Lines 44–48 display some general information In Line 45, the value of the StringBuilder name object is printed In Line 46, you see the current capacity that the name object can hold In Line 47, you see the maximum value that this can be extended to In Line 48, the current length of the value is stored in name Getting Information from the Console So far, today’s... If information is read, it is appended to the Input string (Line 17) Because line-feed information is removed from the string, Line 18 adds a line feed back to the string being created so that the final output displayed in Line 21 matches what the user entered ANALYSIS How could you prevent Ctrl+Z from being used? Suppose that you wanted to end this listing by entering a blank line Exercise 3 at the. .. because the dash is included in the format for the negative sign, and there are five zeros If the value is equal to 0, a 0 will be printed In the second example, text is included with the formatting of the numbers This is also done in the third example The difference is that, in the second example, zero placeholders are also included so that the actual numbers will print This is not the case with the third... of a string to a new string or character array EndsWith Determines whether the end of the value stored in the string is equal to a string value If they are equal, true is returned; otherwise, false is returned Equals Compares two strings to determine whether they contain the same value Returns true if the two values are equal; otherwise, returns false IndexOf Returns the index (location) of the first... or string Returns -1 if the value is not found Insert Inserts a value into a string This is done by returning a new string LastIndexOf Returns the index (location) of the last match for a character or a string Returns -1 if the value is not found Length Returns the length of the value stored in the string The length is equal to the number of characters contained 11 4 06 Day 11 TABLE 11.5 continued Method . of code. Lines 26 and 45 were left in the listing as comments. You will be asked to use these data members in one of today’s exercises. In Line 63 , you see the beginning of the Main method. learned earlier today. In Lines 1 06 123, the program again loops through the myCompany array. This time, each element in the array is printed to the screen. In Line 110, the element in the array is checked. line. In Line 80, the name is retrieved using the ReadLine method. In Line 82, a contractor object is created named contr. This object is initialized with the name obtained from the ReadLine