delegate event 以及lambda expression的基本例子(synchronous invocation)
////////////////////
// C#代码 Car.cs
////////////////////
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace event_test
{
class Car
{
private int speed;
public Car(int speed)
{
this.speed = speed;
}
//delegate TYPE declaration(CarEventHandler is delegate of type "void(object,CarEventArgs)")
public delegate void CarEventHandler(Object sender,CarEventArgs e);
//event is syntactic sugar of defining internal private delegate object and providing add/remove functionality
//i.e. define member variable of delegate type and (provide helper method to)add members to the invocation list
//see 《Pro C# .NET3.5 Platform》Ebook pp.379
public event CarEventHandler eventBusted;
//defining event using generic EventHandler
public event EventHandler<CarEventArgs> GenericEventBusted;
public void accelerate(int delta)
{
if (speed+delta>100)
{
if (eventBusted!=null)
{
eventBusted(this,new CarEventArgs(true,true));
GenericEventBusted(this, new CarEventArgs(true, true));
}
}
else
{
speed += delta;
Console.WriteLine("current speed is {0}", speed);
}
}
}
}
public class CarEventArgs:EventArgs
{
public readonly bool bCarBusted;
public readonly bool bDriverAlive;
public CarEventArgs(bool isCarBusted,bool isDriverAlive)
{
this.bCarBusted = isCarBusted;
this.bDriverAlive = isDriverAlive;
}
}
////////////////////////////
//C#代码 Program.cs
////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace event_test
{
class Program
{
static void Main(string[] args)
{
Car mycar = new Car(50);
//EventObject calls InternalPrivateDelegateObject.Add() to add function to its invocation list
mycar.eventBusted += new Car.CarEventHandler(ShowCarStatus);
//using anonymous delegate
mycar.eventBusted += delegate(object sender,CarEventArgs e)
{
Console.WriteLine("driver of car {0} is {1}", sender, e.bDriverAlive ? "alive" : "dead");
};
//using lambda expression(which is a shorthand for anonymous delegate)
mycar.eventBusted += ((object sender, CarEventArgs e) => { Console.WriteLine("invoking lambda exp from {0}", sender); });
//alternatively,we can use Generic delegate type: EventHandler
mycar.GenericEventBusted += new EventHandler<CarEventArgs>(cbBustHandler);
for (int i = 5; i >= 0;i--)
{
mycar.accelerate(15);
Console.WriteLine();
}
Console.ReadLine();
}
//the (callback)function is defined here(stub is auto generated by intellisense when typing "someobject.event += new...")
static void ShowCarStatus(object sender, CarEventArgs e)
{
Console.WriteLine("the car {0} is {1}",sender,(e.bCarBusted?"busted":"safe"));
}
static void cbBustHandler(object sender,EventArgs e)
{
Console.WriteLine("invoking from generic delegate type:EventHandler");
}
}
}
posted on 2009-07-31 12:10 TobyLin的学习之路 阅读(227) 评论(0) 编辑 收藏 举报