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

2 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;
}
Run Code Online (Sandbox Code Playgroud)

这是无法编译的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;
}
Run Code Online (Sandbox Code Playgroud)

这是行isCached = DataCaching .....我得到了错误.我已经尝试将它转换为字典(Dictionary<int, string>),做了一个.ToDictionary(),但没有任何作用.

有人有任何想法吗?

Lee*_*Lee 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;
}
Run Code Online (Sandbox Code Playgroud)