重写方法ToString()c#console应用程序

问题描述:

我正在处理一个具有不同书籍通用列表的程序。我的问题是,我的书类应该重写超System.Object方法ToString()使其显示像这样的字符串:重写方法ToString()c#console应用程序

 
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

代码正在编译但与StackOverflow失败。你的属性设置不正确。将它们更改为:'private string _bookTitle; 公共字符串bookTitle { get {return _bookTitle; } set {_bookTitle = value; } }' – Nogard 2013-02-21 08:26:02

不能覆盖system.Object.ToString()

但是你可以实现你自己的收藏这确实

,或者你让一个Extensionmethod到列表“ListToMyStringFormat”,可以在列表上被称为

+0

嗯..好吧,那么在超类System.Object中重写方法ToString()是什么意思? – user2057693 2013-02-21 08:23:40

+0

@ user2057693这意味着.NET中的每个对象都从'System.Object'继承,它具有'ToString()'方法。如果你想在你的类中覆盖该方法(在本例中为'Book'),你只需要使用我在我的答案中使用的语法。 – 2013-02-21 08:25:41

+0

ahaa好的.. Thx很棒! – user2057693 2013-02-21 08:30:36

请看下图:

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); 
    } 
} 

下面是例子,如何做到这一点:

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; 
    } 
} 

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

public override string ToString() 
{ 
    return this.authorFirstName + ", " + this.authorLastName + ", " + this.bookTitle + "," + this.publicationYear.ToString(); 
}