无法从用法中推断出方法的类型参数。尝试显式指定类型参数

时间:2014-10-20 18:28:01

标签: c# linq dictionary

我有一个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 个答案:

答案 0 :(得分: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 :(得分:4)

更改方法签名中的参数
Dictionary<T, T> cacheItem

Dictionary<TKey, TValue> cacheItem

T,T表示密钥和值具有相同的类型。

相关问题