如何利用EventArgs类来传递消息事件
我们看C#内部很多类型中的方法定义,都是两个参数,第一个是Object,第二个是Event,而这是C#非常建议的一种形式,利用这种形式传递事件,可以让代码看起来更规范,也比较好用。
需要注意的是:
EventArgs是基类,不能直接用,如果需要自定义事件,需要继承它然后写一个自己的事件类
用法相对简单,直接上代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace tests3
{
//这里定义了一个自定义消息类
public class CarEventArgs : EventArgs
{
public readonly string msg;
public CarEventArgs(string message)
{
msg = message;
}
}
public class Car
{
public int CurrentSpeed { get; set; }
public int MaxSpeed { get; set; }
public string PetName{ get; set; }
private bool carIsDead;
public Car() { MaxSpeed = 100; }
public Car( string name, int maxSp, int currSp)
{
CurrentSpeed = currSp;
MaxSpeed = maxSp;
PetName = name;
}
public delegate void CarEngineHandler(object sender, CarEventArgs e);
public event CarEngineHandler Exploded;
public event CarEngineHandler AboutToBlow;
public void Accelerate(int delta)
{
if (carIsDead)
{
if (Exploded != null)
{
Exploded(this,new CarEventArgs("Sorry, this car is dead ..."));
}
}
else
{
CurrentSpeed += delta;
if (10 == (MaxSpeed - CurrentSpeed) && AboutToBlow != null)
{
AboutToBlow(this,new CarEventArgs("Careful buddy! Gonna blow!"));
}
if (CurrentSpeed >= MaxSpeed)
carIsDead = true;
else
Console.WriteLine("CurrentSpeed = {0}", CurrentSpeed);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("**** Delegates as event enablers ******\n");
Car c1 = new Car("SlugBug", 100, 10);
c1.AboutToBlow += CarIsAlmostDoomed;
c1.AboutToBlow += CarAboutToBlow;
Car.CarEngineHandler d = CarExploded;
c1.Exploded += d;
Console.WriteLine("**** Speeding up *****");
for(int i = 0; i< 6;i ++)
{
c1.Accelerate(20);
}
Console.ReadLine();
c1.Exploded -= d;
Console.WriteLine("****** Speeding up*******");
for(int i = 0; i<6; i++)
{
c1.Accelerate(20);
}
Console.ReadLine();
}
public static void OnCarEngineEvent(string msg)
{
Console.WriteLine("\n ******** Message From Car Object *********");
Console.WriteLine(" => {0}", msg);
Console.WriteLine("******************\n");
}
public static void OnCarEngineEvent2(string msg)
{
Console.WriteLine("=>{0}", msg.ToUpper());
}
public static void CarAboutToBlow(object sender, CarEventArgs e)
{
Console.WriteLine("{0} says : {1}",sender,e.msg);
}
public static void CarIsAlmostDoomed(object sender, CarEventArgs e)
{
Console.WriteLine("=> Critical Message from Car: {0}",e.msg);
}
public static void CarExploded(object sender, CarEventArgs e)
{
Console.WriteLine(e.msg);
}
}
}