初始化对象不在列表中的<工作; 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";}
}
上面的代码是不是加工。我在想什么。我使用C#.NET 2.0。请帮忙
The above code is not working. What am i missing. I am using c# .NET 2.0. Please help.
答
收集和对象初始化是新的C#3.0;它们不能在Visual Studio 2005中使用
Collection and object initializers are new to C# 3.0; they cannot be used in Visual Studio 2005.
此外,这是无效的语法甚至在C#3;您需要更换分号(;
)用逗号(,
)的对象初始化器内,并添加之间的逗号每个对象的集合初始化。
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.