C#中委托的使用

  1. 在类中声明一个委托(关键字 delegate ,类似于定义了一个抽象函数):  public delegate int Add(int m, int n);
  2. 定义它的实例,如a:public Add a;
  3. 在使用它的类中具体实现并进行关联:例如Add声明及实例化是在类C中,则在使用的它的类如Form1类中具体写个方法实现,并做好映射
  4. 在事件中使用,若实例未具体实现则为null
class C
{
//声明委托
  public delegate int Add(int m,int n);
//实例化委托
 public Add add;

 //事件中使用
private void button_Click(object sender, EventArgs e)
        {
            if(add==null)
            {
                MessageBox.Show("doctor die");
            }
            else {
                MessageBox.Show(add(1, 2).ToString());
            }
        }
}

class Form
{
   //实现
   public int  function(int m,int n)
  {
     return m+n;
  } 
   
  //关联
  C  c = new C();
  c.add = this.function;

  
}

猜你喜欢

转载自blog.csdn.net/weixin_42731241/article/details/81144073