委托类似于函数指针,但函数指针只能引用静态方法,而委托既能引用静态方法,也能引用实例方法。

委托使用分三步:1、委托声明;2、委托实例化;3、委托调用。

代码
namespace First
{
delegate int Num(int one, int b); //第一步:委托声明
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Form1 form
= new Form1();
Num num
= new Num(form.Add); //委托实例化,注意参数是要使用的参数名,且不带括号
MessageBox.Show(num(1, 2) + ""); //委托调用
}

private int Add(int num1,int num2)
{
return (num1+num2);
}
}

}

 

相关文章:

  • 2021-07-04
  • 2022-12-23
  • 2021-12-02
  • 2022-02-10
  • 2021-12-30
  • 2022-12-23
猜你喜欢
  • 2021-12-13
  • 2022-02-17
  • 2021-06-21
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案