Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать
Figure 910 To insert a list of random numbers into the linked list you can - фото 147

Figure 9-10

To insert a list of random numbers into the linked list, you can use the following statements:

Random rnd = new Random();

for (int i = 0; i < 20; i++)

InsertNumber(rnd.Next(100)); //---random number from 0 to 100---

To print out all the numbers contained within the linked list, traverse the link starting from the first node:

//---traverse forward---

LinkedListNode node = Numbers.First;

while (node != null) {

Console.WriteLine(node.Value);

node = node.Next;

}

The result is a list of 20 random numbers in sorted order. Alternatively, you can traverse the list backward from the last node:

//---traverse backward---

LinkedListNode node = Numbers.Last;

while (node != null) {

Console.WriteLine(node.Value);

node = node.Previous;

}

The result would be a list of random numbers in reverse-sort order.

System.Collections.ObjectModel

The System.Collections.ObjectModelnamespace in the .NET class library contains several generic classes that deal with collections. These classes are described in the following table.

Generic Class Description
Collection Provides the base class for a generic collection.
KeyedCollection Provides the abstract base class for a collection whose keys are embedded in the values.
ObservableCollection Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
ReadOnlyCollection Provides the base class for a generic read-only collection.
ReadOnlyObservableCollection Represents a read-only ObservableCollection.

Let's take a look at Collection, one of the classes available. It is similar to the generic Listclass. Both Collectionand Listimplement the IListand ICollectioninterfaces. The main difference between the two is that Collectioncontains virtual methods that can be overridden, whereas Listdoes not have any.

The Listgeneric class is discussed in details in Chapter 13.

The following code example shows how to use the generic Collectionclass:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections.ObjectModel;

namespace CollectionEg1 {

class Program {

static void Main(string[] args) {

Collection names = new Collection();

names.Add("Johnny");

names.Add("Michael");

names.Add("Wellington");

foreach (string name in names) {

Console.WriteLine(name);

}

Console.ReadLine();

}

}

}

Here's the example's output:

Johnny

Michael

Wellington

To understand the usefulness of the generic Collectionclass, consider the following example where you need to write a class to contain the names of all the branches a company has:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections.ObjectModel;

namespace CollectionEg2 {

class Program {

static void Main(string[] args) {}

}

public class Branch {

private List _branchNames = new List();

public List BranchNames {

get {

return _branchNames;

}

}

}

}

In this example, the Branchclass exposes a public read-only property called BranchNamesof type List. To add branch names to a Branchobject, you first create an instance of the Branchclass and then add individual branch names to the BranchNamesproperty by using the Add()method of the Listclass:

static void Main(string[] args) {

Branch b = new Branch();

b.BranchNames.Add("ABC");

b.BranchNames.Add("XYZ");

}

Suppose now that your customers request an event for the Branchclass so that every time a branch name is deleted, the event fires so that the client of Branchclass can be notified. The problem with the generic Listclass is that there is no way you can be informed when an item is removed.

A better way to resolve this issue is to expose BranchNameas a property of type Collectioninstead of List. That's because the generic Collectiontype provides four overridable methods — ClearItems(), InsertItem(), RemoveItem(), and SetItem()— which allow a derived class to be notified when a collection has been modified.

Here's how rewriting the Branchclass, using the generic Collectiontype, looks:

public class Branch {

public Branch() {

_branchNames = new BranchNamesCollection(this);

}

private BranchNamesCollection _branchNames;

public Collection BranchNames {

get {

return _branchNames;

}

}

//---event raised when an item is removed---

public event EventHandler ItemRemoved;

//---called from within the BranchNamesCollection class---

protected virtual void RaiseItemRemovedEvent(EventArgs e) {

if (ItemRemoved != null) {

ItemRemoved(this, e);

}

}

private class BranchNamesCollection : Collection {

private Branch _b;

public BranchNamesCollection(Branch b) _b = b;

//---fired when an item is removed---

protected override void RemoveItem(int index) {

base.RemoveItem(index);

_b.RaiseItemRemovedEvent(EventArgs.Empty);

}

}

}

There is now a class named BranchNamesCollectionwithin the Branchclass. The BranchNamesCollectionclass is of type Collection. It overrides the RemoveItem()method present in the Collectionclass. When an item is deleted from the collection, it proceeds to remove the item by calling the base RemoveItem()method and then invoking a function defined in the Branchclass: RaiseItemRemovedEvent(). The RaiseItemRemovedEvent()function then raises the ItemRemoved event to notify the client that an item has been removed.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x