如何在C#中的基类型列表中使用Foreach

Kil*_*oku 3 c# generics foreach

我在每个Tiles中都有一个名为"Within"的GameObject类型列表.

List<GameObject> Within = new List<GameObject>();
Run Code Online (Sandbox Code Playgroud)

GameObject派生了类的类型Bee,FlowerTree.

我正在做一个foreach应该检测列表中的所有蜜蜂并选择或取消选择它们.

foreach (Bee bee in Tile.Within)
{
    bee.selected = !bee.selected;
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我这样做,如果列表类型的对象Flower或者Tree,我得到一个异常:

"Unable to cast object of type 'WindowsGame2.Flower' to type 'WindowsGame2.Bee'."
Run Code Online (Sandbox Code Playgroud)

我认为foreach当我们调用它时会忽略所有不符合描述的对象,但它不会......我怎样才能使它工作?

Øyv*_*hen 8

在foreach中使用LINQ进行过滤怎么样?

foreach (Bee bee in Tile.Within.OfType<Bee>())
{
    bee.selected = !bee.selected;
}
Run Code Online (Sandbox Code Playgroud)

那将只选择蜜蜂,没有花或树.