c#委托学习2

   delegate int  Modelegate(string src ,int std);    //定义一个有两个参数,返回一个int类型的参数的委托。

//再定义一个方法,这个方法要和定义的委托一样

public static int Mo(string cl,int dl)
{
  Console.WriteLine("我是委托{0},{1}",cl,dl);


    return 10;
}

//调用委托,

static void Main(string[] args)
{
Modelegate write = new Modelegate(Mo);  new一个委托,传一个方法名,这个传入的方法要和委托定义一样;

    int dd= write("徐周", 20);           


    Console.WriteLine("aaa{0}", dd);
   Console.ReadKey();

}

  事件学习

   

public delegate void Doipoa();  //定义一个委托

public class ipoa   //定义一个类
{
   public event Doipoa mo;  定义一个事件,和委托一样,事件就是在前面加一个event,


  public void Getchong()      //一个播放音乐的方法,
  {
   Console.WriteLine("开始播放音乐,,,,,,,,,");  

    if (mo != null)
   {
   mo();
    }
  }

public void Getding()
{
Console.WriteLine("停止播放音乐,,,,,,,,");
}
public void Befong()
{
Console.WriteLine("播放下一首音乐.,,,,,,,,");
}
}

  // 调用事件

   

class Program
{
static void Main(string[] args)
{
   ipoa ipoas = new ipoa();   
   ipoas.mo+=new Doipoa(Mo);  //调用事件是时候是+=一个委托类型


    ipoas.Getchong();    然后调用播放音乐的方法

Console.ReadKey();

}

public static void Mo()   //定义一个委托方法,
{
Console.WriteLine("好日子,好日子");



}

}

原文地址:https://www.cnblogs.com/xu3593/p/3041333.html