使用对象初始值设定项

时间:2018-03-07 07:16:03

标签: c# generics object-initializers

我有一个泛型类,它只包含一个list类型的数据成员。现在我想使用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;
    }
}

3 个答案:

答案 0 :(得分:2)

它会给您一个错误,因为allData字段在List<Student>的情况下属于GenericStore<Student>类型,因此为了在对象初始值设定项中播种该字段,您需要实例化{{1}收集并使用其对象初始值设定项添加List<Student>个对象

Student

答案 1 :(得分:1)

allDataList<T>,您每次尝试为其分配单个对象Student

使用 object intializer 填写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"),
    }
};

答案 2 :(得分:1)

我认为您混淆了对象初始化程序的工作方式。这样:

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 初始值设定项来初始化带有学生对象的列表。