使用foreach循环显示对象
本文关键字:对象 显示 循环 foreach 使用 | 更新日期: 2023-09-27 18:13:29
我有一个问题,而从数组列表检索数据,并将它们显示到文本框。我得到一个错误:Unable to cast object of type 'Lab_9.Book' to type '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: ");
}
}
您真正想要定义一个接口来封装所有发布的公共属性和方法,而不是继承。
public interface IPublication
{
string Title {get;set;}
float Price {get;set;}
// etc.
}
接下来让你的类实现接口
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
}
在这一点上你已经有了更多的灵活性,但是出于你的目的,你可以保持剩下的代码不变,只使用一个循环,这更干净,更内联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);
}
pub对象(ArrayList)的项是Book和Magazine类型的Object
类型实例。因此,您需要使用. oftype()进行筛选,以显示每种类型。此方法将只返回ArrayList中目标类型(T)的实例。
foreach (Book list in pubs.OfType<Book>())
{
}
foreach (Magazine list in pubs.OfType<Magazine>())
{
}
要组合这两个foreach,我建议您重写ToString()或创建一个具有string属性的基类。要使用基类,将所有值(例如title + "," + bookNumber…)设置为字符串属性。我将展示重写ToString()。
internal class Book
{
public override string ToString()
{
return "=== Book " + bookNumber + " ===" + Environment.NewLine +....;
}
}
internal class Magazine
{
public override string ToString()
{
return "=== Publication: " + bookNumber + ....;
}
}
然后你可以把这两个循环结合起来。
foreach (string item in pub)
{
Console.WriteLine(item.ToString());
}
编辑:我重新阅读了你的问题和你的评论(抱歉),我想你在寻找这个:
foreach (var list in pubs)
{
if(list is Book)
{
Book tmp = (Book)list;
// Print tmp.<values>
}
if(list is Magazine)
{
Magazine tmp = (Magazine)list;
// Print tmp.<values>
}
}