2014-10-20 68 views
3

我有一個linq查詢,我將返回一個Dictionary<int, string>。我有一個重載的緩存方法,我已經創建了這個方法,它會將Dictionary<T,T>項目作爲參數之一。我在這門課有其他一些方法,其中List<T>T[]沒有問題。但是這一個方法,拒絕用線程主題的錯誤信息進行編譯。無法從使用情況推斷方法的類型參數。嘗試明確指定類型參數

這是我的緩存類代碼:

public static bool AddItemToCache<T>(string key, Dictionary<T, T> cacheItem, DateTime dt) 
{ 
    if (!IsCached(key)) 
    { 
     System.Web.HttpRuntime.Cache.Insert(key, cacheItem, null, dt, TimeSpan.Zero); 

     return IsCached(key); 
    } 

    return true; 
} 

public static bool AddItemToCache<T>(string key, Dictionary<T, T> cacheItem, TimeSpan ts) 
{ 
    if (!IsCached(key)) 
    { 
     System.Web.HttpRuntime.Cache.Insert(key, cacheItem, null, Cache.NoAbsoluteExpiration, ts); 

     return IsCached(key); 
    } 

    return true; 
} 

,這是無法編譯LINQ查詢:

private Dictionary<int, string> GetCriteriaOptions() 
{ 
    Dictionary<int, string> criteria = new Dictionary<int, string>(); 
    string cacheItem = "NF_OutcomeCriteria"; 

    if (DataCaching.IsCached(cacheItem)) 
    { 
     criteria = (Dictionary<int, string>)DataCaching.GetItemFromCache(cacheItem); 
    } 
    else 
    { 
     Common config = new Common(); 
     int cacheDays = int.Parse(config.GetItemFromConfig("CacheDays")); 

     using (var db = new NemoForceEntities()) 
     { 
      criteria = (from c in db.OutcomeCriterias 
         where c.Visible 
         orderby c.SortOrder ascending 
         select new 
         { 
          c.OutcomeCriteriaID, 
          c.OutcomeCriteriaName 
         }).ToDictionary(c => c.OutcomeCriteriaID, c => c.OutcomeCriteriaName); 

      if ((criteria != null) && (criteria.Any())) 
      { 
       bool isCached = DataCaching.AddItemToCache(cacheItem, criteria, DateTime.Now.AddDays(cacheDays)); 

       if (!isCached) 
       { 
        ApplicationErrorHandler.LogException(new ApplicationException("Unable to cache outcome criteria"), 
         "GetCriteriaOptions()", null, ErrorLevel.NonCritical); 
       } 
      } 
     } 
    } 

    return criteria; 
} 

這行=的isCached ..... DataCaching我得到的錯誤。我試過把它轉換成字典(Dictionary<int, string>),做一個.ToDictionary(),但沒有任何效果。

任何人有任何想法?

+2

「OutcomeCriteriaID」和「OutcomeCriteriaName」的類型是什麼?他們需要是相同的呼叫是有效的。 – Lee 2014-10-20 18:31:24

回答

5

由於字典的鍵和值類型需要相同,而您的不同,因此無法編譯。你可以改變方法的定義,要求一個字符串鍵類型:

public static bool AddItemToCache<T>(string key, Dictionary<string, T> cacheItem, TimeSpan ts) 
{ 
    if (!IsCached(key)) 
    { 
     System.Web.HttpRuntime.Cache.Insert(key, cacheItem, null, Cache.NoAbsoluteExpiration, ts); 

     return IsCached(key); 
    } 

    return true; 
} 
+1

難道他也不能改變模板採取''? – Hogan 2014-10-20 18:37:40

+0

@Hogan - 是的,但'key'參數是一個字符串,'System.Web.HttpRuntime.Cache.Insert'使用字符串鍵,所以鍵類型是固定的。 – Lee 2014-10-20 18:42:18

4

改變你的方法簽名的參數從

Dictionary<T, T> cacheItem 

Dictionary<TKey, TValue> cacheItem 

T,T意味着鍵和值具有相同的類型。

相關問題