添加实现类型的泛型类型列表,并将其连接到具有相同接口值的字典 [英] Add list of generic type that implements and interface to a dictionary that has a value of the same interface

查看:64
本文介绍了添加实现类型的泛型类型列表,并将其连接到具有相同接口值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

private Dictionary<TypeList<ICacheable>> cachedEntities;
 
public ICacheable GetFromCache<T>(Expression<Func<Tbool>> predicate) where T : ICacheable
{
    var type = typeof(T);
 
    if (!cachedEntities.ContainsKey(type))
        cachedEntities.Add(type, new List<T>());
 
    var entitiesList = cachedEntities[type].AsQueryable();
    var result = entitiesList.Where(predicate);
 
    return result;
}

我在尝试添加新列表< T>时遇到错误字典声称它不能从T转换为ICacheable,但我强迫T实现,所以我不太明白为什么我得到它。

I'm getting an error when trying to add the new List<T> to the dictionary claiming that it can't convert from T to ICacheable, but I force T to implement, so I'm not really understanding why I'm getting it.

我是entityList.Where(谓词)中也有一个错误,声称它无法转换为Expression< Func< T,bool>>表达式< Func< ICacheable,int,bool>>。

I'm also getting an error in the entitiesList.Where(predicate) claiming it can't convert from Expression<Func<T,bool>> to Expression<Func<ICacheable, int, bool>>.

推荐答案

我猜这是一个协方差/逆变问题。但是......因为Dictionary被声明为只保存ICacheable的列表,该方法的那部分实际上是否需要使用泛型类型?

I would guess this is a covariance/contravariance problem. But...since the Dictionary is declared as only holding lists of ICacheable, does that part of the method actually need to use the generic type at all?

例如。你不能这样做:

 private Dictionary<Type, List<ICacheable>> cachedEntities;

public IQueryable<ICacheable> GetFromCache<T>(Expression<Func<ICacheable, bool>> predicate)
{
    var type = typeof(T);

    if (!cachedEntities.ContainsKey(type))
        cachedEntities.Add(type, new List<ICacheable>());

    var entitiesList = cachedEntities[type].AsQueryable();
    var result = entitiesList.Where(predicate);

    return result;
}

(不得不将方法的返回类型更改为IQueryable,因为那就是Where ()方法返回)。

(Had to change the return type of the method to IQueryable as well since that's what the Where() method returns).


这篇关于添加实现类型的泛型类型列表,并将其连接到具有相同接口值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆