日期:2014-05-18 浏览次数:21074 次
public class Student { public Student(string strName) { Name = strName; Score = 100; ChaoZuoYeCount = 0; IsChaoZuoYe = false; } public string Name { get; set; } public int Score { get; set; } public int ChaoZuoYeCount { get; set; } public bool IsChaoZuoYe { get; set; } public override string ToString() { string strSpilt = "\t"; StringBuilder sb = new StringBuilder(); sb.Append("Name: " + Name + strSpilt); sb.Append("Score: " + Score + strSpilt); sb.Append("ChaoZuoYeCount: " + ChaoZuoYeCount + strSpilt); return sb.ToString(); } } public delegate void WatchStudent(Student student); public class StudentLeader : Student { public StudentLeader(string strName) : base(strName) { } public WatchStudent WatchHandler { get; set; } public void Watch(Student student) { if (WatchHandler != null) { WatchHandler(student); } } } public class DelegateDemo { public void DoTest() { List<Student> students = new List<Student>() { new Student("Student A"), new Student("Student B"), new Student("Student C"), new Student("Student D"), new Student("Student E"), }; StudentLeader leader = new StudentLeader("Leader"); leader.WatchHandler = DoWatch; int testCount = 10; Random rand = new Random(); for (int i = 0; i < testCount; i++) { foreach (Student student in students) { if (rand.Next(1, 10) % 2 == 0) { student.IsChaoZuoYe = true; } leader.Watch(student); } } Console.ReadKey(); } public void DoWatch(Student student) { if (student == null) { return; } if (student.IsChaoZuoYe) { student.Score += 5; student.ChaoZuoYeCount++; } Console.WriteLine(student.ToString()); } }