gpt4 book ai didi

c# - 使用 foreach 循环显示对象

转载 作者:行者123 更新时间:2023-12-02 18:00:12 25 4
gpt4 key购买 nike

我在从 ArrayList 检索数据并将其显示到文本框中时遇到问题。我收到错误:无法将“Lab_9.Book”类型的对象转换为“Lab_9.Magazine”类型。我尝试使用 2 个 foreach 循环,但这似乎是不可能的。我怎样才能避免这个问题?

问题发生在这里:

    // Displaying all Book objects from pubs ArrayList.
foreach (Book list in pubs)
{
bookNumber++; // Count books from the begining.

// Displaying and formating the output
// in txtBookList textbox.
bookList.txtBookList.Text +=
"=== Book " + bookNumber + " ===" + Environment.NewLine +
list.Title + Environment.NewLine +
list.getAuthorName() + Environment.NewLine +
list.PublisherName + Environment.NewLine +
"$" + list.Price + Environment.NewLine
+ Environment.NewLine;
}

问候。

最佳答案

这将允许你只有一个循环,但它并不漂亮

foreach (object publication in pubs)
{
var book = publication as Book;
var magazine = publication as Magazine;
if (book != null) {
//it's a book, do your thing
} else if (magazine != null) {
//it's a magazine, do your thing
} else {
throw new InvalidOperationException(publication.GetType().Name + " is not a book or magazine: ");
}
}

您真正想要定义一个接口(interface)来封装所有发布的公共(public)属性和方法,而不是继承。

public interface IPublication
{
string Title {get;set;}
float Price {get;set;}
// etc.
}

接下来让你的类实现接口(interface)

public class Book : IPublication
{
public string Title {get;set;}
public float Price {get;set;}
//the rest of the book implementation
}

public class Magazine: IPublication

{
public string Title {get;set;}
public float Price {get;set;}
//the rest of the magazine implementation
}

此时您已经获得了更大的灵 active ,但出于您的目的,您可以保持其余代码不变,并仅使用一个更干净的循环,并且与 jwJung 的解决方案更加内联

foreach (var publication in pubs.OfType<IPublication>())
{
// publication is either a book or magazine, we don't care we are just interested in the common properties
Console.WriteLine("{0} costs {1}", publication.Title, publication.Price);
}

关于c# - 使用 foreach 循环显示对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7990883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com