【问题标题】:Why doesn't instantiating an object automatically instantiate its properties?为什么实例化一个对象不会自动实例化它的属性?
【发布时间】:2019-02-06 16:50:59
【问题描述】:

我有以下课程:

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();

为什么下面会返回一个空引用?当我创建CustomerResult() 时,肯定会实例化OverallResult

apiResult.Result.CustomerId = "12345";

【问题讨论】:

  • 不,它没有被实例化。原始值将自动为您保留默认值,它不会创建对象的实例,但那是您的 OverallResult
  • 当没有代码来执行实例化时,为什么要实例化OverallResult Result 属性?实例化一个对象不会自动实例化它的所有属性。
  • 您的代码中没有new OverallResult();
  • 我试着给你一个更好的标题。如果您觉得我错过了标记,请随时编辑。
  • 这就是为什么程序员认为编写构造函数很有用。做到这一点。

标签: c# .net instance


【解决方案1】:

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

你可以在构造函数中做到这一点。

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 允许您在自动属性声明中为自动属性使用的存储分配初始值:

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

【讨论】:

  • 另外值得注意的是,#6 前向编译中使用的自动属性可以像第一个示例一样在构造函数中设置属性。语法糖。
【解决方案2】:

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

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

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"),
   };
}

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2011-04-10
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多