为什么实例化一个对象不自动实例化它的属性?

Why doesn't instantiating an object automatically instantiate its properties?

我有以下 类:

public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; }
}

public class OverallResult
{
    public string StatusDescription { get; set; }
    public int StatusCode { get; set; }
    public string CustomerId { get; set; }        
}

我实例化:

var apiResult = new CustomerResult();

为什么下面的 return 是空引用?当我创建 CustomerResult()?

时,肯定会实例化 OverallResult
apiResult.Result.CustomerId = "12345";

因为您没有为 Result 创建实例。默认情况下,引用类型具有空值,OverallResult 是一个 class,因此是一个引用类型。

你可以在构造函数中完成。

public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; }
    public CustomerResult(){
        Result = new OverallResult();
    }
}

如果你的 C# 版本高于 6.0 有一个更简单的方法 Auto-Property Initializers

C# 6 enables you to assign an initial value for the storage used by an auto-property in the auto-property declaration:

public class CustomerResult
{
    public string CompanyStatus { get; set; }
    public OverallResult Result { get; set; } = new OverallResult();
}

子对象没有自动实例化的原因之一是你可能不想调用默认的构造函数,甚至你想强制程序员调用具有足够参数的构造函数来正确初始化class 完全,所以没有 public 默认构造函数。

你可能会争辩说,如果有一个默认构造函数,那么它应该总是 运行,然后是你真正想要的构造函数,但这样你就在做同样的工作两次。

public class CustomerResult
{
   public string CompanyStatus { get; set; }
   public OverallResult Result { get; set; }
}

public class OverallResult
{
   public OverallResult()
   {
       StatusCode = 55;
       StatusDescription = "Nothing to see";
   }
   public OverallResult(int statusCode, string status)
   {
      StatusCode = statusCode;
      StatusDescription = status;
   }
   public string StatusDescription { get; set; }
   public int StatusCode { get; set; }
   public string CustomerId { get; set; }        
}

void main()
{
   var result = new CustomerResult()
   {
       Result = new OverallResult(51, "Blah"),
   };
}