C#“委託”學習筆記

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateTest
{
    public class test
    {
        static void Main(string[] args)
        {
            Class1 c = new Class1();

            //用new操作把委託與一個方法關聯
            SayHello sh = new SayHello(c.SayHelloMethod);
            Console.WriteLine(sh("Wang"));

            //用等號把委託與一個方法關聯
            SayHello sh2 = c.SayHelloMethod;
            Console.WriteLine(sh2("Liu"));

            //委託與一個匿名方法關聯
            SayHello sh3 = delegate(string var)
            {
                Console.WriteLine("sh3!");
                return var + ",how are you?";
            };
            Console.WriteLine(sh3("Jiang"));

            //組合委託,此時委託就能夠依次執行多個方法
            NumberHandle nh = new NumberHandle(c.DoubleNumber);
            NumberHandle nh2 = c.TrebleNumber;
            NumberHandle nh3 = nh + nh2;
            int num = 2;
            nh3(ref num);
            Console.WriteLine(""+num);

            //組合委託,若委託的方法有返回值,則返回值爲最後一個被執行方法的返回值
            SayHello sh4 = sh + sh3;
            Console.WriteLine(sh4("Zheng"));

            //lambda表達式:另一種把委託與匿名方法關聯起來的方法
            SayHello sh5 = var => var + ",Hello lambda";
            Console.WriteLine(sh5("Guo"));

            Console.ReadLine();
        }
    }

    delegate string SayHello(string val);

    delegate void NumberHandle(ref int num);

    class Class1
    {
        public string SayHelloMethod(string name)
        {
            Console.WriteLine("SayHello Method!");
            return name + ",Hello!";
        }

        public void DoubleNumber(ref int num)
        {
            Console.WriteLine("Double it!");
            num *= 2;
        }

        public void TrebleNumber(ref int num)
        {
            Console.WriteLine("Treble it!");
            num *= 3;
        }

    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章