2

我有一个小游戏,我在其中实现了一些碰撞检测。现在我想获取与当前“实体”对象发生冲突的特定类型的所有项目的列表。我想做这样的事情:

    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>"

谁能解释一下,为什么会这样?

谢谢!

4

2 回答 2

8

你不能那样使用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();
}
于 2011-07-08T23:33:49.443 回答
0

Jeff Mercado 的回答是正确的,但可以说得更清楚。

.Where(e => e is T)

此调用Enumerable.Where<Entity>返回一个IEnumerable<Entity>(源的过滤版本,它是一个IEnumerable<Entity>)。该调用不返回IEnumerable<T>.

Enumerable.Select<TSource, TResult>并且Enumerable.OfType<TResult>可以返回类型与源不同的 IEnumerable:

.Where(e => e is T)
.Select(e => e as T)

或者

.Select(e => e as T)
.Where(e => e != null)

或者

 .OfType<T>()
于 2011-07-08T23:57:00.180 回答