1

I am trying to learn to serialize XML files and I have hit a snag on accessing a variable that is inside a Class that is inside a List. Here is the declaration code:

public class Library{
    public string name;
    public List<Book> books;
}

public class Book{
    public string name;
}

Here is the code where I populate the List that I'm going to serialize, but whenever I run this code all of the library.books.name always end up being equal to the last thing I saved book as, in this case "Xenocide".

    public void MakeXML(){
        Library library = new Library();
        library.books = new List<Book>();       
        library.name = "Red";
        Book book = new Book();
        book.name = "Hobbit";
        library.books.Add(book);
        book.name = "Xenocide";
        library.books.Add(book);
    }

I was wondering if there is a way to acess the variable name inside the Class Book inside the List books, but I can't seem to find something. Any help would be appreciated, Thanks.

4

3 に答える 3

4

As simple as:

library.books[0].name
于 2012-07-31T22:41:10.830 に答える
4

You've also got a problem where you're adding the SAME book to the library twice, and just changing its name inbetween. You need to create two separate book objects and add each one to the list.

    Book book1 = new Book();
    book1.name = "Hobbit";
    library.books.Add(book1);
    Book book2 = new Book()
    book2.name = "Xenocide";
    library.books.Add(book2);
于 2012-07-31T22:44:09.320 に答える
0

You have stumbled into what OOP is all about. As DGH says, you are adding the same book to the list twice and just changing the name in between.

You are basically creating a new Book object called book:

Book book = new Book();

You are then assigning the name field of book to "Hobbit":

book.name = "Hobbit";

You then add book to your Library.books List field:

library.book.Add(book);

You then change then name field of your original book to "Xenocide" and add it to the list

book.name = "Xenocide";

This previous line is what I think you are forgetting. book is a single object. You can pass this specific instance of Book to any other class or method, and you are always working with the same book. Most any change you make along the way always impacts the original book (there are some exceptions, but not many)

You need to create a new Book any time you want a different Book. This is not optional, this is a requirement of any object orientated language.

于 2012-07-31T23:34:11.527 に答える