结合.net框架在C#派生类中触发基类事件及实现接口事件
在派生类中引发基类事件
以下简单示例演示了在基类中声明可从派生类引发的事件的标准方法。此模式广泛应用于 .net framework 类库中的 windows 窗体类。
在创建可用作其他类的基类的类时,应考虑如下事实:事件是特殊类型的委托,只可以从声明它们的类中调用。派生类无法直接调用基类中声明的事件。尽管有时需要事件仅由基类引发,但在大多数情形下,应该允许派生类调用基类事件。为此,您可以在包含该事件的基类中创建一个受保护的调用方法。通过调用或重写此调用方法,派生类便可以间接调用该事件。
注意:不要在基类中声明虚拟事件,也不要在派生类中重写这些事件。c# 编译器无法正确处理这些事件,并且无法预知的该派生的事件的用户是否真正订阅了基类事件。
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; } } } // 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 * radius; } public void update(double d) { radius = d; area = 3.14 * radius * 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 in debug mode. system.console.writeline("press any key to exit."); system.console.readkey(); } } }
输出:
received event. shape area is now 10201.86 drawing a circle received event. shape area is now 49 drawing a rectangle
实现接口事件
接口可声明事件。下面的示例演示如何在类中实现接口事件。实现接口事件的规则与实现任何接口方法或属性的规则基本相同。
在类中实现接口事件
在类中声明事件,然后在适当的区域调用该事件。
namespace implementinterfaceevents { public interface idrawingobject { event eventhandler shapechanged; } public class myeventargs : eventargs { // class members } public class shape : idrawingobject { public event eventhandler shapechanged; void changeshape() { // do something here before the event… onshapechanged(new myeventargs(/*arguments*/)); // or do something here after the event. } protected virtual void onshapechanged(myeventargs e) { if(shapechanged != null) { shapechanged(this, e); } } } }
下面的示例演示如何处理以下的不常见情况:您的类是从两个以上的接口继承的,每个接口都含有同名事件)。在这种情况下,您至少要为其中一个事件提供显式接口实现。为事件编写显式接口实现时,必须编写 add 和 remove 事件访问器。这两个事件访问器通常由编译器提供,但在这种情况下编译器不能提供。
您可以提供自己的访问器,以便指定这两个事件是由您的类中的同一事件表示,还是由不同事件表示。例如,根据接口规范,如果事件应在不同时间引发,则可以将每个事件与类中的一个单独实现关联。在下面的示例中,订户将形状引用强制转换为 ishape 或 idrawingobject,从而确定自己将会接收哪个 ondraw 事件。
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; } // 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; object objectlock = new object(); // explicit interface implementation required. // associate idrawingobject's event with // predrawevent event eventhandler idrawingobject.ondraw { add { lock (objectlock) { predrawevent += value; } } remove { lock (objectlock) { predrawevent -= value; } } } // explicit interface implementation required. // associate ishape's event with // postdrawevent event eventhandler ishape.ondraw { add { lock (objectlock) { postdrawevent += value; } } remove { lock (objectlock) { 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(); // keep the console window open in debug mode. system.console.writeline("press any key to exit."); system.console.readkey(); } } }
输出:
sub1 receives the idrawingobject event. drawing a shape. sub2 receives the ishape event.
上一篇: C#数据库操作的用法