2

我正在开发一个包含不同书籍的通用列表的程序。我遇到的问题是,我的书本类应该覆盖ToString()超类中的方法,System.Object以便它显示如下字符串:

作者名字,作者姓氏,“书名”,年份。

这是我的书类代码:

 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,使其返回具有以下格式的字符串”的任何想法:

作者名字,作者姓氏,“书名”,年份。
4

4 回答 4

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);
    }
}
于 2013-02-21T08:21:17.857 回答
0

您不能覆盖 system.Object.ToString()

但是你可以实现你自己的集合

或者您对可以在列表中调用的列表“ListToMyStringFormat”进行扩展方法

于 2013-02-21T08:20:53.553 回答
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;
    }
}
于 2013-02-21T08:22:17.807 回答
0

您需要覆盖Book类中的字符串,而不是System.Object. 将以下函数添加到Book类中。

public override string ToString()
{
    return this.authorFirstName + ", " + this.authorLastName + ", " + this.bookTitle + "," + this.publicationYear.ToString();
}
于 2013-02-21T08:22:24.783 回答