ObjectAndCollectionInitializers.md 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
# 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<int> digits = new List<int> { 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<int, string>()
{
    7 = "seven",
    9 = "nine",
    13 = "thirteen"
};
```

## 选项

### A

```csharp
var numbers = new Dictionary<int, string>()
{
    [1] = "one",
    [9] = "nine",
    [13] = "thirteen"
};
```

### B

```csharp
var numbers = new Dictionary<int, string>()
{
    {19, "nineteen" },
    {23, "twenty-three" },
    {42, "forty-two" }
};
```

### C

```csharp
var numbers = new Dictionary<int, string>()
{
};
```