今天玩了玩C/S开发,也随便练习了很久不用的委托
父窗体中写的代码
#region 委托与事件传递
public delegate void TextChangedHandler(string s);
public class CallObject {
//用来存放子窗体返回的结果
public string ResultValue = "";
//定义事件对象 可以让子窗体修改父窗体的状态
public event TextChangedHandler SelTextChanged;
//以调用delegate的方式触发函数
public void ChangeSelText(string s)
{
if (SelTextChanged != null)
{
//调用delegate
SelTextChanged(s);
}
}
}
#endregion
void co_SelTextChanged(string s)
{
textBox2.Text = s;
}
private void button3_Click(object sender, EventArgs e)
{
CallObject co = new CallObject();
co.SelTextChanged += new TextChangedHandler(co_SelTextChanged);
Form3 f3 = new Form3(co);
f3.ShowDialog();
textBox2.Text = "测试结果" + co.ResultValue;
}
子窗体中写的代码
public Form3(CallObject cov) : this() { this.co = cov; }
private void button1_Click(object sender, EventArgs e)
{
co.ResultValue = textBox1.Text;
Close();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
co.ChangeSelText("A");
}
private void radioButton2_CheckedChanged_1(object sender, EventArgs e)
{
co.ChangeSelText("B");
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
co.ChangeSelText("C");
}
结果