使用对象初始值设定项将值初始化为 class 类型列表的 public 变量

initialize value to a public variable of type list of a class using the object initializer

我有一个泛型 class,它只包含一个列表类型的数据成员。现在我想使用我的 main 方法中那个泛型 class 的对象初始值设定项向该列表添加值。

这是我的通用 Class

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

class Student
{
    private Guid id;
    private string name;
    public Student(Guid id, string name)
    {
        this.id = id;
        this.name = name;
    }
}

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> 的情况下,allData 字段的类型是 List<Student>,所以为了在对象初始化程序中播种该字段,你需要实例化 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")
        }
    }

我认为您对对象初始化程序的工作方式感到困惑。这个:

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")
};

不正确,因为一个字段不能多次赋值,StudentList<Student>不兼容。正确的做法是

GenericStore<Student> studentData = new GenericStore<Student>()
{
    allData = new List<Student>() 
    {
        // and you create your student objects *here*
    }
};

您需要将 List<Student> 正确分配给 allData。然后,您可以使用 list 初始化程序用学生对象初始化列表。