开发者

Last added List element overwrtiting others

开发者 https://www.devze.com 2023-02-28 18:17 出处:网络
private List<Movie> movies = new List<Movie>(); Movie _movie; _movie = new Movie(); movie.Title = \"test2\";
    private List<Movie> movies = new List<Movie>();
    Movie _movie;

    _movie = new Movie();
    movie.Title = "test2";
  开发者_如何转开发  _movie.Year = "1992";
    movies.Add(_movie);

   _movie = new Movie();
   _movie.Title = "test2";
   _movie.Year = "1992";
   movies.Add(_movie);

   _movie = new Movie();
   _movie.Title = "test3";
   _movie.Year = "1992";
   movies.Add(_movie);

   label8.Text = movies[0].toString();
   label9.Text = movies[1].toString();
   label10.Text = movies[2].toString();

Okay, so I'm making a little program to help me and my friends/girldfriend choose a film when we're bored. Obvious functionality includes adding a new film to the List. I've added the labels there for testing, because everytime I add movies to the List, the last one overwrites all the others.

I've looked at the few questions/threads I could find on this problem and I can't see how on earth all the objects are somehow referencing the same object. Could do with a bit of help.


Try changing:

   label8.Text = movies[0].toString();
   label9.Text = movies[1].toString();
   label10.Text = movies[2].toString();

To:

   label8.Text = movies[0].Title;
   label9.Text = movies[1].Title;
   label10.Text = movies[2].Title;

The reason is that you are storing and accessing the Movie class ToString() doesn't know exactly how you want to print it out unless you override the string method.

You didn't explicitly say so I am not going to assume that you have overridden the ToString() method. If you did, then you need to post that code and any other relevant code from your Movie class.


That code is fine, assuming you are just approximating what your code does (ignoring syntax errors). The problem is most likely in your custom Movie ToString() implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号