linq - C# : Chained Linq methods and casting

标签 linq casting plinq

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

    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/

相关文章:

c++ - 为什么 C 和 C++ 允许表达式 (int) + 4*5?

c# - 如何使用 PLINQ 进行延迟加载?

c# - 我该如何解决这个错误?时间:2019-03-08 标签:c#asplinq

c# - 如何从 Expression<Func< , >> 创建委托(delegate)? (将参数传递给表达式)?

c# - 双数组到对象数组?

c# - 接口(interface)转换与类转换

c# - 强制 Entity Framework 使用 datetime 而不是 datetime2

c# - 使用 Lambda 或 Linq 为 MVC5 中的 Razor View 创建带有所选项目的 SelectList 模型

c# - PLINQ ForAll WithCancellation 不起作用

c# - 任务与 AsParallel()