从博客园看到的 转载来。
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eventDelegate
{
//通水人
class middleBoy
{
//
public delegate void playGame(object obj, playGameEventArgs e);
}
//消息
class playGameEventArgs:EventArgs
{
public string name{get;set;}
}
class Boss
{
public static void notify(object obj, playGameEventArgs e)
{
Console.WriteLine(e.name + " 玩游戏了");
}
}
//管理人2
class Admin
{
public static void notify(object obj, playGameEventArgs e)
{
Console.WriteLine(e.name + " 玩游戏了");
}
}
class employee
{
private string name{get;set;}
public employee(string n)
{
name = n;
}
public event middleBoy.playGame game;
public void iPlayGame()
{
if (game != null)
{
playGameEventArgs e=new playGameEventArgs();
e.name = name;
game(this,e);
}
}
}
class Program
{
static void Main(string[] args)
{
employee ee = new employee("Javk");
ee.game += new middleBoy.playGame(Boss.notify);
ee.game += new middleBoy.playGame(Admin.notify);
ee.iPlayGame();
Console.ReadLine();
}
}
}
1.delegate做 监控人、事件发生者 之间的通讯人 2. 新的事件发生者的参数需要继承EventArgs,做成新的消息 3.事件发生者要判断事件是否为空再运行行动 4.多路发布遵守OPP原则(原基类封闭原则,开放业务类) [C#] 纯文本查看 复制代码 //消息
class playGameEventArgs:EventArgs
{
public string name{get;set;}
}
class Boss
{
public static void notify(object obj, playGameEventArgs e)
{
Console.WriteLine(e.name + " 玩游戏了");
}
}
//管理人2
class Admin
{
public static void notify(object obj, playGameEventArgs e)
{
Console.WriteLine(e.name + " 玩游戏了");
}
}
class employee
{
private string name{get;set;}
public employee(string n)
{
name = n;
}
//用泛式代替了代理
public event EventHandler<playGameEventArgs> game;
public void iPlayGame()
{
if (game != null)
{
playGameEventArgs e=new playGameEventArgs();
e.name = name;
game(this,e);
}
}
}
class Program
{
static void Main(string[] args)
{
employee ee = new employee("Javk");
ee.game += Boss.notify;
ee.game +=Admin.notify;
ee.iPlayGame();
Console.ReadLine();
}
}
}
|