如何将列表转换为可枚举 [英] How to cast list to enumerable
问题描述
以下代码有问题:
public IEnumerable<ISession> GetSessions()
{
// ...
using (ProvaDbEntities DBEntities = new ProvaDbEntities(Utilities.ToEntitiesConnectionString()))
{
ObjectQuery<session> sessions = DBEntities.session;
IEnumerable<session> q1 = from session in sessions
where session.site == this.Name
select session;
List<Session> sessionList = new List<Session>();
foreach (var s in q1)
{
sessionList.Add(new Session(s.id.ToString(),s.username, s.site, new DateTime()));
}
IEnumerable<Session> res = sessionList;
return sessionList;
}
}
例外是:
无法将对象类型'System.Collections.Generic.List`1 [prova3.Session]'强制转换为类型'System.Collections.Generic.IEnumerable'1 [TAP2009.AuctionSite.Interfaces.ISession]'. /p>
Is not possible to cast object type 'System.Collections.Generic.List`1[prova3.Session]' to type 'System.Collections.Generic.IEnumerable`1[TAP2009.AuctionSite.Interfaces.ISession]'.
查看此SO问题似乎是正确的.我错了吗?
Looking at this SO question it seems to be correct. Am I wrong?
推荐答案
应该没问题,只要Session
实现ISession
- if ,而您使用的是C#4和.NET 4.如果不是,那就不会.
It should be fine, so long as Session
implements ISession
- if you're using C# 4 and .NET 4. If you're not, it won't be.
请注意,您提到的问题在两种情况下均使用相同的"T",而您遇到的例外情况是有关将List<Session>
转换为IEnumerable<ISession>
的问题.您尚未说明要从何处获得异常,这使得很难确切地了解发生了什么.您确定这确实是实际上的失败代码吗?您确定要获取异常而不是编译时失败吗?
Note that the question you referred to use the same "T" in both cases - whereas the exception you've got is about converting a List<Session>
to an IEnumerable<ISession>
. You haven't stated where you're getting the exception, which makes it a bit harder to see exactly what's going on... Are you sure this is actually the code which is failing? Are you sure you're getting an exception rather than a compile-time failure?
如果您不使用.NET 4和C#4,则协方差的解决方法在此非常简单-使用Cast<T>()
LINQ运算符:
If you're not using .NET 4 and C# 4, the workaround for covariance is reasonably simple here - use the Cast<T>()
LINQ operator:
return sessionList.Cast<ISession>();
这篇关于如何将列表转换为可枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!