我的每个 Tiles 中都有一个名为“Within”的 GameObject 类型列表。
List<GameObject> Within = new List<GameObject>();
GameObject 具有Bee
、Flower
和Tree
类型的派生类。
我正在做一个 foreach
,它应该检测列表中的所有蜜蜂并选择或取消选择它们。
foreach (Bee bee in Tile.Within)
{
bee.selected = !bee.selected;
}
问题是,当我这样做时,如果列表中有一个类型为 Flower
或 Tree
的对象,我会得到一个异常:
"Unable to cast object of type 'WindowsGame2.Flower' to type 'WindowsGame2.Bee'."
我以为 foreach
会在我们调用它时忽略所有不符合描述的对象,但它不会......我怎样才能让它工作?
最佳答案
在 foreach 中使用 LINQ 过滤怎么样?
foreach (Bee bee in Tile.Within.OfType<Bee>())
{
bee.selected = !bee.selected;
}
这只会选择蜜蜂的,不会选择花或树。
关于c# - 如何在 C# 中的基类型列表中使用 Foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8341270/