Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
173
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 7: Strings, Arrays, and Collections

59

 

 

 

! Modify the Application class

1.In the Application class's Main method, create an instance of

WordCounter named wc.

2.Create two variables of type Int64 named NumWords and NumChars.

3.Call the wc object’s CountStats method to assign the word and character counts to NumWord and NumChars respectively.

4.Output to the console the test string WordCounter.testString.

5.Output to the console a two-column header labeled Words and Chars. Use a tab to separate the columns.

6.Output to the console the number of words, and format this output to occupy five characters, followed by a tab and the number of characters.

! Test the WordCount application

Build and run the application. You should see output that is similar to the following:

For string

Hello world

 

hello here

i am where are you hello you

Words

Chars

 

11

41

 

60

Module 7: Strings, Arrays, and Collections

Exercise 2

Sorting Words by Number of Occurrences

In this exercise, you will create a nested class that implements the

IComparable interface and whose CompareTo method will result in a

SortedList that is ordered on the basis of the number of occurrences of a word.

!Modify the WordCount class to sort words by occurrences

1.Add a nested class named WordOccurrence that inherits from

IComparable.

2.Add a private member of type int named occurrences.

3.Add a private member of type String named word.

4.Add a constructor that takes two parameters. The first parameter is of type int, and the second parameter is of type String. The constructor assigns the first value to occurrences and the second value to word.

5.Add a public method CompareTo that takes an Object parameter and returns an int.

The code should follow the CompareTo design pattern and return a value that results in a sort of words that is ordered by the occurrences of each word in ascending order. Less frequently occurring words should be followed by more frequently occurring words.

In the case in which the number of occurrences of the instance and the Object parameter are the same, the sort should be alphabetical by using the

String.Compare method.

Tip For an example of implementing the CompareTo method, see Demonstration: Sorting and Enumerating an Array in this module.

6.Add two public read-only properties named Occurrences and Word that return the fields occurrences and word respectively. End the nested class definition.

7.Back in the WordCounter class itself, add a public method named

GetWordsByOccurrenceEnumerator that returns an object of type IDictionaryEnumerator. Implement GetWordsByOccurrenceEnumerator as follows:

a.Create a new SortedList named sl.

b.Iterate through the alphabetically-sorted list named wordCounter by using an enumerator that is obtained by calling the

GetWordsAlphabeticallyEnumerator method.

i.For each alphabetical list entry, create a new object of type WordOccurence that is initialized with the alphabetically sorted list entry’s Value and Key.

ii.Add to sl a new entry whose key field is the new WordOccurence object and whose value field is set to null.

c.Return an enumerator of sl of type IDictionaryEnumerator.

Module 7: Strings, Arrays, and Collections

61

 

 

 

! Modify the Application class

1.Output the words to be sorted alphabetically by adding code to the Application class’s Main method to:

a.Obtain an IDictionaryEnumerator object named de by calling the wc object’s GetWordsAlphabeticallyEnumerator method.

b.Display a message to inform the user that the output that is generated will display word usage sorted alphabetically. Also inform the user of the number of unique words.

c.Iterate over the collection and output each entry’s value and key, formatting them so that the value is displayed in the first column and the key is displayed in the second column.

2.Output the words sorted by occurrence by adding code to:

a.Assign to de an IDictionaryEnumerator object by calling the wc object’s GetWordsByOccurrenceEnumerator method.

b.Display a message to inform the user that the output that is generated will display word usage sorted by occurrence. Also inform the user of the number of unique words.

c.Iterate over the collection. For each entry, obtain the key field’s WordCounter.WordOccurrence object and output to the console the

Occurrences property of the WordCounter.WordOccurrence object in the first column and the object’s Word property in the second column.

62

Module 7: Strings, Arrays, and Collections

!Test the WordCount application

Build and run the application. You should see output that is similar to the following:

For string

Hello world

 

hello here

i

am where are you hello you

Words

Chars

 

11

 

41

 

Word usage

sorted

alphabetically (9 unique words)

1:"am"

1:"are"

2:"hello"

1:"Hello"

1:"here"

1:"i"

1:"where"

1:"world"

2:"you"

Word usage sorted by occurrence (9 unique words)

1:am

1:are

1:Hello

1:here

1:i

1:where

1:world

2:hello

2:you

Module 7: Strings, Arrays, and Collections

63

 

 

 

Review

Topic Objective

To reinforce module objectives by reviewing key points.

Lead-in

The review questions cover some of the key concepts taught in the module.

!Strings

!Terminology – Collections

!.NET Framework Arrays

!.NET Framework Collections

*****************************ILLEGAL FOR NON-TRAINER USE******************************

1.Enter the code to read an integer from the console and assign it to a variable named aNumber.

int MyInt = int.Parse(Console.ReadLine());

2.What class should you use to improve performance when you want to perform repeated modifications to a string?

System.Text.StringBuilder

3.Name and briefly describe the interfaces implemented by System.Array.

ICloneable: Supports cloning, which creates a new instance of a class with the same value as an existing instance.

IList: Represents a collection of objects that can be individually indexed.

ICollection: Defines size, enumerators, and synchronization methods for all collections.

IEnumerable: Exposes the enumerator, which supports a simple iteration over a collection.

4.What does it mean to say that an enumerator is required to be safe?

The enumerator must have a fixed view of the items in a collection that remains the same, even if the collection is modified.

64Module 7: Strings, Arrays, and Collections

5.Create an array that contains the integers 1, 2, and 3. Then use the C# foreach statement to iterate over the array and output the numbers to the console.

int[ ] numbers = {1, 2, 3}; foreach (int i in numbers) {

System.Console.WriteLine("Number: {0}", i);

}

6.What is the name of the interface that is implemented by classes that contain an ordered collection of objects that can be individually indexed? Name the System.Collections classes that implement this interface.

The IList interface is implemented by Array, ArrayList, StringCollection, and TreeNodeCollection.

7.What is the name of the interface for collections of associated keys and values? Name the System.Collections classes that implement this interface.

The IDictionary interface is implemented by Hashtable, DictionaryBase, and SortedList.

8.Generic collection classes require runtime type-casting of their items to obtain the true type of the items in the collection classes. Name the issues raised by runtime casting.

Type-checking cannot be done at compile time. Performance overhead of casting.

In the case of collection of value types, boxing and unboxing operations.

Module 8:

Delegates and Events

Contents

 

Overview

1

Delegates

2

Multicast Delegates

12

Events

21

When to Use Delegates, Events, and

 

Interfaces

31

Lab 8: Creating a Simple Chat Server

32

Review

42

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

2001-2002 Microsoft Corporation. All rights reserved.

Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint, Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and

Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Module 8: Delegates and Events

iii

 

 

 

Instructor Notes

Presentation:

75 Minutes

Lab:

75 Minutes

After completing this module, students will be able to:

!Use the delegate class to create type-safe callback functions and eventhandling methods.

!Use the event keyword to simplify and improve the implementation of a class that raises events.

!Implement events that conform to the Microsoft® .NET Framework guidelines.

Materials and Preparation

This section provides the materials and preparation tasks that you need to teach this module.

Required Materials

To teach this module, you need the Microsoft PowerPoint® file 2349B_08.ppt.

Preparation Tasks

To prepare for this module, you should:

!Read all of the materials for this module.

!Practice the demonstrations.

!Complete the lab.

iv

Module 8: Delegates and Events

Demonstrations

This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.

Using Delegates

In this demonstration, you will use Microsoft Visual Studio® .NET to run code in which a delegate to a light object’s method is passed to a switch object. When the switch object’s state changes, the switch object calls the light object’s method and passes its new state.

The code for this demonstration is provided in the student notes. The demonstration files are located in <install folder>\Democode\Mod08\ Demo08.1\Using Delegates.

Multicast Delegates

In this demonstration, you will show students how to add and remove methods from the invocation list of multicast delegates by using the plus operator (+) and the minus operator (-).

The code for this demonstration is provided in the student notes. The demonstration files are located in <install folder>\Democode\Mod08\ Demo08.2\MULTICAST DELEGATES.

Module Strategy

Use the following strategy to present this module:

!Delegates

Use the Delegate Scenario to help students to visualize and comprehend the concept of delegates. Some students may question the validity of this scenario. In the real world, a house would never be rewired dynamically, but you can explain that software programs often need to rebind dynamically.

!Multicast Delegates

Contrast typical multicast delegate use with that of the single delegate example by using the common scenario of a switch that controls two light bulbs. Explain how to create and invoke multicast delegates and show how to use the + and operators in C# to add and remove methods from the invocation list of multicast delegates.

!Events

Use the Event Scenario to help students to visualize and comprehend the concept of events. Emphasize that events are an important building block for creating classes that can be reused in many different programs, and that delegates are particularly suited for event handling. Explain how to declare, connect to, and raise an event.

Introduce the .NET Framework guidelines for delegates and events.

!When to Use Delegates, Events, and Interfaces

Contrast and compare the specific usage characteristics of delegates, interfaces, and events for providing callback functionality in particular situations.

Соседние файлы в папке c#