C# - Lambda運算

Lambda可以更簡潔的方式進階使用delegate(委派)功能,是C#3.0之後提供的新功能。

Lambda以"=>"符號組成,語法如下: (input) => {expression}

延伸delegate(委派)內的範例,以Lambda運算:

public delegate void ShowMessage(string);
ShowMessage FunctionRef=(string message)=>{
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"alert","alert('"+message+"');",true);};
FunctionRef('Alert Message');
        
FunctionRef=(string message)=>{
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"confirm","confirm('"+message+"');",true);};
FunctionRef('Confirm Message');

FunctionRef=(string message)=>{
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"customMessage","customMessage('"+message+"');",true);};
FunctionRef('CustomMessage Message');

當delegate無輸入參數時,Lambda運算如下:

public delegate void HelloWorld();
HelloWorld FuncRef=()=>{Console.WriteLine("Hello World!")};

當Input參數只有一個參數時,允許不使用()包住輸入參數:

ShowMessage FunctionRef= message=>{
    this.ClientScript.RegisterClientScriptBlock(
        this.GetType(),"alert","alert('"+message+"');",true);};
FunctionRef('Alert Message');

出處

沒有留言:

橫式廣告