我有一个类电影,我已经自动实现列表'显示'来添加显示类对象。我可以在main
方法中添加和访问它,但是当我从名为Access
的另一个类调用该列表时,它给了我一个空列表。
我在Movie
类中实例化了Access
类,但它创建了新列表,而不是获取已有的列表。
我需要在Movie
类中有一个非参数化的构造函数。我还需要能够在其他类中访问相同的List
'Shows'。
// The Movie class where i create the list and store all show class objects
public class Movie
{
public List<Show> Shows { get; set; }
public Movie()
{
this.Shows = new List<Show>();
}
public static void Main(string[] args)
{
// create new object of Show type
Show s = new Show(153, 258, 391);
Movie mv = new Movie();
// add object to List
mv.Shows.Add(s);
// The output gives me 153, which is correct
Console.WriteLine(mv.Shows.ElementAt(0).ShowID);
}
}
public class Show
{
public int ShowID { get; set; }
public int MovieID { get; set; }
public int TheatreID { get; set; }
public Show(int showid, int movieid, int theatreid)
{
this.ShowID = showid;
this.MovieID = movieid;
this.TheatreID = theatreid;
}
}
// i need to Access the list in this class
public class Access
{
Movie mov = new Moive();
// the output is showing null value error
Console.WriteLine(mov.Shows.ElementAt(0).ShowID);
}
我需要能够从同一名称空间中的其他类获取和设置List
由于您在构造函数中实例化了show list(Shows),因此每次实例化Movie时都会实例化一个新的show list(Shows),这个问题似乎是合乎逻辑的。
在您的情况下,您必须使用单例模式
单例模式是一种Creational设计模式,它保证了对象的单个实例。
private static List<Show> shows;
public static List<Show> Shows
{
get
{
if (shows == null)
{
shows = new List<Show>();
}
return shows;
}
}
欢迎来到Stackoverflow。请仔细阅读您的代码。在Main
方法中,您创建新的Movie
对象(让我们称之为movieA
),并将新的Show
对象添加到movieA
。在Access
类中你没有使用MovieA
,但是你再次创建了一个新的Movie
对象。如果你想访问在Movie
类中创建的Main
,你需要在Access
类中传递它。
public static void Main(string[] args)
{
// create new object of Show type
Show s = new Show(153, 258, 391);
Movie movieA = new Movie();
// add object to List
movieA.Shows.Add(s);
// The output gives me 153, which is correct
Console.WriteLine(movieA.Shows.ElementAt(0).ShowID);
var access = new Access();
access.MyMethod(movieA);
}
public class Access
{
public void MyMethod(Movie movie)
{
// this should work
Console.WriteLine(movie.Shows.ElementAt(0).ShowID);
}
}
你应该有一个参数化的构造函数,用于接受Movie对象的Access类。
在Access
你创建一个新的Movie
,而你需要采取已经创建的Movie
。
public class Access
{
public void ShowMovieOutput(Movie mov)
{
Console.WriteLine(mov.Shows.ElementAt(0).ShowID);
}
}
public static void Main(string[] args)
{
// create new object of Show type
Show s = new Show(153, 258, 391);
Movie mv = new Movie();
// add object to List
mv.Shows.Add(s);
Access.ShowMovieOutput(mv);
// The output gives me 153, which is correct
Console.WriteLine(mv.Shows.ElementAt(0).ShowID);
}