我该如何将数据类型从
Expression<Func<T, bool>> predicate
为了
Expression<Func<SomeType, bool>> predicate
迄今为止还没有找到方法。或者至少可以通过使用第一个表达式的谓词的字符串表示来创建一个新的Expression<Func<SomeType, bool>>。
如果有帮助,T仅限于实现了ISomeInterface的类型,并且SomeType实现了它。
LE:进一步澄清
接口类似于:
public interface ICacheable
{
List<T> GetObjects<T>(Expression<Func<T, bool>> predicate) where T : ICacheable;
}
那么你需要:
public partial class Video : ICacheable
{
public List<T> GetObjects<T>(Expression<Func<T, bool>> predicate) where T : ICacheable
{
// implementation here that returns the actual List<Video>
// but when I try to query the dbcontext I can't pass a predicate with type T, I have to cast it somehow
List<Video> videos = db.Videos.Where(predicate).ToList(); // not working
}
}
那么你就有:
public class RedisCache
{
public List<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : ICacheable
{
List<T> objList = // get objects from cache store here
if(objList == null)
{
List<T> objList = GetObjects<T>(predicate);
// cache the result next
}
return objList;
}
}
我可以像这样从任何类使用上述代码:
// If the list is not found, the cache store automatically retrieves
// and caches the data based on the methods enforced by the interface
// The overall structure and logic has more to it.
List<Video> videos = redisCache.GetList<Video>(v => v.Title.Contains("some text"));
List<Image> images = redisCache.GetList<Image>(v => v.Title.Contains("another text"));
我希望将这种缓存扩展到任何需要进行缓存的对象,使用方法可以自动检索实体或实体列表,如果它们在缓存中不存在。不过,我可能做错了。
ISomeInterface的另一种实现,而不是SomeType,你会期望发生什么? - Jon Skeet