1. 程式人生 > >C# 進階(一)Lambda 表示式

C# 進階(一)Lambda 表示式

Lambda 表示式是一種可用於建立委託或表示式目錄樹型別的匿名函式。通過使用 lambda 表示式,可以寫入可作為引數傳遞或作為函式呼叫值返回的本地函式。 Lambda 表示式對於編寫 LINQ 查詢表示式特別有用。若要建立 Lambda 表示式,需要在 Lambda 運算子 => 左側指定輸入引數(如果有),然後在另一側輸入表示式或語句塊。例如,lambda 表示式 x => x * x 指定名為 x 的引數並返回 x 的平方值

using System;

namespace NewAttr
{
    /// <summary>
    /// Lambda 表示式是一種可用於建立委託或表示式目錄樹型別的匿名函式。
    /// Lambda 表示式對於編寫 LINQ 查詢表示式特別有用。
    /// </summary>
    public class LambdaDemo
    {
        public LambdaDemo() { }
        /// 委託不能過載,即委託名稱相同,引數型別,個數不同。
        /// 構造委託的時候,根本不管引數,當然也就不知道你要構造的是哪個委託。
        private delegate int del(int x);
        private delegate int del2(int x, int s);
        private delegate void del3();
        public static void Test()
        {
            del myDel1 = x => x * x;
            del myDel2 = (x) => x * x;
            del myDel3 = (x) => x * x;
            del myDel4 = (int x) => x * x;
            del myDel5 = (int x) => { return x * x; };
            Console.WriteLine("del myDel1 = x => x * x :{0}", myDel1(2));
            Console.WriteLine("del myDel2 = (x) => x * x :{0}", myDel2(2));
            Console.WriteLine("del myDel3 = (x) => x * x :{0}", myDel3(2));
            Console.WriteLine("del myDel4 = (int x) => x * x :{0}", myDel4(2));
            Console.WriteLine("del muDel5 = (int x) =>{1}:{0}", myDel5(2), " { return x * x; } ");
            del3 myDel6 = () => Test2();
            Console.WriteLine("--------------------------------");
            myDel6();
        }

        public static void Test2()
        {
            del2 myDel2 = (x, y) => x * y;
            del2 myDel3 = (int x, int y) => x * y;
            del2 myDel4 = (int x, int y) => { return x * y; };
            Console.WriteLine("del2 myDel2 = (x, y) => x * y :{0}", myDel2(2, 2));
            Console.WriteLine("del2 myDel3 = (int x, int y) => x * y :{0}", myDel3(2, 2));
            Console.WriteLine("del2 myDel4 = (int x, int y) => {1} :{0}", myDel4(2, 2), "{ return x * y; }");
            Console.WriteLine("--------------------------------");
            FunTest();
        }

        public static void FunTest()
        {
            ///其中 Func 是最多具有十六個輸入引數的任何一個 Func 委託
            ///之後一個為返回值。
            ///Func<TResult>,Func<T,TResult>,Func<T,.....T,TResult>
            Func<int> myFunc = () => 1;
            Console.WriteLine("Func<int> myFunc = () => 1 :{0}", myFunc());
            Func<int, string, int> myFunc2 = (x, y) => x + y.Length;
            Console.WriteLine("Func<int, string, int> myFunc = (x, y) => x + y.Length :{0}", myFunc2(1, "jasonhua"));

            ///其中 Action 是最多具有十六個輸入引數的任何一個 Action 委託
            Action myAction = () => { Console.WriteLine("Action myAction :1 * 1"); };
            myAction();
            Action<int, int> myAction2 = (x, y) => { Console.WriteLine("Action<int, int> myAction2 = (x, y) :{0}", x * y); };
            myAction2(1,1);
        }
    }
}