在声明为父对象的列表中查找子对象
本文关键字:对象 查找 列表 声明 | 更新日期: 2023-09-27 18:32:24
我正在为一个XNA项目开发屏幕管理器类。我正在跟踪类型 GameScreen
的列表,以跟踪我的每个游戏状态。我的每个屏幕都继承自GameScreen
我将如何在我的列表中找到特定的孩子?
例如,假设我们有:
List<Fruit> fruits = new List<Fruit>(){Apple, Orange, Banana, Pineapple};
我想编写一个函数,该函数接收某种类型的水果并从列表中返回该特定水果。我该怎么做呢?
编辑
public Fruit findFruit(object myFruit)
{
//use myFruit to find the correct fruit in the list
}
家庭作业?
你可以这样做:
public Fruit GetFruit(Type type)
{
return fruits.Find(x => x.GetType() == type);
}
遍历每个元素并比较所需类的类型
水果中的水果f) { if(typeof(f) is typeof(Apple) 返回 f; }