简体   繁体   中英

Getting A Smaller List From A List Of Abstract Objects

I have an abstract object named Stock and two child classes of this named Book and Journal. I have a list of Stock items named stock and this list is compiled of objects of both Book and Journal. Basically what I'm looking to do is extrapolate only the Books in the list however I keep getting an error message saying that:

"An unhandled exception of type 'System.InvalidCastException' occurred in SimpleLibrary.exe

Additional information: Unable to cast object of type 'SimpleLibrary.Journal' to type 'SimpleLibrary.Book'."

I don't understand why this is happening as I'm only looking to work with the Book items in stock and not needing to do any casting, my code for this is as follows:

    public string getOnlyBooks()
    {
        string books = "";

        foreach (Book book in stock)
        {
            books += book + "\n";
        }

        return books;
    }

The foreach statement does not handle filtering implicitly. Your statement will attempt to cast each object in the stock collection to a Book, and will throw the System.InvalidCastException when it encounters a Journal object. Try the following:

foreach (Stock s in stock)
{
    Book book = s as Book;
    if (book != null) 
    {
        books += book + "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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