初始化列表

时间:2012-01-01 13:40:35

标签: c# .net list

我创建了一个类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>

为什么会这样?

4 个答案:

答案 0 :(得分:2)

您使用的语法是尝试将新的Student传递给List<Student>的构造函数 - 没有这样的构造函数,因此出错。

您的语法错误很少。这应该有效:

List<Student> school = new List<Student>{
                        new Student(12,"ram","ece"));                        
                       };

集合初始值设定项的语法是{}而不是()

答案 1 :(得分:1)

List<Student>构造函数期待IEnumerable<Student>,而不是单个学生。我想你实际上想要使用list initializer语法:

List<Student> school = new List<Student>()
{
    new Student(12,"ram","ece"),
};

答案 2 :(得分:1)

List<Student> school = new List<Student>() { new Student(12,"ram","ece") };

答案 3 :(得分:0)

试试这个:

List<Student> school = new List<Student>();
school.add(new Student(12,"ram","ece"));