如何检查List是否包含某种类型的对象?C#

Kil*_*oku 15 c# xna

我有一个列表(称为Within),它包含类型的对象GameObject. GameObject是许多其他人的父类,包括DogBall.我想创建一个方法,如果Within包含任何类型的对象,则返回true Ball,但我不知道如何执行此操作.

我已经尝试使用Count<>,Any<>,Find<>和C#中提供了一些其他的方法,但我不能让他们的工作.

public bool DetectBall(List<GameObject> Within)
{
    //if Within contains any object of type ball:
    {
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 53

if (within.OfType<Ball>().Any())
Run Code Online (Sandbox Code Playgroud)

除了Cast<T>()和之外的所有LINQ方法的泛型参数OfType<T>()用于允许方法调用进行编译,并且必须与列表的类型兼容(或者用于协变强制转换).它们不能用于按类型过滤.


Eri*_*rix 9

如果你有兴趣,请在非linq

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

    return false;
}
Run Code Online (Sandbox Code Playgroud)