我正在尝试在 Movie 以外的类中初始化 Movie 类型的列表,而这两个类都位于同一名称空间中。代码在下面提到:
namespace MovieListCaseStudy
{
class Movie
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private float duration;
public float Duration
{
get { return duration; }
set { duration = value; }
}
private float price;
public float Price
{
get { return price; }
set { price = value; }
}
}
}
******
namespace MovieListCaseStudy
{
class BusinessLogic
{
List<Movie> movielist = new List<Movie>();
{
{Id=1, Name="pk", Duration=2, Price=200}
};
}
}
问题是 BusinessLogic 类中未标识Id,Name等属性。请帮助。
答案 0 :(得分:4)
您错过了new Movie()
:
List<Movie> movielist = new List<Movie>()
{
new Movie() { Id=1, Name="pk", Duration=2, Price=200 }
};
答案 1 :(得分:2)
删除尾部半冒号,并根据@Marcin使用new Movie()
构造。另请注意,默认构造函数parenths ()
对于初始化程序是可选的:
class BusinessLogic
{
List<Movie> movielist = new List<Movie>
{
new Movie {Id=1, Name="pk", Duration=2, Price=200}
};
}
顺便说一下,Array
初始化可以使用另一种速记,但在这种情况下需要额外的.ToList()
转换,在这种情况下效率会降低:
class BusinessLogic
{
List<Movie> movielist = new [] // No type needed, will be inferred
{
new Movie {Id=1, Name="pk", Duration=2, Price=200}
}
.ToList();
}