# C# 3.0 特性 对象和集合初始值设定项 使用对象初始值设定项,你可以在创建对象时向对象的任何可访问字段或属性分配值,而无需调用后跟赋值语句行的构造函数。 比如下面的Cat类,以往创建对象可能 ```csharp Cat cat = new Cat(); cat.Name = "Tom"; cat.Age = 10; ``` 当然可以直接为对象设置初始值,这样可以简化对象的构造,如下例子: ```csharp public class Cat { // 自动实现的属性 public int Age { get; set; } public string Name { get; set; } public Cat() { } public Cat(string name) { this.Name = name; } } ``` ```csharp Cat cat = new Cat { Age = 10, Name = "Fluffy" }; Cat sameCat = new Cat("Fluffy"){ Age = 10 }; ``` 上面这段代码示例了使用具有命名类型Cat的对象初始值设定项以及如何调用无参数构造函数。当然也可以为匿名类型设置初始值: ```csharp var testA = new { name = "Gao", age = 996 }; ``` 下面是一个List集合的初始化例子: ```csharp List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ``` 除了分配字段和属性外,对象初始值设定项还可以设置索引器,如下例子: ```csharp public class MatrixTest { private readonly double[,] storage = new double[3, 3]; public double this[int row, int column] { get { return storage[row, column]; } set { storage[row, column] = value; } } } ``` ```csharp var identity = new MatrixTest() { [0, 0] = 1.0, [0, 1] = 0.0, [0, 2] = 0.0, [1, 0] = 0.0, [1, 1] = 1.0, [1, 2] = 0.0, [2, 0] = 0.0, [2, 1] = 0.0, [2, 2] = 1.0 }; ``` 在了解了对象和集合初始值的设定之后,实现对Dictionary初始值设定,以下选项错误的是: ## 答案 ```csharp var numbers = new Dictionary() { 7 = "seven", 9 = "nine", 13 = "thirteen" }; ``` ## 选项 ### A ```csharp var numbers = new Dictionary() { [1] = "one", [9] = "nine", [13] = "thirteen" }; ``` ### B ```csharp var numbers = new Dictionary() { {19, "nineteen" }, {23, "twenty-three" }, {42, "forty-two" } }; ``` ### C ```csharp var numbers = new Dictionary() { }; ```