How to: Raise Base Class Events in Derived Classes 


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



ЗНАЕТЕ ЛИ ВЫ?

How to: Raise Base Class Events in Derived Classes



The following simple example shows the standard way to declare events in a base class so that they can also be raised from derived classes. This pattern is used extensively in Windows Forms classes in the.NET Framework class library.

When you create a class that can be used as a base class for other classes, you should consider the fact that events are a special type of delegate that can only be invoked from within the class that declared them. Derived classes cannot directly invoke events that are declared within the base class. Although sometimes you may want an event that can only be raised by the base class, most of the time, you should enable the derived class to invoke base class events. To do this, you can create a protected invoking method in the base class that wraps the event. By calling or overriding this invoking method, derived classes can invoke the event indirectly.

Note:
Do not declare virtual events in a base class and override them in a derived class. The C# compiler does not handle these correctly in Microsoft Visual Studio 2008 and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event.

Example

namespace BaseClassEvents { using System; using System.Collections.Generic;   // Special EventArgs class to hold info about Shapes. public class ShapeEventArgs: EventArgs { private double newArea;   public ShapeEventArgs(double d) { newArea = d; } public double NewArea { get { return newArea; } } }

Создание событий базового класса в производных классах

В следующем примере показан стандартный способ объявления событий в базовом классе таким образом, чтобы они могли создаваться и из производного класса. Этот принцип широко используется в классах Windows Forms в библиотеке классов.NET Framework.

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

Примечание.
Не следует объявлять виртуальные события в базовом классе и переопределять их в производном классе. Компилятор C# неправильно обрабатывает такие события в Microsoft Visual Studio 2008, невозможно с точностью предсказать, будет ли подписчик производного события в действительности подписан на событие базового класса.

Пример

ß--------


 

// Base class event publisher

public abstract class Shape

{

protected double area;

 

public double Area

{

get { return area; }

set { area = value; }

}

// The event. Note that by using the generic EventHandler<T> event type

// we do not need to declare a separate delegate type.

public event EventHandler<ShapeEventArgs> ShapeChanged;

 

public abstract void Draw();

 

//The event-invoking method that derived classes can override.

protected virtual void OnShapeChanged(ShapeEventArgs e)

{

// Make a temporary copy of the event to avoid possibility of

// a race condition if the last subscriber unsubscribes

// immediately after the null check and before the event is raised.

EventHandler<ShapeEventArgs> handler = ShapeChanged;

if (handler!= null)

{

handler(this, e);

}

}

}


 

 

ß-----


 

public class Circle: Shape

{

private double radius;

public Circle(double d)

{

radius = d;

area = 3.14 * radius;

}

public void Update(double d)

{

radius = d;

area = 3.14 * radius;

OnShapeChanged(new ShapeEventArgs(area));

}

protected override void OnShapeChanged(ShapeEventArgs e)

{

// Do any circle-specific processing here.

 

// Call the base class event invocation method.

base. OnShapeChanged(e);

}

public override void Draw()

{

Console.WriteLine("Drawing a circle");

}

}


 

ß-------


 

public class Rectangle: Shape

{

private double length;

private double width;

public Rectangle(double length, double width)

{

this. length = length;

this. width = width;

area = length * width;

}

public void Update(double length, double width)

{

this. length = length;

this. width = width;

area = length * width;

OnShapeChanged(new ShapeEventArgs(area));

}

protected override void OnShapeChanged(ShapeEventArgs e)

{

// Do any rectangle-specific processing here.

 

// Call the base class event invocation method.

base. OnShapeChanged(e);

}

public override void Draw()

{

Console.WriteLine("Drawing a rectangle");

}

 

}


 

 

ß-----


 

// Represents the surface on which the shapes are drawn // Subscribes to shape events so that it knows // when to redraw a shape. public class ShapeContainer { List<Shape> _list;   public ShapeContainer() { _list = new List<Shape>(); }   public void AddShape(Shape s) { _list.Add(s); // Subscribe to the base class event. s.ShapeChanged += HandleShapeChanged; }   //...Other methods to draw, resize, etc.   private void HandleShapeChanged(object sender, ShapeEventArgs e) { Shape s = (Shape)sender;   // Diagnostic message for demonstration purposes. Console.WriteLine("Received event. Shape area is now {0}", e.NewArea);   // Redraw the shape here. s.Draw(); } }

 


 

ß-----


 

class Test {   static void Main(string[] args) { //Create the event publishers and subscriber Circle c1 = new Circle(54); Rectangle r1 = new Rectangle(12, 9); ShapeContainer sc = new ShapeContainer();   // Add the shapes to the container. sc.AddShape(c1); sc.AddShape(r1);   // Cause some events to be raised. c1.Update(57); r1.Update(7, 7);   // Keep the console window open. Console.WriteLine(); Console.WriteLine("Press Enter to exit"); Console.ReadLine(); } } }
Received event. Shape area is now 178.98 Drawing a circle Received event. Shape area is now 49 Drawing a rectangle

 

ß-----



Поделиться:


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

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