我试图通过在WinForm应用程序中使用以下代码将数据保存到ArrayList()。问题是当我这样做时,bookList.txtBookList.Text中的输出是Lab_8.Book
,我无法弄清楚原因。希望有一些提示。
BookEntry.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace Lab_8
{
public partial class BookEntry : Form
{
private ArrayList books = new ArrayList();
private BookList bookList = new BookList();
public BookEntry()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
books.Add(new Book(txtTitle.Text, txtFirstName.Text,
txtLastName.Text, txtPublisher.Text,
float.Parse(txtPrice.Text)));
}
private void btnShowBooks_Click(object sender, EventArgs e)
{
foreach (object list in books)
{
bookList.txtBookList.Text += list.ToString() + "\n";
}
bookList.ShowDialog();
}
}
}
Book.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab_8
{
class Book : Publication
{
private string authorFirstName, authorLastName;
public Book()
{ }
public Book(string title, string firstName, string lastName, string publisherName, float price)
: base(title, publisherName, price)
{
this.authorFirstName = firstName;
this.authorLastName = lastName;
}
public string getAuthorName()
{
return authorFirstName + " " + authorLastName;
}
public string AuthorFirstName
{
get
{
return authorFirstName;
}
set
{
authorFirstName = value;
}
}
public string AuthorLastName
{
get
{
return authorLastName;
}
set
{
authorLastName = value;
}
}
}
}
的问候。 HelpNeeder
答案 0 :(得分:2)
这里的问题是Book
没有覆盖ToString
,这意味着这个循环:
foreach (object list in books)
{
bookList.txtBookList.Text += list.ToString() + "\n";
}
只打印出类的名称(带命名空间)或Lab_8.Book
。
要解决此问题,您可以Book
中的override ToString()
:
class Book : Publication
{
// .. Your code...
public override string ToString()
{
return this.Title + " by " + this.AuthorFirstName + " " + this.AuthorLastName;
}
话虽如此,我强烈建议您将ArrayList
转换为使用List<Book>
。这将允许您直接将书籍称为书籍,即:
foreach (Book book in books)
{
bookList.txtBookList.Text += book.AuthorFirstName + Environment.NewLine;
}
唯一需要改变的是:
private ArrayList books = new ArrayList();
要:
private List<Book> books = new List<Book>();
然后还要更改上面的列表......
答案 1 :(得分:1)
您应该将ArrayList转换为List。
然后,您将拥有一个强类型List
Book
以及IEnumerable
界面的所有好处。这将使您的代码更容易阅读。
因为你有
foreach (object book in books)
这将采用ToString()
的默认实施,因为book
为System.Object
。调用System.Object.ToString()
将返回该类的名称。在这种情况下,Lab_8.Book
。