.NET 3.5 / C# 3.0 引入多項 VB 不支援的語法特性,大幅提升開發效率與程式碼表達力。本文詳細介紹自動屬性、集合初始化器、物件初始化器、多行 Lambda、匿名型別等 C# 獨有功能。
編譯器自動產生背景欄位,減少樣板程式碼。
// 基本形式
public int Id { get; set; }
// 存取層級差異
public string Name { get; private set; } // 唯讀對外
public DateTime CreatedAt { get; init; } // C# 9.0:僅初始化可設定
// C# 6.0+:自動屬性初始化
public int MaxRetryCount { get; set; } = 3;
// C# 7.0+:唯讀自動屬性(建構函數指派)
public Guid CorrelationId { get; } = Guid.NewGuid();
任何實作 IEnumerable 且有 Add 方法的型別均可使用。
// List
var names = new List { "Alice", "Bob", "Charlie" };
// Dictionary
var scores = new Dictionary
{
["Alice"] = 95,
["Bob"] = 87,
["Charlie"] = 92
};
// HashSet
var uniqueTags = new HashSet { "csharp", "dotnet", "linq" };
// 自訂類別(需實作 IEnumerable 並有 Add 方法)
public class MyCollection : IEnumerable
{
private List _items = new();
public void Add(string item) => _items.Add(item);
public IEnumerator GetEnumerator() => _items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
// 使用
var custom = new MyCollection { "A", "B", "C" };
var person = new Person
{
Name = "Alice",
Age = 28,
Address = new Address { City = "Taipei", Zip = "100" },
Skills = new List { "C#", "SQL" }
};
// 等同於:
// var person = new Person();
// person.Name = "Alice";
// person.Age = 28;
// ...
VB 僅支援單行 Lambda,C# 完整支援陳述式區塊。
// 多行 Lambda(需大括號與 return)
Func calculate = (x, y) =>
{
var sum = x + y;
var product = x * y;
Console.WriteLine($"Sum: {sum}, Product: {product}");
return sum + product;
};
// 事件處理
button.Click += (sender, e) =>
{
Log.Info("Button clicked");
UpdateUI();
await SaveAsync();
};
// LINQ 中使用
var result = items.Where(item =>
{
if (!item.IsValid) return false;
var score = CalculateScore(item);
return score > Threshold;
});
var product = new { Id = 1, Name = "Laptop", Price = 29999 };
Console.WriteLine(product.Name); // 唯讀屬性
// LINQ 投影常用
var summary = orders.Select(o => new
{
o.OrderId,
CustomerName = o.Customer.Name,
Total = o.Items.Sum(i => i.Price * i.Quantity)
});
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string str)
=> string.IsNullOrWhiteSpace(str);
public static string ToTitleCase(this string str)
=> CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
// 使用
" hello world ".IsNullOrWhiteSpace(); // false
"hello world".ToTitleCase(); // "Hello World"
public class Calculator
{
// 方法
public int Add(int a, int b) => a + b;
// 屬性
public double Pi => Math.PI;
// 建構函數 (C# 7.0+)
public Calculator(int initialValue) => _value = initialValue;
// 解構函式 (C# 7.0+)
public void Deconstruct(out int x, out int y) => (x, y) = (_value, _value * 2);
}
這些 C# 獨有特性不只是語法糖,更能:
建議團隊制定編碼規範,全面採用這些現代 C# 特性,淘汰舊式冗長寫法。