c# - 如何在 C# 中修改具有公共(public)父类(super class)的对象列表的成员?

标签 c# list inheritance

我在 Visual Studio 中实现了一个 WindowsForms 应用程序。现在我有一份玩具 list :

List <Toy> toys;

Toy是一个抽象类,CarSubmarine等类都派生自它。该列表当然可以包含 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/

相关文章:

C#:长路径与 UseLegacyPathHandling 和 BlockLongPaths 不起作用

c# - .NET 委托(delegate)连接中的顺序有什么影响?

python-3.x - Python根据条件将列表转换为嵌套列表

r - 列表中向量的频率

c++ - 没有 "using"的模板基类的访问属性

python - 将 self 变量作为参数传递给 mixin 父方法的正确方法

c# - C# 中的读取共享权限

c# - 找到与请求 Web API 匹配的多个操作?

python - 清理字符串列表

java - 为什么调用父类方法?