如何检查一个列表中是否包含某种类型的对象?C#

26

我有一个列表(名为Within),其中包含类型为GameObject的对象。GameObject是许多其他类的父类,包括DogBall。我想编写一个方法,如果Within包含任何类型为Ball的对象,则返回true,但我不知道该怎么做。

我尝试使用C#中提供的Count<>Any<>Find<>等几种方法,但我无法使它们起作用。

public bool DetectBall(List<GameObject> Within)
{
    //if Within contains any object of type ball:
    {
        return true;
    }
}
2个回答

73
if (within.OfType<Ball>().Any())
除了 Cast<T>()OfType<T>() 方法之外,所有 LINQ 方法的泛型参数都用于让方法调用的编译通过,必须与列表的类型兼容(或进行协变转换)。它们不能用于按类型过滤。

12

如果您感兴趣的话,在非Linq中

public bool DetectBall(List<GameObject> Within)
{
    foreach(GameObject go in Within)
    {
        if(go is Ball) return true;
    }

    return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接