繁体   English   中英

实例化类的实例时,Collection字段为null

[英]Collection field is null when instantiating instance of the class

我创建了一个对象,该对象将保存遇到的错误以及一个布尔字段以指示是否存在任何错误。 该类看起来像这样。

public class ValidationResult
{
    public bool IsValid{ get; set; }
    public List<string> Errors { get; set; }
}

我将在这样的验证方法中使用此类的实例

public class ValidationService
{
    // This instance will hold the errors if there are any
    ValidationResult myValidationResult = new ValidationResult();

    public void ValidationMethod()
    {
       // Validation takes place here
       ...
       // Some errors occurred to lets add then to the instance of the ValidationResult object
       myValidationResult.IsValid = false;
       myValidationResult.Errors.Add("An error occurred here are the details");
    }
}

问题是实例myValidationResult中的Errors集合为null? 为什么是这样? 我创建了该类的实例,并且布尔属性IsValid可用,但是Errors集合为null

您必须初始化您的Errors属性:

public class ValidationResult
{
     public ValidationResult()
     {
          Errors = new List<string>();
     }

    public bool IsValid{ get { return (Errors.Count() == 0); } }
    public List<string> Errors { get; set; }
}

默认情况下仅初始化值类型。 您的List<string>是引用类型,它具有默认值-null。

在这里查看更多信息:

https://msdn.microsoft.com/zh-CN/library/aa691171(v=vs.71).aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM