初始化C#自动属性

我习惯于编写这样的类:


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";


SMILET
浏览 621回答 3
3回答

三国纷争

您可以通过类的构造函数来实现: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;}}如果您始终将调用链接到默认构造函数,则可以在那里设置所有默认属性初始化。链接时,链接的构造函数将在调用构造函数之前被调用,以便您更专业的构造函数将能够在适用时设置不同的默认值。

蝴蝶不菲

在默认构造函数中(当然也可以在任何非默认构造函数中):public foo() {    Bar = "bar";}我相信这与原始代码的性能一样好,因为无论如何这都是幕后发生的事情。
打开App,查看更多内容
随时随地看视频慕课网APP