日期:2014-05-18  浏览次数:21022 次

一道委托的题目
学生类
班长类继承学生类
班长负责巡查。
学生抄作业一次,扣5份,二次10分,以此类推。
学生存在一个list里面,抄作业的学生是随机的。
问用委托实现。

------解决方案--------------------
C# code

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());
        }
    }