C# 3.0引入了“自动属性”,写起代码方便了许多。但当在结构体(struct)中使用自动属性时,有一个很细小的问题要注意,这就是,带参构造器(非默认构造器)中不能为属性赋值。
请看下面的代码:
1
using
System;
2
3 class A
4 {
5 static void Main()
6 {
7 }
8}
9
10 struct T
11 {
12 public int P { get; set; }
13
14 public T(int p) { this.P = p; }
15}
2
3 class A
4 {
5 static void Main()
6 {
7 }
8}
9
10 struct T
11 {
12 public int P { get; set; }
13
14 public T(int p) { this.P = p; }
15}
注意class A没有用途,只是能方便编译而已;主要关注struct T。
编译这段代码,将得到如下错误消息:
a.txt(14,21): error CS0188: The 'this' object cannot be used before all of its fields are assigned to
a.txt(14,10): error CS0843: Backing field for automatically implemented property 'T.P' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
错误消息告诉我们,自动属性背后的字段还没有初始化;并且给了我们一个建议,那就是在构造器之前调用默认构造器。
因此,将构造器的定义改为 public T(int p) : this() { this.P = p; } 即可修正该错误。
但是,如果定义的是class T,而不是struct,则不会出现上述错误。各种原因尚不理解。