我习惯于编写这样的类:
public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}将Bar转换为auto-property似乎既方便又简洁,但我如何才能在不添加构造函数并将初始化放入其中的情况下保留初始化?
public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}您可以看到,添加构造函数并不符合我应该从auto-properties中获得的工作量节省。
这样的事情对我来说更有意义:
public string Bar { get; set; } = "bar";发布于 2008-10-03 23:06:09
你可以通过你的类的构造函数来实现:
public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}如果你有另一个构造函数(例如,一个接受参数的构造函数)或一堆构造函数,你总是可以拥有这个(称为构造函数链):
public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}如果您总是将调用链接到默认构造函数,则可以在那里设置所有默认属性初始化。在链接时,链接的构造函数将在调用构造函数之前调用,以便您更专业的构造函数能够根据需要设置不同的默认值。
https://stackoverflow.com/questions/169220
复制相似问题