• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > 结合.net框架在C#派生类中触发基类事件及实现接口事件

结合.net框架在C#派生类中触发基类事件及实现接口事件

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了c net框架,net框架4.0下载,mvc框架 asp.net,.net框架,.net框架培训等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

在派生类中引发基类事件
以下简单示例演示了在基类中声明可从派生类引发的事件的标准方法。此模式广泛应用于 .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();
    }
  }
}

</div>

输出:

    Received event. Shape area is now 10201.86
    Drawing a circle
    Received event. Shape area is now 49
    Drawing a rectangle
</div>


实现接口事件

接口可声明事件。下面的示例演示如何在类中实现接口事件。实现接口事件的规则与实现任何接口方法或属性的规则基本相同。
在类中实现接口事件
在类中声明事件,然后在适当的区域调用该事件。

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);
      }
    }
  }

}

</div>

下面的示例演示如何处理以下的不常见情况:您的类是从两个以上的接口继承的,每个接口都含有同名事件)。在这种情况下,您至少要为其中一个事件提供显式接口实现。为事件编写显式接口实现时,必须编写 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)
        {
         



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 结合.net框架在C#派生类中触发基类事件及实现接口事件

相关文章

  • 2017-05-28C#交错数组浅析
  • 2017-05-28C#发送内置图片html格式邮件的方法
  • 2017-05-28C# TextBox控件实现只能输入数字的方法
  • 2017-05-28rsa加密算法使用示例分享
  • 2017-05-28C#访问命令行的两种方法
  • 2017-05-28c#批量上传图片到服务器示例分享
  • 2017-05-28C#实现在控制台输入密码显示星号的方法
  • 2017-05-28C#使用linq计算执行元素在列表中出现次数的方法
  • 2017-05-28WinForm实现为TextBox设置水印文字功能
  • 2017-05-28C# yield在WCF中的错误用法(一)

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • c#转义字符串中的所有正则特殊字符方法示例
    • C# 常用公共方法
    • C#生成随机ArrayList的方法
    • C#实现DataTable映射成Model的方法(附源码)
    • C#多线程学习之(五)使用定时器进行多线程的自动管理
    • C#实现自动识别URL网址的方法
    • C#组合函数的使用详解
    • C#连接数据库和更新数据库的方法
    • C#实现随机数产生类实例
    • C#从foreach语句中枚举元素看数组详解

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有