参考文章来自:http://bbs.csdn.net/topics/360062894此处回帖 。
有点乱,将就着看,毕竟第一次写。。。内容仅为当前个人见解,错误之处麻烦指出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace 委托事件
{
class Program
{
static void Main(string[] args)
{
Console.Write("正在点击");
for (int i = 0; i < 4; i++)
{
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine();
Console.Write("点击完成,正在传送数据给事件");
for (int i = 0; i < 4; i++)
{
Thread.Sleep(1000);
Console.Write(".");
}
Console.WriteLine();
button bt = new button("委托功能已经实现!!!");
bt.Clicked += (object sender, EventArgs e) => {
Console.WriteLine("事件已经完成");
};
bt.Clicked += (object o, EventArgs e) => {
Console.WriteLine("事件2已经完成");
};
bt.Clicked += (object o, EventArgs e) => {
Console.WriteLine("事件功能3已经完成");
Console.WriteLine(o.ToString());
};
Console.WriteLine("请输入点击事件传输的数据");
string str = Console.ReadLine();
while (true)
{
//事件的执行者一直再执行一个判断事件订阅者有没有发来数据,数据通过EventArgs传输,一单数据符合则事件执行
//数据通过sender发送
if (str=="Test")
{
bt.Click(() => {
Console.WriteLine("委托功能实现中!!!");
});
Console.ReadKey();
}
else
{
Console.WriteLine("请输入点击事件传输的数据");
str = Console.ReadLine();
}
}
}
}
class Test
{
}
class button
{
public button(string Text)
{
this.Text = Text;
}
private string Text;
public delegate void Clicking();
public event EventHandler Clicked;
public void Click(Clicking clicking)
{
clicking();
Console.WriteLine(Text);
Test t = new Test();
Clicked(t, EventArgs.Empty);
}
}
}