我习惯写这样的类:
public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
将Bar转换为自动属性似乎很方便简洁,但是如果不添加构造函数并将初始化放在其中,如何保留初始化值呢?
public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
你可以看到,添加构造函数并不符合我应该从自动属性中获得的节省精力的要求。
像这样做对我更有意义:
public string Bar { get; set; } = "bar";