C# 2.0 引入泛型、匿名委托等特性,多借鑑 C++/Java 既有概念;而 C# 3.0 推出的 Lambda 表達式、LINQ、對象初始化器、var 等特性,則構建了獨特的聲明式、函數式編程能力,標誌著 C# 邁入現代語言第一方陣。
Lambda 表達式(=>)是匿名函數的簡潔語法,可隱式轉換為委托或表達式樹:
// C# 2.0 匿名委托
Func convert = delegate(string s) { return s.ToUpper(); };
// C# 3.0 Lambda
Func convert = s => s.ToUpper(); // 單參數可省略括號
// 多參數
Func add = (a, b) => a + b;
// 語句體
Action log = s => { Console.WriteLine(s); };
Expression<Func<T>> 時生成 AST,支撐 LINQ to SQL/IQueryable 遠端查詢轉譯。list.Where(x => x.Age > 18) 遠優於 delegate(int x) { return x.Age > 18; }。public class Student {
public string Name { get; set; }
public int Age { get; set; }
public string Class { get; set; }
}
// C# 2.0 繁瑣賦值
var s = new Student();
s.Name = "Brian"; s.Age = 21; s.Class = "1班";
// C# 3.0 一氣呵成
var s = new Student { Name = "Brian", Age = 21, Class = "1班" };
編譯器生成:調用無參構造函數 → 依次賦值屬性。無需為每種屬性組合編寫構造函數。
var students = new List {
new Student { Name = "A", Age = 18 },
new Student { Name = "B", Age = 19 }
};
實現 IEnumerable 且有 Add 方法的類型均支持(如 Dictionary:new Dictionary<int, string> { {1, "a"}, {2, "b"} })。
解決「SQL 查庫、XPath 查 XML、foreach 查內存」割裂問題:
private void BindGridView(string criteria) {
var db = new NorthwindDb(connStr);
IEnumerable results = string.IsNullOrEmpty(criteria)
? db.Employee.ToArray()
: (from e in db.Employee
where e.FirstName.Contains(criteria)
select e).ToArray();
GridView1.DataSource = results;
GridView1.DataBind();
}
關鍵點:查詢語法編譯為方法鏈(Where/Select),配合 Lambda 實現強類型、IntelliSense、編譯期檢查、自動映射。
var ≠ 動態類型。核心規則:
var x = 10;)。null(無類型信息)。var i = 10; i = "err"; 編譯失敗。int/string/int[])。// ✅ 匿名類型(必須用 var)
var anon = new { Name = "Edi", Age = 25 };
// ✅ LINQ 查詢結果類型冗長
var query = from c in customers where c.Orders > 10 select new { c.Name, c.Orders };
// ✅ foreach 迭代變量
foreach (var item in complexGenericCollection) { ... }
// ❌ 基礎類型降低可讀性
var i = 10; // 建議 int i = 10;
public static class StudentExtensions {
public static string GetInfo(this Student s) {
return $"Name: {s.Name}, Age: {s.Age}, Class: {s.Class}";
}
}
// 使用
var stu = new Student { Name = "Brian", Age = 12, Class = "1班" };
Console.WriteLine(stu.GetInfo()); // 如同實例方法
需 using 命名空間;優先級低於實例方法;不可破壞封裝(無法訪問 private 成員)。
C# 3.0 這組特性形成閉環:var + 匿名類型解決「中間結果無法聲明」;對象/集合初始化器解決「測試數據構建繁瑣」;Lambda 提供「內聯函數邏輯」;擴展方法為 IEnumerable<T> 注入查詢算子;LINQ 統一查詢語法。掌握它們,是邁向現代 C# 開發的必經之路。