初学者在开始学习的时候,对于委托很难做到一下子理解,其中也包括我。委托好比一座大山,没爬上山顶就不能有“一览众山小”的感觉,只有你真正的爬到山顶的时候,才会发现大自然的是神奇。
委托我们可以把它认为是一个类,而不是一个方法。用委托我们可以调用方法,来简化程序,非常像C++中的指针。
使用委托的一般步骤为:
(1)定义委托,delegate 返回值类型 委托类型名称(参数列表);
(2)声明方法;
(3)实例化委托,注意声明的类型要和方法中的类型一样。
下面给出例子,利用委托创建窗体单向通信:
这是主窗体的程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _561
{
public partial class Form1 : Form
{
public ContactDelegate message;
public Form1()
{
InitializeComponent();
//从窗体实例化
FormOther1 form1 = new FormOther1();
form1.Show();
//调用委托
message +=form1.ReceiveDelegate;
}
private string word;
//单击发送按钮
private void zhudanji_Click(object sender, EventArgs e)
{
word = fswbk.Text;
message(word);
}
}
/// <summary>
/// 委托定义
/// </summary>
public delegate void ContactDelegate(string word);
}
注意委托的定义要在类的外面。
下面给子窗体的程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _561
{
public partial class FormOther1 : Form
{
public FormOther1()
{
InitializeComponent();
}
public void ReceiveDelegate(string word)
{
this.CCtwbk.Text = word;
}
}
}
运行结果:
子窗体和主窗体界面: