委托delegate的学习

委托五步法 -----------委托,其实委托的是方法
【1】声明委托
【2】方法编写
【3】创建委托变量
【4】关联委托方法
【5】使用委托变量

【1】public void delegate recMsg(string msg )
【2】 private void recmsg(string data){ .... }
【3】 public recMsg rec;
【4】 rec+= recmsg
【5】 rec("data");

//主窗体

public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}

    //【3】创建委托变量(私有化)
    private ReceiveDelegate receivgMsg = null;  
 
    private void btnCreateChild_Click(object sender, EventArgs e)
    {
        for (int i = 1; i < 4; i++)
        {
            FrmChild frm = new FrmChild(i);
            frm.Show();

            //【4】关联委托变量和方法
            this.receivgMsg += frm.ReceiveMsg; //这里必须使用+=!!!!!!
            frm.recMsg += RecMsg;
        }
    }

    //广播消息
    private void btnSend_Click(object sender, EventArgs e)
    {
        //【5】使用委托变量
        receivgMsg(this.txtSendMsg.Text.Trim());
    }
    
    private void RecMsg(string msg) 
    {
        this.txtContent.AppendText($"【{ DateTime.Now.ToString("HH:mm:ss")}】 接收:{msg}\r\n") ;
    }
}

//子窗体

public partial class FrmChild : Form
{
public ReceiveDelegate recMsg { get; set; }

    public FrmChild(int num)
    {
        InitializeComponent();
        this.Text += $"  [{num}]";
    }

    //【2】编写具体方法(公有化)
    public void ReceiveMsg(string data)
    {
        this.txtContent.Text += $"【{ DateTime.Now.ToString("HH:mm:ss")}】发送{data}\r\n";
    }  
 
    private void btnSend_Click(object sender, EventArgs e)
    {
        recMsg($"【{this.Text.Trim()}】{this.txtSendMsg.Text.Trim()}");
    }
}
posted @ 2025-09-02 15:30  $虫虫$  阅读(3)  评论(0)    收藏  举报