This article has been localized into Chinese by the community.
C# 3.0:
集合的初始化
C# 3.0为对象初始化提供了新的写法同时,也为初始化一个列表并给它增加一组特定元素提供了新的写法。我们继续说上节的Car类:
class Car
{
public string Name { get; set; }
public Color Color { get; set; }
}
如果我们打算创建一个列表并为之加入一组车型,在C# 2.0里面我们需要这么做:
Car car;
List<Car> cars = new List<Car>();
car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
cars.Add(car);
car = new Car();
car.Name = "Golf";
car.Color = Color.Blue;
cars.Add(car);
利用对象初始化器,我们可以来得简短一点:
List<Car> cars = new List<Car>();
cars.Add(new Car { Name = "Corvette", Color = Color.Yellow });
cars.Add(new Car { Name = "Golf", Color = Color.Blue});
如果利用集合的初始化器,它还可以更简短:
List<Car> cars = new List<Car>
{
new Car { Name = "Corvette", Color = Color.Yellow },
new Car { Name = "Golf", Color = Color.Blue}
};
还可以写成一行,其作用是完全一样的:
List<Car> cars = new List<Car> { new Car { Name = "Corvette", Color = Color.Yellow }, new Car { Name = "Golf", Color = Color.Blue} };
因为有对象初始化器和集合初始化器,原来10行的代码被缩成了1行,虽然这行有点长。
This article has been fully translated into the following languages:
Is your preferred language not on the list? Click here to help us translate this article into your language!