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

C# 3.0 入門【Lambda 表達式】第四章(五):空 Lambda 表達式——替代 null 的無操作委派模式

     編輯:關於C語言

用 null 表示「無操作」的缺點

class Program
{
    static void Sample(Action<string> action)
    {
        if (action != null) action("Hello!");
    }
    static void Main()
    {
        Action<string> action = null;
        Sample(action); // 無輸出

        action = x => Console.WriteLine(x);
        Sample(action); // 輸出 Hello!
    }
}

需檢查 null,呼叫端與實作端皆增加防禦性代碼。

空 Lambda 表達式:什麼都不做的委派

Action<string> action = (x) => { }; // 空語句本體

static void Sample(Action<string> action)
{
    action("Hello!"); // 直接呼叫,無需 null 檢查
}
Sample(action); // 無輸出,不拋例外

action = x => Console.WriteLine(x);
Sample(action); // 輸出 Hello!

優點:消除 null 檢查,程式碼更簡潔,符合「空物件模式」精神。

實戰應用:自動化測試回放系統

回放使用者操作生成報表時,需禁用所有輸出相關處理以提升效率。將輸出委派設為空 Lambda () => { },無需在每個呼叫點加 if 判斷,原始碼保持乾淨,隨時可切換啟用/禁用。

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