我有一个小游戏,我在其中实现了一些碰撞检测。现在我想获取与当前“实体”对象发生冲突的特定类型的所有项目的列表。我想做这样的事情:
public List<T> GetCollidingObjects<T>() where T : Entity
{
return this.Game.World.Entities
.AsParallel()
.Where(e => e.IsColliding(this))
.Where(e => e is T)
.ToList<T>();
}
我收到以下错误:
Instance argument: cannot convert from "System.Linq.ParallelQuery<GameName.GameObjects.Entity>" to "System.Collections.Generic.IEnumerable<T>"
谁能解释一下,为什么会这样?
谢谢!
最佳答案
您不能那样使用 ToList()
。您提供的通用参数(如果您选择这样做)必须与序列的类型相匹配。它是 Entity
的序列,而不是 T
。
无论如何,您应该使用 OfType()
进行过滤,这就是它的用途。
public List<T> GetCollidingObjects<T>() where T : Entity
{
return this.Game.World.Entities
.OfType<T>()
.AsParallel()
.Where(e => e.IsColliding(this))
.ToList();
}
关于linq - C# : Chained Linq methods and casting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6631559/