Object initializers not working in List<T>

前提是你 提交于 2019-12-10 18:08:11

问题


        List<Car> oUpdateCar = new List<Car>();

        oUpdateCar.Add(new Car());
        oUpdateCar[0].name = "Color";
        oUpdateCar[0].value = "red";

        oUpdateCar.Add(new Car());
        oUpdateCar[1].name = "Speed";
        oUpdateCar[1].value = "200";

The above code is working but i want to initialize it when i create the list as below,

List<Car> oUpdateCar = new List<Car>
    {

        new Car{
        name = "Color";
        value = "red";}

    new Car{
        name = "Speed";
        value = "200";}
    }

The above code is not working. What am i missing. I am using c# .NET 2.0. Please help.


回答1:


Collection and object initializers are new to C# 3.0; they cannot be used in Visual Studio 2005.

Also, that's invalid syntax even in C# 3; you need to replace the semicolons (;) with commas (,) inside the object initializers, and add a comma between each object in the collection initializer.




回答2:


Collection initializers are part of C# 3.0 and the syntax is like this:

List<Car> oUpdateCar = new List<Car>
{
    new Car
    {
        name = "Color",
        value = "red"
    },

    new Car
    {
        name = "Speed",
        value = "200"
    }
};


来源:https://stackoverflow.com/questions/2667446/object-initializers-not-working-in-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!