Suppose I have the following class:
public class Author
{
public int ID {get; private set;}
public string firstName {get; private set;}
public string lastName {get; private set; }
public Author(int id, string firstname, string lastname)
{
this.ID = ID;
this.firstName = firstname;
this.lastName = lastName;
}
public static Author Clone(Author clone)
{
Author copyAuth = new Author(clone.ID, clone.firstName, clone.lastName);
return copyAuth;
}
}
并且
public class Book
{
public string bookTitle {get; private set;}
private List<Author> authors;
private List<Author> copyofAuthors;
public string ISBN {get; private set; }
public Book(string bookTitle, List<Author> authors, string ISBN)
{
copyofAuthors = new List<Author>();
this.bookTitle = bookTitle;
this.ISBN = ISBN;
//How do I create a deep copy of my authors List?
foreach(Author copy in authors)
{
Author addAuthors = Author.Clone(copy);
copyofAuthors.Add(addAuthors);
}
}
}
我该如何创建一个包含
List<Authors>
集合的深拷贝?我在 StackOverFlow 上看到了其他页面建议使用序列化以及一些我不熟悉且似乎令人困惑的建议。我按照 这个链接 创建了我的克隆方法。
问题一:
上述实现是否视为深拷贝?如果是,使用这种方式是否可行?我的意思是,在构造函数中使用 foreach 循环将作者复制到一个新的列表集合中。
问题二:
如果我修改 copyofAuthor 集合中的任何内容,则它将不再引用原始的集合,对吗?因此,原始 集合应该保持不变?
更新1:
public List<Author> Authors
{
get
{
return returnAuthors(authors);
}
}
private List<Author> returnAuthors(List<Author> copyList)
{
List<Author> getAuthors = new List<Author>();
foreach(Author copy in copyList){
getAuthors.Add(Author.Clone(copy));
}
return getAuthors;
}
我正确地实现了我的getter集合,使得当它返回List集合时,它是独立于原始集合的吗?因此,从getter返回的集合所做的任何更改将不会反映在原始集合中,是吗?
更新#2:
使用ReadOnlyCollection
public class Book
{
public string bookTitle {get; private set;}
private ReadOnlyCollection<Author> authors;
public string ISBN {get; private set; }
public Book(string bookTitle, ReadOnlyCollection<Author> authors, string ISBN)
{
this.bookTitle = bookTitle;
this.ISBN = ISBN;
//Is it okay to do this?
this.authors = authors;
}
public List<Author> Authors
{
get
{ //Create a shallow copy
return new ReadOnlyCollection<Author>(authors);
}
}
}