相关疑难解决方法(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万
查看次数

C#3.0+中属性和字段的区别

我意识到它似乎是C#中字段和属性之间有什么区别的重复但我的问题略有不同(从我的观点来看):

一旦我知道了

  • 我不会将我的课程用于"仅适用于属性的技术"和
  • 我不会在getter/setter中使用验证代码.

是否有任何区别(风格/未来发展除外),如设置属性时的某种控制类型?

是否有任何额外的区别:

public string MyString { get; set; }
Run Code Online (Sandbox Code Playgroud)

public string myString;
Run Code Online (Sandbox Code Playgroud)

(我知道,第一个版本需要C#3.0或更高版本,并且编译器会创建私有字段.)

c# field properties automatic-properties c#-3.0

138
推荐指数
6
解决办法
7万
查看次数