如何检查列表是否包含某种类型的对象? C# [英] How do I check if a List contains an object of a certain type? C#

查看:75
本文介绍了如何检查列表是否包含某种类型的对象? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list (called Within), and it contains objects of type GameObject. GameObject is a parent class to many others, including Dog and Ball. I want to make a method that returns true if Within contains any object of type Ball, but I don't know how to do this.

我尝试使用 Count<> Any<> Find<> 和C#中提供的其他一些方法,但我无法使它们正常工作。

I've tried using Count<>, Any<>, Find<> and a few other methods provided within C#, but I couldn't get them to work.

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


推荐答案

if (within.OfType<Ball>().Any())

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

The generic parameter of all LINQ methods except Cast<T>() and OfType<T>() is used to allow the method call to compile and must be compatible with the type of the list (or for a covariant cast). They cannot be used to filter by type.

这篇关于如何检查列表是否包含某种类型的对象? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆