简体   繁体   English

如何在继承的类中使用foreach?

[英]How to use foreach with inherited classes?

I have a base class of Item. 我有一个Item的基类。 The inherited class is Book. 继承的类是Book。 So, a book is an item. 因此,一本书是一件物品。 Fantastic. 太棒了

Now, I have a method called Take(). 现在,我有一个名为Take()的方法。 It does a foreach on all items. 它对所有项目都进行了foreach。

It's doing... 在做...

foreach (Item item in lstItems)

It also gets my Book object, but just the base members. 它还获取了我的Book对象,但只有基本成员。

Of course, I can't get the Book's specific properties from it. 当然,我无法从中获得《书》的特定属性。 Since not all items are books, I don't want to cast item to Book each time. 由于并非所有项目都是书籍,因此我不想每次都将项目转换为书籍。

Is there a common way to get an inherited class in a foreach with C#? 有没有一种常用方法在C#中的foreach中获取继承的类?

If the list had A's in it (or other things that aren't B or subclasses of B), 如果列表中包含A(或不是B或B的子类的其他内容),

then it would simply break with an invalid-cast. 那么它会因无效广播而中断。 You probably want: 您可能想要:

foreach(B i in lstItems.OfType<B>()) {...}

in .NET 3.5. 在.NET 3.5中 (I'm assuming that the lstItems itself will be non-null, btw.) (我假设lstItems本身将为非null,顺便说一句。)

To complete other answers (ie there are many ways to cast things), you usually don't have have to use any form of cast when dealing with inheritance . 要完成其他答案(即,有很多方法可以转换内容), 在处理继承时通常不必使用任何形式的转换 More, the exact goal of inheritance is to deal with polymorphic types. 此外,继承的确切目标是处理多态类型。

You are supposed to provide polymorphic methods that acts logically on every class of your hierarchy. 您应该提供在逻辑上作用于层次结构的每个类的多态方法。

For instance, provide an Execute() method that does nothing in the base class, and which Book properly overrides. 例如,提供一个Execute()方法,该方法在基类中不执行任何操作,并且Book适当地覆盖它。

public class Item
{
    public virtual void Execute() {}
}

public class Book : Item
{
    public override void Execute() { Console.WriteLine("I'm a book"); }
}

public class Test
{
    public static void Main()
    {
        List<Item> items = new List<Item> { new Item() , new Item() , new Book(), new Book() };
        foreach(var item in items)
            item.Execute();
    }
}

If this is not suitable for you, then maybe that Book should not inherits from Item in the first place. 如果这不适合您,则也许Book不应首先从Item继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM