1. 程式人生 > >C# λ運算子=>匿名方法 lambda表示式

C# λ運算子=>匿名方法 lambda表示式

Lambda 表示式是一個匿名函式,是C# 3.0引入的新特性。Lambda 運算子=>,該運算子讀為“goes to”。C#為委託提供一種機制,可以為委託定義匿名方

法,匿名方法沒有名稱,編譯器會定指定一個名稱。匿名方法中不能使用跳轉語句跳轉到該匿名方法的外部,也不能跳轉到該方法的內部。也不能在匿名方法外部

使用的ref和out引數。

下面的程式碼簡單的演示了Lambda表示式:

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

namespace Lambda
{
    class Program
    {
        //委託方法
        delegate string MyDelagate(string val);

        static void Main(string[] args)
        {
            string str1 = "匿名方法外部\n";

            //中括號部分定義了一個方法,沒有名稱,編譯器會自動指定一個名稱  
            MyDelagate my = (string param) =>
            {
                string str2 = "匿名方法內部\n";
                return(param + str1 + str2);
            };

            //呼叫委託的匿名方法  
            Console.WriteLine(my("引數\n"));

            //從結果可以看到,匿名方法同樣達到了為委託定義實現體方法的效果  
            Console.Read();
        }  
    }
}

λ運算子 =>

左邊是引數,使用括號表達 (string param),

右邊是實現程式碼,使用花括號,如果程式碼只有一行,則不使用花括號和return關鍵字也可以,編譯器會為我們新增。

這是λ表示式的簡單實現:

string str1 = " 匿名方法外部 ";
string str2 = " 匿名方法內部 ";
MyDelagate my = param => param + str1 + str2;
Console.WriteLine(my(" 引數 "));

1個引數:
private delegate int MyDelagate(int i);

MyDelagate test1 = x => x * x;
MyDelagate test2 = (x) => x * x;
MyDelagate test3 = (int x) => x * x;
MyDelagate test4 = (int x) => { return x * x; };

Console.WriteLine(test1(10));
Console.WriteLine(test2(10));
Console.WriteLine(test3(10));
Console.WriteLine(test4(10));

2個或多個引數:兩個或者多個引數不能使用簡略的方式書寫,必須使用小括號宣告引數。
private delegate int MyDelagate(int x, int y);

MyDelagate test1 = (x, y) => x * y;
MyDelagate test2 = (int x, int y) => x * y;
MyDelagate test3 = (int x, int y) => { return x * y; };

Console.WriteLine(test1(3,4));
Console.WriteLine(test2(3,4));
Console.WriteLine(test3(3,4));

無引數:
 private delegate void Void();       

 void test11 = () => { Console.WriteLine("Void Params"); };
 test11();