我习惯写这样的课程:
public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
Run Code Online (Sandbox Code Playgroud)
将Bar转换为自动属性看起来既方便又简洁,但是如何在不添加构造函数并将初始化放在那里的情况下保留初始化?
public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
Run Code Online (Sandbox Code Playgroud)
您可以看到添加构造函数并不符合我应该从自动属性中获得的省力.
这样的事情对我来说更有意义:
public string Bar { get; set; } = "bar";
Run Code Online (Sandbox Code Playgroud)