简体   繁体   中英

Objects and references

I'm a little bit lost right now among objects and references. I'm building a small project with some different classes and winForms.

This is a short description of my project: I have a MainForm and when i click 'add new movie' button, the MovieForm opens where I enter information about a movie. When I click the 'save' button I create a NewMovie object of the information in MovieForm.

Next step is to save this NewMovie object to a file. And it's here I'm a bit lost in how to grab the data from this NewMovie object somewhere else from another class, like the MovieManager from where I then use an object of the FileManager to save the data?

In the MainForm I have this code to detect when the button 'add new movie' is clicked in the MovieForm:

MovieForm movieForm = new MovieForm();
if (movieForm.ShowDialog() == DialogResult.OK)
{
Do something here?
}

Could I reach or pass the new MovieForm object here? How do I do then? In my project I also have a MovieManager. One way is to pass the object to that class? Should I create an object of MovieManager in MovieForm and pass the data that way after I have created the NewMovie object?

Preciate some help and ideas! Thanks!

After ShowDialog has finished, the reference to movieForm is still valid. Thus, you can create a public property in your MovieForm:

class MovieForm {
    ...
    public NewMovie Result { get; private set; }
    ...
}

You set this value in your MoveForm (when the form is closed or when some Save button is pushed), and then you can read it in your Main Form and pass it to your MovieManager:

MovieForm movieForm = new MovieForm();      
if (movieForm.ShowDialog() == DialogResult.OK)      
{      
    NewMovie newMovie = movieForm.Result;
    myMovieManager.CreateNewMovie(newMovie);
}      

在MovieForm类中创建一个属性,并在创建实例时传递其值。

You should return newly created instance of Movie from the MovieForm and store it in the manager.

public class MovieManager
{
  List<Movie> movies;

  public void AddMovie(Movie movie)
  {
    movies.Add(movie);
  }

  public Save()
  {
  }
}

public class Movie
{
  public string Name;
}

public class MainForm
{
  MovieManager manager;

  private void NewMovieClick(...)
  {
     using(var form = new MovieForm())
     {
       if(form.ShowDialog(this) == DialogResult.OK)
       {
         manager.Add(from.Movie);
       }
     }
  }
}

public class MovieForm
{
  public Movie Movie;
}

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