Object initializers not working in List<T>
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.
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.
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"
}
};
精彩评论