2016年3月29日 星期二

C# 已經建立的類別.cs之間傳值的方法 (也適用於Form 互相傳遞值 )

寫程式時有可能會發生以下情況:

當建立好一個類別A之後,之後的程式產生類別B,之後需要將"類別B"的值 傳給"類別A",雖然類別B是由A所產生,但是不知該如何將值回應給A做處理 (ex:A產生大量的Thread 類別B 最後 類別B的結果回傳給A)

此時可以使用Event Delegate的方式 建構類別A可接收資料的方法,並且在類別B產生一個呼叫Delegate的事件回應給類別A

程式碼大致如下:
分成1. Form1 2.Form2


//================Form1 設計畫面:




//================Form1.cs
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 TransFormExample
{
    /// <summary>
    /// 說明:將資料從別的類別取得,先建構子類別的Delegate
    /// ※目前為單向,如果要由Form1 傳值給Form2
    ///        雙向:1.可以依照相同的方法在Form2進行接收Form1的資料
    ///    
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //Form2 變數名稱
        Form2 ReturnCallback = new Form2();

        private void button_Form1_Click(object sender, EventArgs e)
        {
            //顯示Form2
            ReturnCallback.Show();
        }

        private void Data(string GetStream)
        {
            //將傳回的字串放進
            this.Form1_textBox.AppendText(GetStream);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //讓MyMailWork掛載事件回傳Identifier的事件
            ReturnCallback.ReturnCallback += new Form2.ReturnDelegate(this.Data);
        }
    }
}


//================Form2設計畫面:




//================Form2.cs:
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 TransFormExample
{
    public partial class Form2 : Form
    {
        //提供給主類別存放委派事件的位址
        public delegate void ReturnDelegate(string Stream);
        //回傳給主類別事件
        public event ReturnDelegate ReturnCallback;

        public Form2()
        {
            InitializeComponent();
        }

        private void button_Form2_Click(object sender, EventArgs e)
        {
            ReturnCallback(this.Form2_textBox1.Text);
        }
    }
}



範例程式下載  Visual 2010 windows form 程式 :

https://drive.google.com/file/d/0B42wM6w1VZR7bmVXcnVETENQNEE/view?usp=sharing

沒有留言:

張貼留言