How to: Implement Interface Events 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Implement Interface Events



An interface can declare an event. The following example shows how to implement interface events in a class. Basically the rules are the same as when you implement any interface method or property.

To implement interface events in a class

· Declare the event in your class and then invoke it in the appropriate areas.

public interface IDrawingObject { event EventHandler ShapeChanged; } public class MyEventArgs: EventArgs {…} public class Shape: IDrawingObject { event EventHandler ShapeChanged; void ChangeShape() { // Do something before the event… OnShapeChanged(new MyEventsArgs(…)); // or do something after the event. } protected virtual void OnShapeChanged(MyEventArgs e) { if(ShapeChanged!= null) { ShapeChanged(this, e); } } }

 


Реализация событий интерфейса

Интерфейс может объявить событие. В следующем примере показана реализация событий интерфейса в классе. В принципе, применяются те же правила, что и при реализации любого метода интерфейса или свойства.

Реализация событий интерфейса в классе

· Объявите событие в классе и вызовите его в соответствующих областях.

ß-----

 


Example

The following example shows how to handle the less-common situation in which your class inherits from two or more interfaces and each interface has an event with the same name. In this situation, you must provide an explicit interface implementation for at least one of the events. When you write an explicit interface implementation for an event, you must also write the add and remove event accessors. Normally these are provided by the compiler, but in this case the compiler cannot provide them.

By providing your own accessors, you can specify whether the two events are represented by the same event in your class, or by different events. For example, if the events should be raised at different times according to the interface specifications, you can associate each event with a separate implementation in your class. In the following example, subscribers determine which OnDraw event they will receive by casting the shape reference to either an IShape or an IDrawingObject.

namespace WrapTwoInterfaceEvents { using System;   public interface IDrawingObject { // Raise this event before drawing // the object. event EventHandler OnDraw; } public interface IShape { // Raise this event after drawing // the shape. event EventHandler OnDraw; }

 


Пример

В следующем примере показано, как действовать в не очень распространенном случае, когда класс наследует от двух или более интерфейсов и каждый интерфейс имеет событие с тем же именем. В такой ситуации, по меньшей мере, для одного из событий следует предоставить явную реализацию интерфейса. При написании явной реализации интерфейса для события необходимо также написать методы доступа к событию add и remove. Как правило, они обеспечиваются компилятором, в этом случае компилятор не сможет предоставить их.

При помощи собственных методов доступа можно определить, будут ли два события представлены одним событием в классе или разными событиями. Например, если события должны инициироваться в разное время в зависимости от требований интерфейса, то каждое событие можно связать с отдельной реализацией в классе. В следующем примере подписчики определяют, какое событие OnDraw они получат путем приведения ссылки на форму к IShape или IDrawingObject.

ß-----


 

// Base class event publisher inherits two

// interfaces, each with an OnDraw event

public class Shape: IDrawingObject, IShape

{

// Create an event for each interface event

event EventHandler PreDrawEvent;

event EventHandler PostDrawEvent;

// Explicit interface implementation required.

// Associate IDrawingObject's event with

// PreDrawEvent

event EventHandler IDrawingObject.OnDraw

{

add

{

if (null!=PreDrawEvent) lock (PreDrawEvent)

{

PreDrawEvent += value;

} else PreDrawEvent += value;

}

remove

{

lock (PreDrawEvent)

{

PreDrawEvent -= value;

}

}

}

// Explicit interface implementation required.

// Associate IShape's event with

// PostDrawEvent

event EventHandler IShape.OnDraw

{

add

{

if (null!= PostDrawEvent) lock (PostDrawEvent)

{

PostDrawEvent += value;

} else PostDrawEvent += value;

}

remove

{

lock (PostDrawEvent)

{

PostDrawEvent -= value;

}

}

}


 

ß----


 

// For the sake of simplicity this one method

// implements both interfaces.

public void Draw()

{

// Raise IDrawingObject's event before the object is drawn.

EventHandler handler = PreDrawEvent;

if (handler!= null)

{

handler(this, new EventArgs());

}

Console.WriteLine("Drawing a shape.");

// RaiseIShape's event after the object is drawn.

handler = PostDrawEvent;

if (handler!= null)

{

handler(this, new EventArgs());

}

}

}

public class Subscriber1

{

// References the shape object as an IDrawingObject

public Subscriber1(Shape shape)

{

IDrawingObject d = (IDrawingObject)shape;

d.OnDraw += new EventHandler(d_OnDraw);

}

 

void d_OnDraw(object sender, EventArgs e)

{

Console.WriteLine("Sub1 receives the IDrawingObject event.");

}

}

// References the shape object as an IShape

public class Subscriber2

{

public Subscriber2(Shape shape)

{

IShape d = (IShape)shape;

d.OnDraw += new EventHandler(d_OnDraw);

}

 

void d_OnDraw(object sender, EventArgs e)

{

Console.WriteLine("Sub2 receives the IShape event.");

}

}


 

ß------


 

public class Program { static void Main(string[] args) { Shape shape = new Shape(); Subscriber1 sub = new Subscriber1(shape); Subscriber2 sub2 = new Subscriber2(shape); shape.Draw();   Console.WriteLine("Press Enter to close this window."); Console.ReadLine(); } }   }
Sub1 receives the IDrawingObject event. Drawing a shape. Sub2 receives the IShape event.

 

ß-----



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 121; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.202.167 (0.014 с.)