AutoImplementedProperties.md 1.1 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
# C# 3.0 特性 自动实现属性

在 C# 3.0 及更高版本,当属性访问器中不需要任何其他逻辑时,自动实现的属性会使属性声明更加简洁。

对于字段可以用属性来封装,上面代码的name就是用Name封装,并且使用时使用Name。C# 3.0特性支持了自动实现属性的访问器,这样就可以写成Id这样,也能实现一样的功能。这里的属性将set访问器声明为私有,那就是私有的访问级别,如果访问器只声明get访问器时,除了能在构造函数中可变,在其他任何位置都不可变。

```csharp
public class Example
{
    private string name;

    public string Name { get => name; set => name = value; }

	public string Id { get; set; }

	public int Count { get; private set; }

	public string UserId { get;}

	public Example(string userId)
    {
		this.UserId = userId;
    }
}
```

如上代码,在下列选项中,不可以设置属性值的是:

## 答案

31
```csharp
32 33 34 35 36 37 38
Example example = new Example(){UserId = Guid.NewGuid().ToString()};
```

## 选项

### A

39
```csharp
40 41 42 43 44
Example example = new Example(Guid.NewGuid().ToString());
```

### B

45
```csharp
46 47 48 49 50 51
Example example = new Example();
example.Id = Guid.NewGuid().ToString();
```

### C

52
```csharp
53 54 55
Example example = new Example();
example.Name = Guid.NewGuid().ToString();
```