1. 类b 去委托类a去做某件事情
2.类b中声明委托,定义事件
3.在类a 中+=将类b与类a关联起来
实例:
首先建立
Form1 ,Form2窗体
Form2窗体通过事件调用Form1窗体的方法,获得值,传值等
Form2窗体中:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 委托2
{
public partial class Form2 : Form
{
//声明带参数的委托
public delegate string strDelegate(string words);
//定义事件
public event strDelegate strEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (showEvent != null)
{
//textBox1.text为委托的参数
//接受从form1中的参数
this.textBox2.Text = showEvent(this.textBox1.Text);
}
}
}
}
2.Form1 窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 委托2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Form2 的委托与Form1建立连接
Form2 f2 = new Form2();
f2.showEvent += new Form2.showdelegate(f2_showEvent);
f2.Show();
}
public string CountTime()
{
DateTime dt = DateTime.Now;
return dt.Second.ToString();
}
string f2_showEvent(string words)
{
//words 为from2传来的参数
this.textBox1.Text = words;
//调用form1的方法CountTime()
return "abc" + CountTime();
}
}
} |