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 car = new Car();
car.Name = "Chevrolet Corvette";
car.Color = Color.Yellow;
这样也不错。但是换成C# 3.0,得益于新的对象初始化写法,它可以变得更简洁一点:
Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };
如你看到的那样,我们在Car的一个新实例后面加了一对花括弧,在里面我们能处理Car类的所有public属性。这能少敲几次键盘,代码也短一点。而且它还是可以嵌套的。看看下面的例子,我们给Car类增加了一个复杂的新属性,像这样子:
class Car
{
public string Name { get; set; }
public Color Color { get; set; }
public CarManufacturer Manufacturer { get; set; }
}
class CarManufacturer
{
public string Name { get; set; }
public string Country { get; set; }
}
用C# 2.0来初始化一个Car的新实例,我们得这样做:
Car car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
car.Manufacturer = new CarManufacturer();
car.Manufacturer.Name = "Chevrolet";
car.Manufacturer.Country = "USA";
用C# 3.0,我们可以变成这样:
Car car = new Car {
Name = "Chevrolet Corvette",
Color = Color.Yellow,
Manufacturer = new CarManufacturer {
Name = "Chevrolet",
Country = "USA"
}
};
你要是不太在乎可读性的话,还可以这样:
Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow, Manufacturer = new CarManufacturer { Name = "Chevrolet", Country = "USA" } };
和自动属性同样,这也是取决于你的偏好。你既可这么写,也可以按照老的传统方式来写。
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!