1. 程式人生 > >委托的N種寫法,你喜歡哪種?

委托的N種寫法,你喜歡哪種?

spa his gif 方法 泛型 copy sta line urn

一、委托調用方式

1. 最原始版本:

技術分享圖片
    delegate string PlusStringHandle(string x, string y);
    class Program
    {
        static void Main(string[] args)
        {
            PlusStringHandle pHandle = new PlusStringHandle(plusString);
            Console.WriteLine(pHandle("abc", "edf"));

            Console.Read();
        }

        static string plusString(string x, string y)
        {
            return x + y;
        }
    }
技術分享圖片

2. 原始匿名函數版:去掉“plusString”方法,改為

            PlusStringHandle pHandle = new PlusStringHandle(delegate(string x, string y)
            {
                return x + y;
            });
            Console.WriteLine(pHandle("abc", "edf"));

3. 使用Lambda(C#3.0+),繼續去掉“plusString”方法(以下代碼均不再需要該方法)

            PlusStringHandle pHandle = (string x, string y) =>
            {
                return x + y;
            };
            Console.WriteLine(pHandle("abc", "edf"));

還有更甚的寫法(省去參數類型)

            PlusStringHandle pHandle = (x, y) =>
            {
                return x + y;
            };
            Console.WriteLine(pHandle("abc", "edf"));

如果只有一個參數

技術分享圖片
        delegate void WriteStringHandle(string str);
        static void Main(string[] args)
        {
            //如果只有一個參數
            WriteStringHandle handle = p => Console.WriteLine(p);
            handle("lisi");

            Console.Read();
        }
技術分享圖片

二、委托聲明方式

1. 原始聲明方式見上述Demo

2. 直接使用.NET Framework定義好的泛型委托 Func 與 Action ,從而省卻每次都進行的委托聲明。

技術分享圖片
        static void Main(string[] args)
        {
            WritePrint<int>(p => Console.WriteLine("{0}是一個整數", p), 10);

            Console.Read();
        }

        static void WritePrint<T>(Action<T> action, T t)
        {
            Console.WriteLine("類型為:{0},值為:{1}", t.GetType(), t);
            action(t);
        }
技術分享圖片

3. 再加上個擴展方法,就能搞成所謂的“鏈式編程”啦。

技術分享圖片
    class Program
    {   
        static void Main(string[] args)
        {
            string str = "所有童鞋:".plusString(p => p = p + " girl: lisi、lili\r\n").plusString(p => p + "boy: wangwu") ;
            Console.WriteLine(str);

            Console.Read();
        }
    }

    static class Extentions
    {
        public static string plusString<TParam>(this TParam source, Func<TParam, string> func)
        {
            Console.WriteLine("字符串相加前原值為:{0}。。。。。。", source);
            return func(source);
        }
    }
技術分享圖片

看這個代碼是不是和我們平時寫的"list.Where(p => p.Age > 18)"很像呢?沒錯Where等方法就是使用類似的方式來實現的。

委托的N種寫法,你喜歡哪種?