C#:实现接口中定义的事件
2015-07-24 18:22
531 查看
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(); } } } /* Output: Sub1 receives the IDrawingObject event. Drawing a shape. Sub2 receives the IShape event. */
View Code
相关文章推荐
- 使用SuspendLayout和ResumeLayout
- c# byte[] 与string转化
- C# FileSystemWatcher 在监控文件夹和文件时的用法
- 在C#中读写INI配置文件
- C# Attribute应用:类签名
- C#简单读取、改变文件的创建、修改及访问时间的方法
- C# 获得程序当前目录的方法
- C#.net实现在Winform中从internet下载文件的方法
- c#封装自己写的dll,和引用自己的dll
- C#获取excel中sheel名称
- .Net Stack 技术栈
- C#关键字列表
- C#运算符优先级
- 用C#写一个实现进程监控的自动关机工具
- c# select标签绑定枚举,并以Description做Text显示
- C#学习笔记(十五):预处理指令
- C# 抽象工厂模式
- c#读取xml文档
- C#中??和?
- C#基础系列——小话泛型