为了账号安全,请及时绑定邮箱和手机立即绑定

初始化C#自动属性

初始化C#自动属性

C#
SMILET 2019-10-16 15:00:18
我习惯于编写这样的类: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";
查看完整描述

3 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

您可以通过类的构造函数来实现:


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

}

如果您始终将调用链接到默认构造函数,则可以在那里设置所有默认属性初始化。链接时,链接的构造函数将在调用构造函数之前被调用,以便您更专业的构造函数将能够在适用时设置不同的默认值。


查看完整回答
反对 回复 2019-10-16
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

在默认构造函数中(当然也可以在任何非默认构造函数中):


public foo() {

    Bar = "bar";

}

我相信这与原始代码的性能一样好,因为无论如何这都是幕后发生的事情。


查看完整回答
反对 回复 2019-10-16
  • 3 回答
  • 0 关注
  • 607 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信