-
</pre> 在委托中,单播委托就是只能调用一个方法;委托中还有另一种方法,改方法能够实现调用多个方法,称为多播委托,方式就是“+=”,实现调用多个方法,也可以用“-=”将固定方法去掉。下面接着上个文章,我们来实现多窗体的通信。<p></p><p>主窗体</p><pre name="code" class="csharp">namespace MoreContact
-
{
-
/// <summary>
-
/// 委托定义
-
/// </summary>
-
public delegate void MoreContactDelegate(string word);
-
public partial class FrmMain : Form
-
{
-
//声明委托
-
MoreContactDelegate Message;
-
public FrmMain()
-
{
-
InitializeComponent();
-
//窗体实例化
-
FrmOther1 f1 = new FrmOther1();
-
FrmOther2 f2 = new FrmOther2();
-
FrmOther3 f3 = new FrmOther3();
-
f1.Show();
-
f2.Show();
-
f3.Show();
-
-
//调用委托变量与方法联系到一起
-
Message = f1.Receive;
-
Message += f2.Receive;
-
Message += f3.Receive;
-
}
-
private string word;
-
//通过单击调用委托实现固定的方法
-
private void button1_Click(object sender, EventArgs e)
-
{
-
word = textBox1.Text;
-
Message(word);
-
}
-
-
private void button2_Click(object sender, EventArgs e)
-
{
-
word = "";
-
Message(word);
-
textBox1.Text = "";
-
}
-
}
-
}
从窗体1-3程序都是一样:
-
<pre name="code" class="csharp">namespace MoreContact
-
{
-
public partial class FrmOther1 : Form
-
{
-
public FrmOther1()
-
{
-
InitializeComponent();
-
}
-
//定义方法
-
public void Receive(string word)
-
{
-
textBox1.Text = word;
-
}
-
}