实例化类的实例时,集合字段为 null



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

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 集合是否为空?这是为什么呢?我创建了该类的一个实例,布尔属性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/en-us/library/aa691171(v=vs.71(.aspx

最新更新