我正在做一个小项目,并且正在尝试使用对象存储数据。唯一的名称:要存储的名称,年份和价格(最多10个项目)。
//On click I get user input and I create new object instance
//This is addmovie.xaml.cs
private void btn_add_movie_Click(object sender, RoutedEventArgs e)
{
string m = input_movie_name.Text;
Movie NewMovie = new Movie { Name = m };
}
// This is Movie class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeNiro
{
public class Movie
{
public string Name {get; set;}
public int year { get; set; }
public string genre { get; set; }
public int price { get; set; }
public List<Movie> Moviez { get; set; }
}
}
问题: 这是movielist.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DeNiro
{
/// <summary>
/// Interaction logic for movielist.xaml
/// </summary>
public partial class movielist : Page
{
public movielist()
{
InitializeComponent();
String test = NewMovie.Name;
}
}
}
为什么我不能使用NewMovie.Name?
是否可以在movielist.xaml.cs中创建新的Movie实例并从中获取以前存储的数据?请帮忙。
答案 0 :(得分:0)
我会尽力做到这一点:
问题是因为当您在没有 return 的函数中定义变量或未将其“ return”值传递给另一个函数或类属性或引用时,数据被浪费了(这是不是完整的程序说明,但可以帮助您理解)
现在,在代码中,单击按钮后,将创建类Movie
(定义为:名称,年份和价格)的新实例。就是这样,函数完成了,对NewMovie
不执行任何操作。
您要做的是将此实例传递给新函数:
public partial class movielist: Page
{
// This is list, unlike array you can insert things to it as much as you want
private List<Movie> MoviesList = new List<Movie>();
public movielist()
{
InitializeComponent();
}
public void AddMovie(string newMovie)
{
this.MoviesList.Add(newMovie); // Adds new movie to the movies list
String test = NewMovie.Name;
}
}
并在:
private void btn_add_movie_Click(object sender, RoutedEventArgs e)
{
string m = input_movie_name.Text;
Movie NewMovie = new Movie { Name = m };
this.movielistInstance.AddMovie(NewMovie);
}
别忘了在private movielist movielistInstance = new movielist();
类中设置addmovie.xaml.cs
下一次,请发布整个addmovie.xaml.cs
,这将使我们更容易回答。