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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

Console.WriteLine("File created: " + e.FullPath);

}

static void fileWatcher_Changed(object sender, FileSystemEventArgs e) {

Console.WriteLine("File changed: " + e.FullPath);

}

static void fileWatcher_Renamed(object sender, RenamedEventArgs e) {

Console.WriteLine("File renamed: " + e.FullPath);

}

static void fileWatcher_Deleted(object sender, FileSystemEventArgs e) {

Console.WriteLine("File deleted: " + e.FullPath);

}

To test the program, you can create a new text file in C:\drive, make some changes to its content, rename it, and then delete it. The output window will look like Figure 7-9.

Figure 79 Implementing Events So far you have been subscribing to events by - фото 129

Figure 7-9

Implementing Events

So far you have been subscribing to events by writing event handlers. Now you will implement events in your own class. For this example, you create a class called AlarmClock. AlarmClockallows you to set a particular date and time so that you can be notified (through an event) when the time is up. For this purpose, you use the Timerclass.

First, define the AlarmClockclass as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Timers;

class AlarmClock {

}

Declare a Timervariable and define the AlarmTimeproperty to allow users of this class to set a date and time:

class AlarmClock {

Timer t;

public DateTime AlarmTime { get; set; }

}

Next, define the Start()method so that users can start the monitoring by turning on the Timerobject:

class AlarmClock {

//...

public void Start() {

t.Start();

}

}

Next, define a public event member in the AlarmClockclass:

public event EventHandler TimesUp;

The EventHandleris a predefined delegate, and this statement defines TimesUpas an event for your class.

Define a protected virtual method in the AlarmClockclass that will be used internally by your class to raise the TimesUpevent:

protected virtual void onTimesUp(EventArgs e) {

if (TimesUp != null) TimesUp(this, e);

}

The EventArgsclass is the base class for classes that contain event data. This class does not pass any data back to an event handler.

The next section explains how you can create another class that derives from this EventArgsbase class to pass back information to an event handler.

Define the constructor for the AlarmClockclass so that the Timerobject ( t) will fire its Elapsedevent every 100 milliseconds. In addition, wire the Elapsedevent with an event handler. The event handler will check the current time against the time set by the user of the class. If the time equals or exceeds the user's set time, the event handler calls the onTimesUp()method that you defined in the previous step:

public AlarmClock() {

t = new Timer(100);

t.Elapsed += new ElapsedEventHandler(t_Elapsed);

}

void t_Elapsed(object sender, ElapsedEventArgs e) {

if (DateTime.Now >= this.AlarmTime) {

onTimesUp(new EventArgs());

t.Stop();

}

}

That's it! The entire AlarmClockclass is:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Timers;

class AlarmClock {

Timer t;

public DateTime AlarmTime { get; set; }

public void Start() {

t.Start();

}

public AlarmClock() {

t = new Timer(100);

t.Elapsed += new ElapsedEventHandler(t_Elapsed);

}

void t_Elapsed(object sender, ElapsedEventArgs e) {

if (DateTime.Now >= this.AlarmTime) {

onTimesUp(new EventArgs());

t.Stop();

}

}

public event EventHandler TimesUp;

protected virtual void onTimesUp(EventArgs e) {

if (TimesUp != null) TimesUp(this, e);

}

}

To use the AlarmClockclass, you first create an instance of the AlarmClockclass and then set the time for the alarm by using the AlarmTimeproperty. You then wire the TimesUpevent with an event handler so that you can print a message when the set time is up:

class Program {

static void Main(string[] args) {

AlarmClock c = new AlarmClock() {

//---alarm to sound off at 16 May 08, 9.50am---

AlarmTime = new DateTime(2008, 5, 16, 09, 50, 0, 0),

};

c.Start();

c.TimesUp += new EventHandler(c_TimesUp);

Console.ReadLine();

}

static void c_TimesUp(object sender, EventArgs e) {

Console.WriteLine("Times up!");

}

}

Difference between Events and Delegates

Events are implemented using delegates, so what is the difference between an event and a delegate? The difference is that for an event you cannot directly assign a delegate to it using the =operator; you must use the +=operator.

To understand the difference, consider the following class definitions — Class1and Class2:

namespace DelegatesVsEvents {

class Program {

static void Main(string[] args) {}

}

class Class1 {

public delegate void Class1Delegate();

public Class1Delegate del;

}

class Class2 {

public delegate void Class2Delegate();

public event Class2Delegate evt;

}

}

In this code, Class1exposes a public delegate del, of type Class1Delegate. Class2is similar to Class1, except that it exposes an event evt, of type Class2Delegate. deland evteach expect a delegate, with the exception that evtis prefixed with the eventkeyword.

To use Class1, you create an instance of Class1and then assign a delegate to the del delegate using the " =" operator:

static void Main(string[] args) {

//---create a delegate---

Class1.Class1Delegate d1 =

new Class1.Class1Delegate(DoSomething);

Class1 c1 = new Class1();

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

Интервал:

Закладка:

Сделать

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

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


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

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

x