C# - 使用 Action 進行委派

摘要:C# - 使用 Action 進行委派

最近在熟悉 WinForm 時看到這樣的寫法「Action f_Process = () =>{ checkBox1.Checked = false; }」,感覺上似乎與 LINQ 有關,但長相跟 Delegate 相仿,但看到宣告的地方是「Action」就...,還是去翻翻 MSDN 好了。原來,從 2.0 開始,.NET Framework 就內建了 Action,還有提供了  Action<T>、Action<T, T>、Action<T, T, T> 與 Action<T, T, T, T>,這樣可省下 0 到 4 個參數的 delegate 宣告。以下就來試著實做看看...

畫面:


Code:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //將 Lambda 運算式指派給 Action 委派執行個體
            Action Act_Init_1 = () => {
                this.Text = "個人資料";
                checkBox1.Text = "男";
                checkBox1.Checked = true;
                label1.Text = "姓名:";
                textBox1.Text = "張小呆";
            };
            Act_Init_1();

            //匿名方法,使用 Action 委派
            DannyChang dcClass1 = new DannyChang("性別:", "女", "姓名:", "邱小胖");
            Action Act_Init_2 = delegate() { dcClass1.Execute(); };           
            Act_Init_2();

            //對 Action 委派執行個體化,而不是明確定義新委派並為其指派具名方法
            DannyChang dcClass2 = new DannyChang("性別:", "女", "姓名:", "張大媽");
            Action Act_Init_3 = dcClass2.Execute;
            Act_Init_3();

            //封裝有四個參數且沒有傳回值的方法
            Action<string, bool, string, string> Act_Init_5 = (x1, x2, x3, x4) => { SetControlItem(x1, x2, x3, x4); };
            Act_Init_5.Invoke("男", false, "姓名:", "邱小胖");
        }

        private void SetControlItem(string x1, bool x2, string x3, string x4)
        {
            checkBox2.Text = x1;
            checkBox2.Checked = x2;
            label2.Text = x3;
            textBox2.Text = x4;
        }

        public class DannyChang
        {
            private string GenderName;
            private string GenderValue;
            private string uName;
            private string uValue;

            public DannyChang(string strGenderName, string strGenderValue, string struName, string struValue)
            {
                this.GenderName = strGenderName;
                this.GenderValue = strGenderValue;
                this.uName = struName;
                this.uValue = struValue;
            }

            public void Execute()
            {
                MessageBox.Show(string.Format("{0}:{1}\r\n{2}{3}",
                    this.GenderName,
                    this.GenderValue,
                    this.uName,
                    this.uValue));
            }
        }
    }
}

結果:




參考:
Action 委派
Action<(Of <(T>)>) 委派
Action<(Of <(T1, T2>)>) 委派
Action<(Of <(T1, T2, T3>)>) 委派
Action<(Of <(T1, T2, T3, T4>)>) 委派
Action<T> and Func<T>
CODE-SetTimeout/ClearTimeout in C#
C# 參考:令人驚喜的泛型委託Predicate/Func/Action
匿名方法 (C# 程式設計手冊)
Lambda 運算式 (C# 程式設計手冊)