An event can be raised only from the declaration space in which it is declared. Therefore, a class cannot raise events from any other class, even one from which it is derived.

事件只能在它被声明的声明空间(类)中使用。所以不能从任何其他类引发,即使该类是事件所在类的继承类。

那我们如何才可以引发基类中的事件,给个实例大家一看就明白了。

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();
}
}
}
/* Output:
Received event. Shape area is now 10201.86
Drawing a circle
Received event. Shape area is now 49
Drawing a rectangle
*/

 

参考

How to: Raise Base Class Events in Derived Classes (C# Programming Guide)

C#基础-事件 继承类无法直接引发基类的事件的更多相关文章

  1. WPF 之 创建继承自Window 基类的自定义窗口基类

    开发项目时,按照美工的设计其外边框(包括最大化,最小化,关闭等按钮)自然不同于 Window 自身的,但窗口的外边框及窗口移动.最小化等标题栏操作基本都是一样的.所以通过查看资料,可按如下方法创建继承 ...

  2. C++ 虚继承实现原理(虚基类表指针与虚基类表)

    虚继承和虚函数是完全无相关的两个概念. 虚继承是解决C++多重继承问题的一种手段,从不同途径继承来的同一基类,会在子类中存在多份拷贝.这将存在两个问题:其一,浪费存储空间:第二,存在二义性问题,通常可 ...

  3. 类转json的基类实现

    类转json的基类实现 项目地址 github地址 实现原理 使用反射获取类的属性名和属性内容.具体原理可以自己查一下资料 对一个类调用getClass().getDeclaredFields()可以 ...

  4. 编写高质量代码改善C#程序的157个建议——建议128:考虑让派生类的名字以基类名字作为后缀

    建议128:考虑让派生类的名字以基类名字作为后缀 派生类的名字可以考虑以基类名字作为后缀.这带来的好处是,从类型的名字上我们就知道它包含在哪一个继承体系中. Exception及其子类就是这样一个典型 ...

  5. C++派生类中如何初始化基类对象(五段代码)

    今天收到盛大的面试,问我一个问题,关于派生类中如何初始化基类对象,我在想派生类对于构造函数不都是先构造基类对象,然后在构造子类对象,但是如果我们在成员初始化列表先初始化派生类的私有成员,在函数内去调用 ...

  6. c++,派生类对象可以对基类赋值,基类对派生类不可以赋值

    派生类对象可以对基类对象赋值,赋值时属于派生类独有的部分就舍弃不用. #include <iostream> using namespace std; class DemoA { publ ...

  7. C++类继承--构造函数时先构造基类

    以下说明继承类函数构造时,先构造基类: 析构基类时,若没加上virtual,只析构基类,不析构派生类: 析构派生类时,同时会析构基类: 1. 基类析构函数有virtual #include <s ...

  8. C#继承机制 访问与隐藏基类成员

    (1) 访问基类成员 通过base 关键字访问基类的成员:   调用基类上已被其他方法重写的方法.  指定创建派生类实例时应调用的基类构造函数.  基类访问只能在构造函数.实例方法或实例属性访问器中进 ...

  9. C++primer原书中的一个错误(派生类using声明对基类权限的影响)

    在C++primer 第4版的 15章 15.2.5中有以下这样一段提示: "注解:派生类能够恢复继承成员的訪问级别,但不能使訪问级别比基类中原来指定的更严格或者更宽松." 在vs ...

随机推荐

  1. ASP.NET MVC自定义验证Authorize Attribute

    前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...

  2. C#汉字转拼音(支持多音字)

    之前由于项目需要,中间需要一个汉字转拼音和首拼的功能来做查询,感觉这种功能基本已经成熟化了,于是查找了相关的代码,首先引入眼帘的是下面两篇文章 1.C# 汉字转拼音(支持GB2312字符集中所有汉字) ...

  3. 分布式系统设计权衡之CAP

    写在最前: 1.为什么学习并记录分布式设计理念一系列相关的东西 在日常工作中系统设计评审的时候,经常会有一些同事抛出一些概念,高可用性,一致性等等字眼,他们用这些最基本的概念去反驳系统最初的设计,但是 ...

  4. 【C#】委托-Delegate

    C# 委托(Delegate) C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针.委托(Delegate) 是存有对某个方法的引用的一种引用类型变量.引用可在运行时被改变. 委托 ...

  5. 第 31 章 项目实战-PC 端固定布局[5]

    学习要点: 1.底部区域 2.说明区域 3.版权及证件区 主讲教师:李炎恢 本章主要开始使用学习用 HTML5 和 CSS3 来构建 Web 页面,第一个项目采用 PC 端固定布局来实现. 一.底部区 ...

  6. 从零开始学 Java - Spring MVC 统一异常处理

    看到 Exception 这个单词都心慌 如果有一天你发现好久没有看到Exception这个单词了,那你会不会想念她?我是不会的.她如女孩一样的令人心动又心慌,又或者你已经练功到了孤独求败,等了半辈子 ...

  7. MongoDB固定集合(capped collection)

    固定集合指的是事先创建而且大小固定的集合 . 固定集合特性:固定集合很像环形队列,如果空间不足,最早的文档就会被删除,为新的文档腾出空间.一般来说,固定集合适用于任何想要自动淘汰过期属性的场景,没有太 ...

  8. 《对象及DOM知识点及其应用1》

    1.图片间的来回切换用if{}else{}; <超链接方式的切换图片(常用)>如:<a href="../images1/1-small.jpg" id=&quo ...

  9. 【一次面试】再谈javascript中的继承

    前言 面向对象编程是每次面试必问的知识点,而前端js如何实现继承每次命中率高达80% 这不,近两天我们面试时候,同事就问道面试者此问题,但是,不论之前自己做的回答,还是面试者的回答,基本都不太令人满意 ...

  10. Web API初探

    前几天有位同事说web api中的接口参数为对象的时候不好接收,具体什么方式我忘记了,虽然本人以前并没有接触过这方面的知识,但是据说和MVC差不多的,今天小小的研究一下,我想应该是可以的. 直接新建一 ...