![](/img/trans.png)
[英]'Cannot initialize type with a collection initializer' while initializing object of my class
[英]initialize value to a public variable of type list of a class using the object initializer
我有一个仅包含类型列表数据成员的通用类。 现在,我想使用main方法中该泛型类的对象初始化程序将值添加到该列表中。
这是我的普通班
class GenericStore<T>
{
public List<T> allData = new List<T>();
}
这是我的入口
class Program
{
static void Main(string[] args)
{
GenericStore<Student> studentData = new GenericStore<Student>()
{
// I Have Write This Which Gives me Error
/*allData = new Student(new Guid(), "Subhashis Pal"),
allData = new Student(new Guid(), "x"),
allData = new Student(new Guid(), "Y"),
allData = new Student(new Guid(), "Z")*/
};
}
}
这是我的学生班
class Student
{
private Guid id;
private string name;
public Student(Guid id, string name)
{
this.id = id;
this.name = name;
}
}
它给您一个错误,因为在GenericStore<Student>
情况下allData
字段的类型为List<Student>
,因此,为了allData
字段allData
种子初始化器,您需要实例化List<Student>
集合并使用其对象初始化器添加Student
对象
GenericStore<Student> store = new GenericStore<Student>
{
allData = new List<Student>
{
new Student(new Guid(), "Subhashis Pal"),
new Student(new Guid(), "x"),
new Student(new Guid(), "Y"),
new Student(new Guid(), "Z")
}
}
allData
是一个List<T>
,您每次都尝试为其分配单个对象Student
。
使用对象初始化器填充allData
如下所示:
GenericStore<Student> studentData = new GenericStore<Student>
{
allData = new List<Student>
{
new Student(new Guid(), "Subhashis Pal"),
new Student(new Guid(), "x"),
new Student(new Guid(), "Y"),
new Student(new Guid(), "Z"),
}
};
我认为您对对象初始化程序的工作方式感到困惑。 这个:
GenericStore<Student> studentData = new GenericStore<Student>()
{
allData = new Student(new Guid(), "Subhashis Pal"),
allData = new Student(new Guid(), "x"),
allData = new Student(new Guid(), "Y"),
allData = new Student(new Guid(), "Z")
};
不正确,因为不能多次分配一个字段,并且Student
与List<Student>
不兼容。 正确的方法是
GenericStore<Student> studentData = new GenericStore<Student>()
{
allData = new List<Student>()
{
// and you create your student objects *here*
}
};
您需要正确地将List<Student>
分配给allData
。 然后,您可以使用列表初始化程序以学生对象初始化列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.