为何要继承EventArgs类
为何要继承EventArgs类
我尝试删除后,依然可以运行。
所以想明白为什么要继承这个类。
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
// 热水器
public class Heater
{
private int temperature;
public string type = "RealFire 001"; // 添加型号作为演示
public string area = "China Xian"; // 添加产地作为演示
//声明委托
public delegate void BoiledEventHandler(Object sender, BoiledEventArgs e);
public event BoiledEventHandler Boiled; //声明事件
// 定义BoiledEventArgs类,传递给Observer所感兴趣的信息
public class BoiledEventArgs : EventArgs //??????????????????????????????????????为何要继承这个class
{
public readonly int temperature;
public BoiledEventArgs(int temperature)
{
this.temperature = temperature;
}
}
// 可以供继承自 Heater 的类重写,以便继承类拒绝其他对象对它的监视
protected virtual void OnBoiled(BoiledEventArgs e)
{
if (Boiled != null)
{ // 如果有对象注册
Boiled(this, e); // 调用所有注册对象的方法
}
}
// 烧水。
public void BoilWater()
{
for (int i = 0; i <= 100; i++)
{
temperature = i;
if (temperature > 95)
{
//建立BoiledEventArgs 对象。
BoiledEventArgs e = new BoiledEventArgs(temperature);
OnBoiled(e); // 调用 OnBolied方法
}
}
}
}
// 警报器
public class Alarm
{
public void MakeAlert(Object sender, Heater.BoiledEventArgs e)
{
Heater heater = (Heater)sender; //这里是不是很熟悉呢?
//访问 sender 中的公共字段
Console.WriteLine("Alarm:{0} - {1}: ", heater.area, heater.type);
Console.WriteLine("Alarm: 嘀嘀嘀,水已经 {0} 度了:", e.temperature);
Console.WriteLine();
}
}
// 显示器
public class Display
{
public static void ShowMsg(Object sender, Heater.BoiledEventArgs e)
{ //静态方法
Heater heater = (Heater)sender;
Console.WriteLine("Display:{0} - {1}: ", heater.area, heater.type);
Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", e.temperature);
Console.WriteLine();
}
}
class Program
{
static void Main()
{
Heater heater = new Heater();
Alarm alarm = new Alarm();
heater.Boiled += alarm.MakeAlert; //注册方法
heater.Boiled += (new Alarm()).MakeAlert; //给匿名对象注册方法
heater.Boiled += new Heater.BoiledEventHandler(alarm.MakeAlert); //也可以这么注册
heater.Boiled += Display.ShowMsg; //注册静态方法
heater.BoilWater(); //烧水,会自动调用注册过对象的方法
Console.ReadKey();
}
}
}
[解决办法]
继承EventArgs是表示该类可作为事件,删掉了就默认继承object,没人会说你错
[解决办法]
初学者应该学习的是编程的约定和规范,而不是突然发现一个小技巧,或者关注“性能”。
如同小朋友学习吃饭,发现不用筷子也能吃,说这样效率很高。
[解决办法]
本帖最后由 caozhy 于 2011-04-05 16:10:34 编辑
了解本质不是错,问题是论坛提问不是一个了解本质的方式。因为这需要很多基础知识的准备。如果你真是一个想了解本质的人,首要需要明白的是找到一条通往了解本质的路。
要想达到你说的“也许有一天”,唯一的办法就是耐心地去学习,我觉得看书和思考更重要。毕竟知道一个似是而非的结论对你或许有一点帮助,但是我觉得微不足道。只有扎实的基础和思考分析能力才是最主要的。在此之上的探究才是“探究本质”,否则是钻牛角尖。
不去花功夫打基础,得到的结论无从理解。甚至可以说,很多所谓的“结论”本身就是以讹传讹,今天看到这么一种说法,明天另外一个人又告诉你另一个说法,你只会和本质越行越远。
至于为什么要继承 EventArgs,这是 .NET 框架的约定。从软件工程的角度,无论你使用 MFC、Windows API、.NET Framework、还是什么库,和系统类库保持一致的编码风格,使得你新增的代码成为核心代码的自然延续都是首推的最佳实践。
当然,这只是我的看法而已。