简体   繁体   English

将字符串添加到字符串列表

[英]Add strings to the list of string

I am trying to fill a list of strings but it throws null reference exception. 我正在尝试填充字符串列表,但它会引发null引用异常。

Code: 码:

public class Validation
{
    public List<string> Errors { get; set; }
}

Class where all validation errors are to be stored: 将存储所有验证错误的类:

public object Post(Currency currency)
{
    ClientData clientData = new ClientData();
    if (ModelState.IsValid)
    {
        new CurrencyProvider().Insert(currency);
        clientData.IsValid = true;
        clientData.Data = new CurrencyProvider().GetAll();
    }
    else
    {
        Validation validation = new Validation();
        foreach (var modelState in ModelState)
            foreach (var error in modelState.Value.Errors)
                validation.Errors.Add(error.ErrorMessage);

        clientData.IsValid = false;
        clientData.Data = validation;
    }   

    return clientData;
}

The problem occurs when I fill validation.Errors.Add(error.ErrorMessage) . 当我填写validation.Errors.Add(error.ErrorMessage)时,会发生问题。 It throws me the null reference exception even though I have done exception handeling globally as follows in my global.asax.cs 即使我在global.asax.cs中按如下方式全局进行了异常处理,也会抛出空引用异常

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalFilters.Filters.Add(new ExceptionFilter());
    }
}

My Exception handler class: 我的异常处理程序类:

public class ExceptionFilter : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        ViewResult view = new ViewResult();
        view.ViewName = "Error";
        view.ViewBag.Exception = filterContext.Exception.Message;
        filterContext.ExceptionHandled = true;
        filterContext.Result = view;
    }
}

I have my custom Error Handling page but its also not showing, when I debug then I came to know the there is the null reference exception at the time of filling the list of string in: 我有我的自定义错误处理页面,但也未显示,当我进行调试时,我才知道在填充字符串列表时存在null引用异常:

validation.Errors.Add(error.ErrorMessage)

What am I doing wrong when I fill the List<string> and why is that throwing null reference exception? 填充List<string>时,我在做什么错?为什么抛出null引用异常? And why that null reference exception is not coming on to my custom error page? 以及为什么该空引用异常不会出现在我的自定义错误页面上?

The issue is that you have not created an instance of List<string> in your Validation class. 问题是您尚未在Validation类中创建List<string>的实例。 You can do that by initializing the instance in the class constructor. 您可以通过在类构造函数中初始化实例来实现。

public class Validation
{
    public Validation()
    {
         this.Errors = new List<string>();
    }

    public List<string> Errors { get; set; }
}

You need to instantiate a new List<string> before adding to list with validation.Errors.Add(). 您需要实例化一个新的List<string>然后再添加带有validation.Errors.Add()的列表。

You could try: 您可以尝试:

public object Post(Currency currency)
{
    ClientData clientData = new ClientData();
    validation.Errors = new List<string>(); // instantiate
    if (ModelState.IsValid)
    {
        new CurrencyProvider().Insert(currency);
        clientData.IsValid = true;
        clientData.Data = new CurrencyProvider().GetAll();
    }
    else
    {
        Validation validation = new Validation();
        foreach (var modelState in ModelState)
        {
            foreach (var error in modelState.Value.Errors)
            {
                validation.Errors.Add(error.ErrorMessage);
            }
        }
        clientData.IsValid = false;
        clientData.Data = validation;
    }
    return clientData;
}

Try 尝试

Validation validation = new Validation();
validation.Errors validationError = new List<string>();

Then write into foreach loop : 然后写入foreach循环:

validationError.Add(error.ErrorMessage);

What you basically doing is called 'Composition' or 'has a' Relation between classes in object oriented programming ,Composition relation between classes, means that class 'has a' another class internally. 在面向对象的编程中,您基本要做的就是称为“组成”或“具有一个”类之间的关系,类之间的构成关系意味着内部该类“具有”另一个类。 for ex : Consider a Customer class below 例如:考虑下面的客户类别

  public class Customer 
    {
       public Address HomeAddress { get; set; } //'Composition' or 'has a' Relation
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EMail { get; set; }
        ...........

    }

Note : (Assume that Address class is another class which contain properties like AddLine1,AddLine2,City,State etc.) 注意:(假设Address类是另一个类,其中包含AddLine1,AddLine2,City,State等属性)

Now Once you initialize the object of Customer class all properties of that class will initialize with it's default values, below will be the default values of object of the above class 现在,一旦初始化Customer类的对象,该类的所有属性将使用其默认值进行初始化,下面将是上述类的对象的默认值

    HomeAddress = null
    FirstName = null
    LastName = null
    EMail = null

so this can lead to run time exception as in your case where you have just declared 'Errors' property but didn't initialized it , And in order to use it you should initialize it,using constructor like below : 因此,这可能会导致运行时异常,就像您刚刚声明'Errors'属性但未对其进行初始化的情况一样,为了使用它,您应该使用如下构造函数对其进行初始化:

public Customer 
{
HomeAddress  = new Address();
FirstName  = "";
LastName  = "";
EMail = "";
}

so similarly you can initialize 'Errors' property in class constructor 所以类似地,您可以在类构造函数中初始化'Errors'属性

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

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