Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

xna - How do I check if a List contains an object of a certain type? C#

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.

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;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
if (within.OfType<Ball>().Any())

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...