擴充套件方法作為強型別包裝器

擴充套件方法可用於為類字典物件編寫強型別包裝器。比如一個快取,HttpContext.Items 在 cetera …

public static class CacheExtensions
{
    public static void SetUserInfo(this Cache cache, UserInfo data) => 
        cache["UserInfo"] = data;

    public static UserInfo GetUserInfo(this Cache cache) => 
        cache["UserInfo"] as UserInfo;
}

這種方法消除了在整個程式碼庫中使用字串文字作為鍵的需要,以及在讀取操作期間需要轉換為所需型別的需要。總的來說,它建立了一種更安全,強型別的方式來與諸如字典之類的鬆散型別的物件進行互動。