我正在开发一个包含不同书籍通用列表的程序。我遇到的问题是,我的书类应该覆盖超类ToString()
中的方法System.Object
,以便它显示如下字符串:
authorFirstName, authorLastName, "bookTitle", year.
这是我的书类代码:
class Book
{
public string bookTitle
{
get;
set;
}
public string authorFirstName
{
get;
set;
}
public string authorLastName
{
get;
set;
}
public int publicationYear
{
get;
set;
}
}
这是Main
中的代码:
static void Main(string[] args)
{
List<Book> books = new List<Book>();
books.Add(new Book { authorFirstName = "Dumas", authorLastName = "Alexandre", bookTitle = "The Count Of Monte Cristo", publicationYear = 1844 });
books.Add(new Book { authorFirstName = "Clark", authorLastName = "Arthur C", bookTitle = "Rendezvous with Rama", publicationYear = 1972 });
books.Add(new Book { authorFirstName = "Dumas", authorLastName = "Alexandre", bookTitle = "The Three Musketeers", publicationYear = 1844 });
books.Add(new Book { authorFirstName = "Defoe", authorLastName = "Daniel", bookTitle = "Robinson Cruise", publicationYear = 1719 });
books.Add(new Book { authorFirstName = "Clark", authorLastName = "Arthur C", bookTitle = "2001: A space Odyssey", publicationYear = 1968 });
}
所以我应该怎么做才能“覆盖超类ToString()
中的方法System.Object
,以便它返回一个格式如下的字符串:”
authorFirstName, authorLastName, "bookTitle", year.
答案 0 :(得分:4)
见下文:
class Book
{
public string bookTitle
{
get {return bookTitle; }
set {bookTitle = value; }
}
...
public override string ToString() {
return string.Format("{0}, {1}, {2}, {3}",
authorFirstName, authorLastName, bookTitle,
publicationYear);
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
以下是如何操作的示例:
public class User
{
public Int32 Id { get; set; }
public String Name { get; set; }
public List<Article> Article { get; set; }
public String Surname { get; set; }
public override string ToString()
{
return Id.ToString() + Name + Surname;
}
}
答案 3 :(得分:0)
您需要覆盖Book
课程中的字符串,而不是System.Object
。将以下函数添加到Book
类。
public override string ToString()
{
return this.authorFirstName + ", " + this.authorLastName + ", " + this.bookTitle + "," + this.publicationYear.ToString();
}