迭代集合中的对象并调用特定对象的方法

本文关键字:对象 方法 调用 集合 迭代 | 更新日期: 2023-09-27 18:04:10

我有一个列表中的对象集合。

基类为car,派生类为CompactTruckSUV

在我的基类中,我有一个名为Drive()的方法。

假设我的列表中有10辆汽车,汽车#3是一辆卡车,我想在它上运行Drive()函数。如何从列表中选择特定对象并在其上运行方法?

迭代集合中的对象并调用特定对象的方法

List<Car> carList;
// fill List with values
carList[2].Drive();
var cars = new List<Car>();
// Add cars....
car[2].Drive();