【发布时间】:2016-06-24 11:12:50
【问题描述】:
我有以下课程,其中包含 MSDN 记录的 2 个相等方法。
public class Book
{
public string bookTitle {get; private set;}
public IReadOnlyCollection<Author> authors {get; private set;}
public string ISBN {get; private set;}
public int numberofpages {get; private set; }
public string Genre {get; private set; }
public Book(string bookTitle, IReadOnlyCollection<Author> authors, string ISBN, int numberofpages, string genre)
{
if(string.IsNullOrWhiteSpace(bookTitle)){
throw new ArgumentNullException("Book Must Have Title!");
}
this.bookTitle = bookTitle;
if(authors.Count < 0){
throw new ArgumentNullException("You must provide at least one author!");
}
this.authors = new ReadOnlyCollection<Author>(new List<Author>(authors));
if(String.IsNullOrWhiteSpace(ISBN)){
throw new ArgumentNullException("A Book Has to have an ISBN number. Check online or the back cover");
}
this.ISBN = ISBN;
if(numberofpages <= 0){
throw new ArgumentNullException("A Book has more than one page!");
}
this.numberofpages = numberofpages;
if(String.IsNullOrWhiteSpace(genre)){
throw new ArgumentNullException("A Book has a genre. Find it and input it");
}
this.Genre = genre;
}
public override bool Equals(Object obj)
{
if (obj == null)
{
return false;
}
Book p = obj as Book;
if ((System.Object)p == null)
{
return false;
}
return (bookTitle == p.bookTitle) && (authors == p.authors) && (numberofpages == p.numberofpages) && (ISBN == p.ISBN) && (Genre == p.Genre);
}
public bool Equals(Book p)
{
if ((object)p == null)
{
return false;
}
return (bookTitle == p.bookTitle) && (authors == p.authors) && (numberofpages == p.numberofpages) && (ISBN == p.ISBN) && (Genre == p.Genre);
}
public class Author
{
public int ID {get; private set;}
public string firstname {get; private set;}
public string lastname {get; private set;}
public(int id, string firstname, string lastname)
{
this.ID = id;
this.firstname = firstname;
this.lastname = lastname;
}
//Rest of code here: just toString method
}
我的问题:
这两种方法都将评估为 false,因为我在构造函数中分配作者之前创建了一个新列表:
this.authors = new ReadOnlyCollection<Author>(new List<Author>(authors));
我这样做是为了让用户无法在课堂外更改ReadOnlyCollection。所做的任何更改都将在该集合的副本上。考虑到这一点,鉴于我创建了一个新列表,我如何让我的 Equals to 方法正常工作?
【问题讨论】:
-
您必须比较作者列表项。在每个索引处对作者进行排序和比较,直到它们不相等或到达列表末尾。此外,Book 和 Author 都应实施 IEquatable 以防止出现问题并保持理智。
-
@MaxSorin - 你能告诉我怎么做吗?
-
答案提供了代码和实现的接口
标签: c# collections equals