我在 Visual Studio 中实现了一个 WindowsForms 应用程序。现在我有一份玩具 list :
List <Toy> toys;
Toy
是一个抽象类,Car
、Submarine
等类都派生自它。该列表当然可以包含 Toy
类型的任何对象。由于我缺乏 C# 经验,我不确定如何修改此列表中的对象,即。 e.更改特定于类型的属性。编译器只知道列表包含 Toy
对象,无法访问 Submarine
对象的字段。所以我不能简单地从列表中取出一些元素,调用一个 setter 并完成它。转换只会让我获得转换为某种类型的列表对象的副本。我怎样才能做到这一点?
最佳答案
如果您不熟悉 Lync 或者想对项目做更多的事情,您也可以循环使用“老派”方式。
给定样本类:
public abstract class Toy
{
public string Manufacturer { get; set; }
}
public class Elephant : Toy
{
public int TrunkLength { get; set; }
}
public class Car : Toy
{
public Color Color { get; set; }
}
您可以像这样添加项目,然后根据它们的类型修改它们:
var toys = new List<Toy>
{
new Car {Color = Color.Red, Manufacturer = "HotWheels"},
new Elephant {TrunkLength = 36, Manufacturer = "Steiff Harlequin"}
};
foreach (var toy in toys)
{
var car = toy as Car;
if (car != null)
{
// Set properties or call methods on the car here
car.Color = Color.Blue;
// Continue the loop
continue;
}
var elephant = toy as Elephant;
if (elephant != null)
{
// Do something with the elephant object
elephant.TrunkLength = 48;
// Continue the loop
continue;
}
}
或者您可以使用“switch”语句和一些转换,这可能更具可读性:
foreach (var toy in toys)
{
switch (toy.GetType().Name)
{
case "Car":
((Car) toy).Color = Color.Blue;
break;
case "Elephant":
var elephant = toy as Elephant;
elephant.TrunkLength = 48;
elephant.Manufacturer = "Made in China";
break;
}
}
关于c# - 如何在 C# 中修改具有公共(public)父类(super class)的对象列表的成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509626/