![](/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.