您的位置:首页 > 编程语言 > C#

C# 委托和事件 练习

2017-03-01 19:13 267 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
* 委托与事件练习
*
* 表、响铃、按钮
*
* 表时间从0开始,走到6就要响铃
* 响铃后输入n按回车,模拟按掉闹铃。
* 参考资料:http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx
*
*/

namespace EventDelegateTest
{
class Alarm //特指 响铃
{
public void Belling(object sender, Watch.ReachTimeEventArgs e)
{
Watch w = (Watch)sender;
Console.WriteLine("###w.time= " + w.Time + "  w.place= " + w.Place + "    dididi, 6 dian la , hayaku okii desu!!");
}
}
class AlarmButton//关闭响铃的按钮
{
public void Press(object sender, Watch.ReachTimeEventArgs e)
{
Watch w = (Watch)sender;
string str = "";
while (str != "n")
{
str = Console.ReadLine();
}
Console.WriteLine("###w.time= " + w.Time + "  w.place= " + w.Place + "  an diao nao zhong la  ! tsuzuku yasumi na sai !");
}
}

class Watch //表
{
public delegate void ReachTimeEventHandle(object sender,ReachTimeEventArgs e);
public event ReachTimeEventHandle ReachTime;

public Alarm alarm;
public AlarmButton alarmbutton;

private int time = 0;
private string place = "nanjing";

public int Time { get { return time; } }
public string Place { get { return place; } }

public class ReachTimeEventArgs:EventArgs
{
public readonly int time;
public readonly string place;
public ReachTimeEventArgs(int t,string p)
{
time = t;
place = p;
}
}

public Watch()
{
alarm = new Alarm();
alarmbutton = new AlarmButton();
}

public void Trigger(ReachTimeEventArgs e)
{
ReachTime(this,e);
}

public void Work()
{
while(time!=6)
{
time = time + 1;
}
ReachTimeEventArgs e = new ReachTimeEventArgs(this.time, this.place);
Trigger(e);
}
}

class Program
{
static void Main(string[] args)
{
Watch w = new Watch();
w.ReachTime += w.alarm.Belling;
w.ReachTime += w.alarmbutton.Press;
w.Work();

Console.Read();

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 委托 事件 示例 练习