C#委派delegate教學

如下圖所示使用者如果想將子視窗Textbox所接收到的資料,在父視窗TextBox上顯示該怎麼去執行呢?這時候就需要使用委派 delegate的手法才可以實現,因此本篇文章小編要分享 C#委派delegate教學 。

C#委派delegate教學

  程式範例如下: 

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 FormCtrl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            /* 將委派綁定寫在form2建構之後 */
            Form2 form2 = new Form2();
            form2.CallReceive += new Form2.EventReceive(seetText);
            form2.Show();
        }
 
        /* 需讓其它class執行的方法 ex:傳入form2的textbox的值寫入Form1的textbox */
        public void seetText(string tmp)
        {
            textBox_setvalue.Text = tmp;
        }
    }
}

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 FormCtrl
{
    public partial class Form2 : Form
    {
        /* 宣告事件建立名為 EventReceive 的委派 讓Form2 可以使用 Form1的方法*/
        public delegate void EventReceive(string tmp);
        /* 把這委派產生成物件 */
        public EventReceive CallReceive;  
 
        public Form2()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            if (CallReceive != null)
            {
                CallReceive(textBox_getValue.Text);
            }
        }
    }
}

延伸閱讀:

C#常用的特殊字元

C#倒數計時器範例教學

C#文字亂碼解碼教學

C#泛型Generics教學

C#使用StreamReader與StreamWrite來讀寫文件

發佈留言