delegate实例

来源:互联网 发布:centos 7 安装 编辑:程序博客网 时间:2024/06/05 22:49

delegate就是调用其他类中的方法。

 

使用Delegate的方法:

using System;

using System.Threading;

 

public class Student

{

 

     private int score;

 

     public void SetScore(int value)

     {

         if (value > 100 || value < 0)

         {

              Console.Out.WriteLine("分数不对");

         }

         else

         {

              score = value;

              if (AdviseDelegateInstance!= null)

              {

                   string result=AdviseDelegateInstance(score);

                   Console.Out.WriteLine("学生收到老师返回的结果/t"+result);

              }

         }

     }

 

     public  delegate string AdviseDelegate(int score);

        

     public AdviseDelegate AdviseDelegateInstance;

}

 

public class Teacher

{

     public string Advise(int score)

     {

         if(score<60)

         {

              Console.Out.WriteLine(score+"老师说加油");

              return "不及格";

         }

         else

         {

              Console.Out.WriteLine(score+"老师说不错");

              return "及格";

         }

     }

}

 

class MainClass

{

     [STAThread]

     static void Main(string[] args)

     {

         Teacher teacher=new Teacher();

         Student s=new Student();

 

         s.AdviseDelegateInstance=new Student.AdviseDelegate(teacher.Advise);

        

         Console.Out.WriteLine("学生得到50");

         s.SetScore(50);

 

         Console.Out.WriteLine("/n学生得到75");

         s.SetScore(75);

 

         Console.ReadLine();

     }

}

原创粉丝点击