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

Teach Yourself the C# Language in 21 Days phần 7 pot

81 415 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 81
Dung lượng 773,21 KB

Nội dung

Making Your Programs React with Delegates, Events, and Indexers 461 13 D’s are good! Z Removing event handler D Don’t like ‘a’! X d As you can see by the output, when Line 22 is executed, the Change_D event is no longer active. However, the Change_A event handler continues to work. ANALYSIS If multiple event handlers are assigned to an event, there is no guarantee for which will be executed first. In Listing 13.5, there is no guarantee that Change_A will execute before Change_D. Additionally, event handlers and events can throw exceptions and do all the things other code can do. If an exception is thrown, there is no guarantee that other event handlers will be executed. Caution Summary In today’s lesson, you learned about some of the more complicated topics within C#. You first learned about indexers. Indexers can be used with a class so that you can access the class using index notation. This makes your classes “arraylike.” You then learned about delegates. You learned that delegates are like interfaces: They state a definition for accessing but don’t actually provide the implementation. Delegates set up a format for using methods. You learned that a delegate can be used to dynami- cally call different methods with a single method call. The last part of today’s lesson focused on events. You learned that code can be created to cause an event to happen. More important, you learned that code—event handlers—can be created to react when an event happens. Q&A Q Today’s concepts were hard. How important is it to understand them? A You can do a lot with C# without understanding the concepts presented today; however, there is a lot more that you won’t be able to do. If you plan to program applications for Windows or other graphical environments, you will find that events are critical. And as you learned today, delegates are critical for working with events. Many of the C# editors, such as Visual Studio .NET, will help by automatically creating a lot of the code for you. For example, Visual Studio .NET adds code for many of the standard events. Q In today’s lesson, events were declared in properties. Do they have to be declared in a property? A No. You can declare an event call within a property or a method. Q Multiple event handlers were assigned to an event. Can multiple methods be assigned to a single delegate? A Yes. It is possible to assign more than one method to a single delegate so that mul- tiple methods execute with a single call. This is also called multicasting. Q What is a function pointer? A In languages such as C and C++, there is a construct called a function pointer. A function pointer is used to accomplish the same task as a delegate. A delegate, however, is type-safe and secure. In addition to being used to reference methods, delegates are used by events. 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. You are in your living room and the phone rings. You get up and answer the phone. The ringing of the phone is best associated with which of the following concepts? a. Indexer b. Delegate c. Event d. Event handler e. Exception handler 462 Day 13 Making Your Programs React with Delegates, Events, and Indexers 463 13 2. Your answering the phone is best associated with which of the following concepts: a. Indexer b. Delegate c. Event d. Event handler e. Exception handler 3. What is the point of an indexer? 4. When declaring an indexer, what keyword is used? 5. An indexer definition is similar to which of the following: a. A class definition b. An object definition c. A property definition d. A delegate definition e. An event definition 6. What are the different steps to creating and using an event? 7. What operator is used to add an event handler? 8. What is it called when multiple event handlers are added to an event? 9. Which is true (note—None and Both are possible answers): An event is an instantiation based on a delegate. A delegate is an instantiation based on an event. 10. Where within a class can an event be instantiated? Exercises 1. Add an indexer to the following class. Use the class in a simple program. public class SimpleClass { int[] numbers; public SimpleClass(int size) { numbers = new int[size]; // declare size elements for ( int x = 0; x < size; x++ ) // initialize values to 0. numbers[x] = 0; } } 2. Rewrite Listing 13.1 without using indexers. 3. Modify Listing 13.2 so that you don’t have to declare a doIT object. 4. Write a program using a delegate that sorts an array of integers. You can use Listing 13.2 as a starting point. 5. Add an event handler to the code in Listing 13.5. This event handler should change any lowercase vowels to uppercase. 464 Day 13 DAY 14 WEEK 2 Making Operators Do Your Bidding: Overloading In today’s lesson, you delve deeper into some of the functionality available when working with classes. This includes exploring overloading in much greater detail. You’ve seen method overloading earlier. Today you… • Revisit method and constructor overloading. • Learn about overloading operators. • Discover how to overload unary, binary, relational, and logical operators. • Understand the difference in overloading the logical operators. • Review the individual operators that can and can’t be overloaded. Overloading Functions Revisited On Day 8, “Advanced Method Access,” you learned that you can overload a method mul- tiple times. The key issue with overloading a method is that you must ensure that each time you overload the method, it has a different signature. A signature is determined by the return type and parameters of a method. For example, all of the following are differ- ent signatures: int mymethod( int x, int y ) int mymethod( int x ) int mymethod( long x ) int mymethod( char x, long y, long z ) int mymethod( char x, long y, int z ) On Day 8, you learned that you could overload constructors as well as regular methods. Today you go beyond overloading methods: You learn how to overload a class’s operators. Overloading Operators In addition to overloading constructors and accessors, many object-oriented languages give you the capability to overload operators. C# is no exception: It enables you to over- load many of the mathematical operators—such as addition (+) and subtraction (-)—as well as many of the relational and logical operators. Why would you want to overload these operators? You do not ever have to overload them. Sometimes, however, it can make your program’s code easier to follow and your classes easier to use. The String class is a great example of a class that has an operator that is overloaded. Normally, the addition operator would not work on a class type, but in C#, you can actu- ally add two strings with the addition operator. This addition does what you would expect: It concatenates two strings. For example: “animal” + “ “ + “crackers” results in this string: “animal crackers” To accomplish this, the String class and the string data type overload the addition operator. 466 Day 14 Making Operators Do Your Bidding: Overloading 467 14 You will find that overloading operators can make some of your programs work better as well. Take a look at Listing 14.1. This listing gives you an error when you compile. The error is shown in the listing’s output. This listing is not a great example of using operator overloading; however, it is simple so that you can focus on the concepts instead of trying to under- stand the code in a complex listing. A few of the later listings in today’s les- son are much more practical. Note LISTING 14.1 over1a.cs—A Program with a Problem 1: // over1a.cs - A listing with a problem 2: // 3: 4: using System; 5: 6: public class AChar 7: { 8: private char private_ch; 9: 10: public AChar() { this.ch = ‘ ‘; } 11: public AChar(char val) { this.ch = val; } 12: 13: public char ch 14: { 15: get{ return this.private_ch; } 16: set{ this.private_ch = value; } 17: } 18: } 19: 20: public class myAppClass 21: { 22: 23: public static void Main(String[] args) 24: { 25: AChar aaa = new AChar(‘a’); 26: AChar bbb = new AChar(‘b’); 27: 28: Console.WriteLine(“Original value: {0}, {1}”, aaa.ch, bbb.ch); 29: 30: aaa = aaa + 3; 31: bbb = bbb - 1; 32: 33: Console.WriteLine(“Final values: {0}, {1}”, aaa.ch, bbb.ch); 34: } 35: } The following errors are generated when you try to compile this listing: over1a.cs(30,13): error CS0019: Operator ‘+’ cannot be applied to ➥operands of type ‘AChar’ and ‘int’ over1a.cs(31,13): error CS0019: Operator ‘-’ cannot be applied to ➥operands of type ‘AChar’ and ‘int’ This listing is easy to follow. A class is created named AChar. This class is not practical, but its simplicity makes it easy to use as an illustration for overloading. The AChar class stores a single character. The class has two constructors in Lines 10–11. The first is called when no arguments are provided; it sets the character value stored in a newly instantiated object to a space. The second constructor takes a single character that is placed in a new object’s private character variable. The class uses an accessor in Lines 13–17 to do the actual setting of the character value. The AChar class is used in the myAppClass class. In Lines 25–26, two AChar objects are cre- ated. aaa will contain a, and bbb will contain b. In Line 33, these values are printed. In Line 30, the value of 3 is added to aaa. What would you expect would happen when you add 3 to an AChar object? Note that this is not a type char object or even a numeric object. It is an AChar object. This listing is trying to add 3 to the actual object, not to a member of the object. The result, as you can see by the compiler output, is an error. In Line 31, the value of 1 is subtracted from an AChar object. An error is produced because you can’t add or subtract from an object like this. If Lines 30–31 had worked, Line 33 would have printed their values. You can make the addition work by manipulating an object’s members instead of the class itself. Changing Lines 30–31 to the following allows the listing to compile: aaa.ch = (char) (aaa.ch + 3); bbb.ch = (char) (bbb.ch - 1); Although this works, it is not the ultimate solution. There is too much casting, and the code is not as simple as it could be. Another solution to make this clear is to add meth- ods to the class that allow addition and subtraction—or other types of operations—to be done with the class’s objects. Listing 14.2 presents this approach. 468 Day 14 OUTPUT ANALYSIS Making Operators Do Your Bidding: Overloading 469 14 LISTING 14.2 over1b.cs—Operators for Mathematical Functions 1: // over1b.cs - Using methods for mathematic operations 2: // 3: 4: using System; 5: 6: public class AChar 7: { 8: private char private_ch; 9: 10: public AChar() { this.ch = ‘ ‘; } 11: public AChar(char val) { this.ch = val; } 12: 13: public char ch 14: { 15: get{ return this.private_ch; } 16: set{ this.private_ch = value; } 17: } 18: 19: static public AChar Add ( AChar orig, int val ) 20: { 21: AChar result = new AChar(); 22: result.ch = (char)(orig.ch + val); 23: return result; 24: } 25: static public AChar Subtract ( AChar orig, int val ) 26: { 27: AChar result = new AChar(); 28: result.ch = (char)(orig.ch - val); 29: return result; 30: } 31: } 32: 33: public class myAppClass 34: { 35: public static void Main(String[] args) 36: { 37: AChar aaa = new AChar(‘a’); 38: AChar bbb = new AChar(‘b’); 39: 40: Console.WriteLine(“Original value: {0}, {1}”, aaa.ch, bbb.ch); 41: 42: aaa = AChar.Add( aaa, 3 ); 43: bbb = AChar.Subtract( bbb, 1 ); 44: 45: Console.WriteLine(“Final values: {0}, {1}”, aaa.ch, bbb.ch); 46: } 47: } [...]... however This is exactly what Line 70 does More important, by overloading the ToString method (Lines 83–85), you gain the capability to “print” the class When you display the class as shown in these lines, the ToString method is automatically called Overloading the Logical Operators Overloading the equality and inequality logical operators takes more effort than overloading the other relational operators... // 1 - 13 public int CardValue { get { int retval; if( (int) retval else if( (int) retval else retval this.val >= 10) = 10; this.val == 1 ) = 11; = (int) this.val; return retval; } } Week in Review LISTING WR2.1 continued CH 10 CH 11 CH 11 CH 7 CH 7 CH 7 CH 8 CH 8 CH 8 CH 8 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70 : 71 : 72 : 73 : 74 : 75 : 76 : 77 : 78 : 79 : 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90:... stated that you should use the Equals method for comparing classes This is exactly what the overloaded == method is doing: It calls the Equals method and returns the value from it The != method does the same thing in Lines 45–52, except that the value is changed by using the ! operator In the Main method of the myAppClass class, using the == and != operators is as easy as using the other overloaded operators... override string ToString() { Making Operators Do Your Bidding: Overloading LISTING 14.6 481 continued 70 : return( this.amount.ToString() ); 71 : } 72 : } 73 : 74 : public class myAppClass 75 : { 76 : public static void Main(String[] args) 77 : { 78 : Salary mySalary = new Salary(24000); 79 : Salary yourSalary = new Salary(24000); 80: Salary PresSalary = new Salary(200000); 81: 82: Console.WriteLine(“Original values:... salary Most of the code in this listing was analyzed before the listing You’ll find the overloaded Equals method in Lines 20–30 The overloaded GetHashCode method is in Lines 32–35 For fun, you can remove one of these two methods and try to compile the listing; you will see that your listing will generate errors without them ANALYSIS 14 486 Day 14 Line 27 starts the method for overloading the == operator... to the previous listing Instead of overloading the - and + operators, this listing overloads the and ++ operators When overloaded, these operators can be used with objects of the given class You see this in Lines 43, 44, 48, and 49 The other unary operators can be overloaded in the same way ANALYSIS Making Operators Do Your Bidding: Overloading 479 Overloading the Relational and Logical Operators The. .. ToString() { Making Operators Do Your Bidding: Overloading LISTING 14 .7 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70 : 71 : 72 : 73 : 74 : 75 : 76 : 77 : 78 : 79 : 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 485 continued return( this.amount.ToString() ); } } public class myAppClass { public static void Main(String[] args) { string tmpstring; Salary mySalary = new Salary(24000); Salary yourSalary =... Review 495 LISTING WR2.1 continued CH 8 CH 7 CH 7 CH 7 CH 7 CH 8 CH 11 CH 11 156: 1 57: 158: 159: 160: 161: 162: 163: 164: 165: 166: 1 67: 168: 169: 170 : 171 : 172 : 173 : 174 : 175 : 176 : 177 : 178 : 179 : 180: 181: 182: 183: 184: 185: 186: 1 87: 188: 189: 190: 191: 192: 193: 194: 195: 196: 1 97: 198: 199: 200: 201: 202: 203: //CLEAR HANDS pTotal = 0; cTotal = 0; pCardCtr = 0; for ( int ctr = 0; ctr < 10; ctr++)... types You can easily compare one salary to another, as done in Lines 88, 90, and 95 Another part of this listing that needs to be covered is not related to operator overloading In Lines 68 71 , the ToString() method is overridden by using the override keyword The ToString method was inherited automatically from the base class, Object Remember from the days on inheritance that all classes derive from Object... specified In the myAppClass class, the AChar.Add method is called to increment aaa by 3, which results in an a becoming a d The Add method returns a new AChar class that can overwrite the original In this way, a number can be added to the class and returned to overwrite the original value The Subtract method works in the same manner, except that the ch value is decremented by the given number This listing . value. The AChar class is used in the myAppClass class. In Lines 25–26, two AChar objects are cre- ated. aaa will contain a, and bbb will contain b. In Line 33, these values are printed. In Line. This includes the basic binary mathematics operators, most of the unary operators, the relational operators, and the logical operators. Overloading the Basic Binary Mathematical Operators The binary. 48, and 49. The other unary operators can be overloaded in the same way. 478 Day 14 LISTING 14.5 continued OUTPUT ANALYSIS Making Operators Do Your Bidding: Overloading 479 14 Overloading the Relational

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

TỪ KHÓA LIÊN QUAN