相关疑难解决方法(0)

初始化C#自动属性

我习惯写这样的课程:

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)

c# initialization automatic-properties

180
推荐指数
3
解决办法
15万
查看次数

标签 统计

automatic-properties ×1

c# ×1

initialization ×1