使用foreach循环显示对象 [英] Displaying objects using foreach loop
问题描述
我有一个问题,同时从一个ArrayList中检索数据并显示他们到textboxs。我得到一个错误:无法转换类型'Lab_9.Book对象键入'Lab_9.Magazine
。我试着用2 foreach循环,但是,这似乎是出了问题。我怎么能避免这个问题?
I am having a problem while retrieving data from an ArrayList and displaying them into textboxs. I am getting an error: Unable to cast object of type 'Lab_9.Book' to type 'Lab_9.Magazine'
. I tried use 2 foreach loops but that seems to be out of the question. How could I avoid this problem?
问题发生在这里:
// 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;
}
问候。
推荐答案
您酒馆对象(ArrayList的)的项目是对象
键入图书和杂志类型的实例。因此,你需要使用.OfType()来显示每个类型进行筛选。这种方法将只返回目标类型(T)的ArrayList中,的实例
The items of your pub object(ArrayList) are Object
type instances for Book and Magazine types. So you need to filter using .OfType() to display each type. This method will returns only the instances of the target type(T) in ArrayList.
foreach (Book list in pubs.OfType<Book>())
{
}
foreach (Magazine list in pubs.OfType<Magazine>())
{
}
要二者结合起来的foreach,我会建议你重写的ToString()或者使具有字符串属性的基类。对于使用的基类,将所有的值(如标题+,+ bookNumber ......)的字符串属性。我会告诉你压倒一切的ToString()。
To combine the two foreach, I will suggest you to override ToString() or to make a base class having the string property. For using the base class, set all of values(eg title + "," + bookNumber...) to the string property. I will show you overriding ToString().
internal class Book
{
public override string ToString()
{
return "=== Book " + bookNumber + " ===" + Environment.NewLine +....;
}
}
internal class Magazine
{
public override string ToString()
{
return "=== Publication: " + bookNumber + ....;
}
}
然后你就可以将二者结合起来循环。
And then you can combine the two loop.
foreach (string item in pub)
{
Console.WriteLine(item.ToString());
}
这篇关于使用foreach循环显示对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!