有些 C# 特性平時用得少,但關鍵時刻能寫出極其優雅的代碼。本文整理 5 個易被遺忘卻極具實戰價值的技巧。
避免寫冗長的 switch/if-else 映射。
enum WeekDay { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
Console.Write("輸入星期: ");
string input = Console.ReadLine(); // "mon"
WeekDay day = (WeekDay)Enum.Parse(typeof(WeekDay), input, true); // true = 忽略大小寫
Console.WriteLine($"枚舉值: {day} = {(int)day}"); // Mon = 1
反向操作:Enum.GetName(typeof(WeekDay), 1) → "Mon"
根據字串方法名創建委托,配合反射實現插件式調用。
delegate void ActionDelegate();
class Processor
{
public void Start() => Console.WriteLine("啟動");
public void Stop() => Console.WriteLine("停止");
}
var proc = new Processor();
Console.Write("輸入方法名: ");
string methodName = Console.ReadLine(); // "Start"
var action = Delegate.CreateDelegate(typeof(ActionDelegate), proc, methodName + "Method", true) as ActionDelegate;
action?.Invoke(); // 輸出: 啟動
優勢:無需 switch,新增方法只需在類中添加,零修改調用端。
C# 2.0 引入,適用於「只用一次、邏輯極簡」的委托場景。
ActionDelegate d = delegate { Console.WriteLine("匿名方法執行"); };
d.Invoke();
// 現代寫法 (Lambda) 更簡潔
ActionDelegate d2 = () => Console.WriteLine("Lambda 也很香");
讓類支援 obj[index] 語法,封裝集合存取邏輯。
class NameContainer
{
private List<string> _names = new List<string>();
public string this[int index]
{
get => _names[index];
set
{
if (index == _names.Count) _names.Add(value); // 自動擴容
else _names[index] = value;
}
}
}
var nc = new NameContainer();
nc[0] = "微軟"; nc[1] = "谷歌"; nc[2] = "百度";
for (int i = 0; i < 3; i++) Console.WriteLine(nc[i]);
注意:索引器不支援 foreach,需實現 IEnumerable。
Hashtable 存的是鍵值對,迭代變量類型是 DictionaryEntry,而非 Key 或 Value。
var table = new Hashtable();
table["name1"] = "微軟";
table.Add("name2", "谷歌");
table["name3"] = "百度";
foreach (DictionaryEntry entry in table)
{
Console.WriteLine($"{entry.Key}: {entry.Value}");
}
// 輸出:
// name1: 微軟
// name2: 谷歌
// name3: 百度
原理:Hashtable 內部以 DictionaryEntry 結構體存儲 Key/Value,實現了索引器 this[object key]。
| 技巧 | 核心 API | 適用場景 |
|---|---|---|
| 枚舉解析 | Enum.Parse / Enum.GetName | 配置字串轉強類型枚舉 |
| 動態委托 | Delegate.CreateDelegate | 插件調用、字串路由分發 |
| 匿名方法 | delegate / Lambda | 一次性簡單回調 |
| 索引器 | this[int index] | 集合封裝、陣列式訪問 |
| Hashtable 迭代 | foreach (DictionaryEntry) | 非泛型鍵值對遍歷 |
這些技巧不常用,但用對地方能瞬間化繁為簡。建議收藏備查。