Initializing a List
本文关键字:List Initializing | 更新日期: 2023-09-27 18:19:07
我创建了一个类student
,它有三个属性,像这样
public class Student
{
public int age;
public string name;
public string course;
public Student(int age , string name , string course)
{
this.age = age;
this.course = course;
this.name = name;
}
List<Student> school = new List<Student>(
new Student(12,"ram","ece"));
);
}
我要做的是,我正在手动添加学生的详细信息到学生类
但是在
这一行出现了错误 new Student(12,"ram","ece"));
错误:不能从
windowsapplication.student
转换到systems.Collections.Generic.IEnumerable<windowsapplication.Student>
为什么会发生这种情况?
您使用的语法试图将新的Student
传递给List<Student>
的构造函数-没有这样的构造函数,因此出现错误。
你有一个小语法错误。这应该可以工作:
List<Student> school = new List<Student>{
new Student(12,"ram","ece"));
};
集合初始化器的语法是{}
而不是()
。
List<Student>
构造器期望IEnumerable<Student>
,而不是单个学生。我想你实际上是想使用列表初始化器语法:
List<Student> school = new List<Student>()
{
new Student(12,"ram","ece"),
};
try
List<Student> school = new List<Student>() { new Student(12,"ram","ece") };
试试这个:
List<Student> school = new List<Student>();
school.add(new Student(12,"ram","ece"));