委托 event Action<string>/event Action 的使用

1、event Action<string>  实现FormA打开FormB,FormB的值 回传到FormA上

FormA的代码:

private void button1_Click(object sender, EventArgs e)
{
FrmB frm = new FrmB();
frm.SendText += Frm_SendText;
frm.ShowDialog();
}

private void Frm_SendText(string obj)
{
label1.Text = obj.ToString();
MessageBox.Show(label1.Text);
}

FormB的代码:

public event Action<string> SendText;

private void button1_Click(object sender, EventArgs e)
{
////方式1
//if (SendText != null)
//{
// SendText(textBox1.Text);
//}
//方式2
SendText?.Invoke(textBox1.Text);
}

 

 

 

2、event Action   实现FormA打开FormB,FormB点击按钮后,FormA提示点击按钮

FormA代码:

private void button1_Click(object sender, EventArgs e)
{
FrmB frm = new FrmB();
frm.SendText += Frm_SendText;
frm.ShowDialog();
}

private void Frm_SendText()
{
label1.Text = "窗体2点击了 回传FrmA按钮";
MessageBox.Show("窗体2点击了 回传FrmA按钮");
}

FormB代码:

public event Action SendText;

private void button1_Click(object sender, EventArgs e)
{

//方式1等同于方法2
if (SendText != null)
{
SendText();
}
////方式2
//SendText?.Invoke();


}

 

posted @ 2021-08-31 16:51  一叶孤城  阅读(1058)  评论(1)    收藏  举报