属性 是否需要显式初始化?

Does a property need to be explicitly initialized?

属性 是否需要像这样显式初始化:

public DeviceSettings ds{ get; private set; } = new DeviceSettings();

或者保持这样可以吗?

public class MyDevice
{
    public MyDevice(string serial, int patientid)
    {

    }

    public DeviceSettings ds{ get; private set; } //no initialization needed?
}

在您的第一个示例中,ds 设置为 DeviceSettings 的新实例,在您的第二个示例中,ds 设置为 default(DeviceSettings),如果该类型是class 将是 null.

如果您希望以第二种方式进行并且您的类型是 class,您将需要在构造函数中添加赋值

public class MyDevice
{
    public MyDevice(string serial, int patientid)
    {
        ds = new DeviceSettings();
    }

    public DeviceSettings ds{ get; private set; }
}

实例化您的 class 不需要初始化。

如果你要使用属性,你需要将它初始化为一个正确的值(它主要是null,因为null在很多情况下是默认值,除非你重新定义它或使用一个结构)。您可以使用 C#6 语法糖作为您的第一个示例,或在构造函数中完成。

public DeviceSettings ds{ get; private set; } = new DeviceSettings();

该语法仅在 C# 6.0 中引入。所以完全可以不初始化它。在这种情况下,它将获得默认值(取决于 DeviceSettings,它是值还是引用类型)

在创建 class 的新实例时不需要初始化属性。 这主要取决于您的业务逻辑

属性 Initializers 可以在您想使用默认值初始化 属性 时帮助您,例如:

private DateTime CreateOn { get; } = DateTime.UtcNow; 

翻译成这样:

private readonly createOn= DateTime.UtcNow;
public DateTime CreateOn 
{ 
   get
     {
        return createOn;
     } 
}

这是一个 属性,它在初始化后将保持不变。

正如@ScottChamberlain 在他的回答中指出的那样,您可以在 class 的构造函数中初始化一个 auto-implemented property。如果这取决于作为参数传递给构造函数的外部值,那么这是初始化 属性 的好地方,例如:

public class Product
{
  private PriceCalculator Calculator {get;set;}
  public decimal Price{get {return Calculator.GetPrice();}}

  public Product(int factor)
  {
    Calculator=new PriceCalculator(factor);
  }
}