首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 3.0 入門【Lambda 表達式】第四章(四):參數型別必須顯式宣告的情況與空 Lambda 寫法

     編輯:關於C語言

多載解析失敗:必須指定參數型別

delegate int delegate1(int x);
delegate int delegate2(string s);

static void Sample(delegate1 method) { Console.WriteLine("delegate1"); }
static void Sample(delegate2 method) { Console.WriteLine("delegate2"); }

static void Main()
{
    Sample((int x) => 0);     // OK:指定 int,匹配 delegate1
    // Sample((x) => 0);     // 編譯錯誤:無法推斷 x 型別,兩個多載皆滿足
}

當多載方法參數型別不同時,Lambda 參數必須顯式宣告型別以協助編譯器多載解析。

空 Lambda 表達式寫法總結

  • 無回傳值(void):(x) => { } 或 () => { }
  • 有回傳值:() => default(T) 或 () => null(參考型別)

核心概念:不要用 null 表示「什麼都不做」,要用空 Lambda 表達式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved