简体   繁体   中英

How do I access a variable that is inside a Class that is inside a List?

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.

简单如:

library.books[0].name

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM