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

C# 實用技巧合集:枚舉解析、動態委托、匿名方法、索引器、Hashtable 迭代

     編輯:關於C#

前言

有些 C# 特性平時用得少,但關鍵時刻能寫出極其優雅的代碼。本文整理 5 個易被遺忘卻極具實戰價值的技巧。

1. Enum.Parse:字串直接轉枚舉值

避免寫冗長的 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"

2. Delegate.CreateDelegate:運行時動態綁定委托

根據字串方法名創建委托,配合反射實現插件式調用。

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,新增方法只需在類中添加,零修改調用端。

3. 匿名方法:內聯簡單邏輯

C# 2.0 引入,適用於「只用一次、邏輯極簡」的委托場景。

ActionDelegate d = delegate { Console.WriteLine("匿名方法執行"); };
d.Invoke();

// 現代寫法 (Lambda) 更簡潔
ActionDelegate d2 = () => Console.WriteLine("Lambda 也很香");

4. 索引器:像陣列一樣訪問對象

讓類支援 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。

5. Hashtable 迭代:DictionaryEntry 是關鍵

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)非泛型鍵值對遍歷

這些技巧不常用,但用對地方能瞬間化繁為簡。建議收藏備查。

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