C#下在派生类中引发基类事件的方法与示例

2024-08-23 23:28

本文主要是介绍C#下在派生类中引发基类事件的方法与示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 基类事件在派生类中的定义及触发方式
    • 基类事件的传播机制
    • 示例
    • 总结

在这里插入图片描述


在面向对象编程中,继承是代码复用的一种重要方式。C#作为一种面向对象的编程语言,允许派生类继承基类的属性和方法。基类定义了一系列共有的属性和行为,而派生类则可以在基类的基础上添加新的特性或重写基类的方法。事件作为一种特殊的成员,也可以在基类中被定义,并在派生类中被触发和使用。

基类事件在派生类中的定义及触发方式

在C#中,事件是一种使类或对象可以通知其他类或对象发生了某些事情的一种机制。在基类中定义事件,然后在派生类中触发这些事件是常见的做法。下面是一个简单的基类事件定义的例子:

public class BaseClass
{// 定义一个事件public event EventHandler MyEvent;// 触发事件的保护方法protected virtual void OnMyEvent(EventArgs e){MyEvent?.Invoke(this, e);}
}

在派生类中,我们可以通过调用基类中定义的保护方法来触发事件:

public class DerivedClass : BaseClass
{// 触发基类事件的派生类方法public void TriggerEvent(){OnMyEvent(EventArgs.Empty);}
}

基类事件的传播机制

基类事件的传播机制主要有两种:主动传播和自动传播。

主动传播
主动传播是指派生类明确调用基类的事件触发方法。这种方式要求派生类知道基类的事件触发方法,并显式调用它。如上例所示,TriggerEvent 方法调用了 OnMyEvent 方法。

自动传播
自动传播是指派生类重写基类的方法,并在其中触发基类事件。这样,当基类的方法被调用时,事件也会被自动触发。例如:

public class BaseClass
{public event EventHandler MyEvent;protected virtual void OnMyEvent(EventArgs e){MyEvent?.Invoke(this, e);}public virtual void DoSomething(){// 基类方法逻辑}
}public class DerivedClass : BaseClass
{public override void DoSomething(){// 派生类自己的逻辑base.DoSomething(); // 调用基类方法OnMyEvent(EventArgs.Empty); // 触发事件}
}

示例

下面是一个完整的示例,展示了基类事件如何在派生类中被触发:

using System;public class BaseClass
{public event EventHandler MyEvent;protected virtual void OnMyEvent(EventArgs e){MyEvent?.Invoke(this, e);}public void TriggerBaseEvent(){OnMyEvent(EventArgs.Empty);}
}public class DerivedClass : BaseClass
{public void DoSomething(){Console.WriteLine("DerivedClass is doing something.");OnMyEvent(EventArgs.Empty); // 触发基类事件}
}class Program
{static void Main(){DerivedClass derived = new DerivedClass();derived.MyEvent += (sender, e) => Console.WriteLine("Event triggered from DerivedClass.");derived.DoSomething(); // 触发事件derived.TriggerBaseEvent(); // 直接触发基类的事件}
}

在这个示例中,我们创建了一个派生类 DerivedClass,它继承自 BaseClass 并重写了 DoSomething 方法。在这个方法中,我们调用了 OnMyEvent 方法来触发基类的事件。

完整示例

namespace BaseClassEvents
{// Special EventArgs class to hold info about Shapes.public class ShapeEventArgs : EventArgs{public ShapeEventArgs(double area){NewArea = area;}public double NewArea { get; }}// Base class event publisherpublic abstract class Shape{protected double _area;public double Area{get => _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){// Safely raise the event for all subscribersShapeChanged?.Invoke(this, e);}}public class Circle : Shape{private double _radius;public Circle(double radius){_radius = radius;_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){_length = length;_width = width;_area = _length * _width;}public void Update(double length, double width){_length = length;_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{private readonly List<Shape> _list;public ShapeContainer(){_list = new List<Shape>();}public void AddShape(Shape shape){_list.Add(shape);// Subscribe to the base class event.shape.ShapeChanged += HandleShapeChanged;}// ...Other methods to draw, resize, etc.private void HandleShapeChanged(object sender, ShapeEventArgs e){if (sender is Shape shape){// Diagnostic message for demonstration purposes.Console.WriteLine($"Received event. Shape area is now {e.NewArea}");// Redraw the shape here.shape.Draw();}}
}
class Test
{
static void Main()
{//Create the event publishers and subscribervar circle = new Circle(54);var rectangle = new Rectangle(12, 9);var container = new ShapeContainer();// Add the shapes to the container.container.AddShape(circle);container.AddShape(rectangle);// Cause some events to be raised.circle.Update(57);rectangle.Update(7, 7);// Keep the console window open in debug mode.Console.WriteLine("Press any key to continue...");Console.ReadKey();
}
}/* Output:
Received event. Shape area is now 10201.86
Drawing a circle
Received event. Shape area is now 49
Drawing a rectangle
*/
}

总结

在派生类中引发基类事件可以增强代码的可重用性、封装性和灵活性。通过这种方式,我们可以确保基类的行为能够在派生类中得到正确的通知,而无需在每个派生类中重新定义事件。这不仅减少了代码的冗余,还使得基类和派生类之间的交互更加清晰和一致。通过合理地使用事件,我们可以构建出更加健壮和易于维护的面向对象系统。

这篇关于C#下在派生类中引发基类事件的方法与示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1100798

相关文章

利用c++判断水仙花数并输出示例代码

《利用c++判断水仙花数并输出示例代码》水仙花数是指一个三位数,其各位数字的立方和恰好等于该数本身,:本文主要介绍利用c++判断水仙花数并输出的相关资料,文中通过代码介绍的非常详细,需要的朋友可以... 以下是使用C++实现的相同逻辑代码:#include <IOStream>#include <vec

SQL Server 中的表进行行转列场景示例

《SQLServer中的表进行行转列场景示例》本文详细介绍了SQLServer行转列(Pivot)的三种常用写法,包括固定列名、条件聚合和动态列名,文章还提供了实际示例、动态列数处理、性能优化建议... 目录一、常见场景示例二、写法 1:PIVOT(固定列名)三、写法 2:条件聚合(CASE WHEN)四、

Python字符串处理方法超全攻略

《Python字符串处理方法超全攻略》字符串可以看作多个字符的按照先后顺序组合,相当于就是序列结构,意味着可以对它进行遍历、切片,:本文主要介绍Python字符串处理方法的相关资料,文中通过代码介... 目录一、基础知识:字符串的“不可变”特性与创建方式二、常用操作:80%场景的“万能工具箱”三、格式化方法

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

Java 接口定义变量的示例代码

《Java接口定义变量的示例代码》文章介绍了Java接口中的变量和方法,接口中的变量必须是publicstaticfinal的,用于定义常量,而方法默认是publicabstract的,必须由实现类... 在 Java 中,接口是一种抽象类型,用于定义类必须实现的方法。接口可以包含常量和方法,但不能包含实例

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

自定义注解SpringBoot防重复提交AOP方法详解

《自定义注解SpringBoot防重复提交AOP方法详解》该文章描述了一个防止重复提交的流程,通过HttpServletRequest对象获取请求信息,生成唯一标识,使用Redis分布式锁判断请求是否... 目录防重复提交流程引入依赖properties配置自定义注解切面Redis工具类controller