对象引用未设置为对象的实例 - 空引用异常

时间:2021-02-11 16:58:06
if (System.Web.HttpContext.Current.Request.Form[day].ToString() != null)
{
    var test = System.Web.HttpContext.Current.Request.Form[day].ToString();
}

I have written these lines but when Form[day] doesn't contain any value, it gives an null object exception. How can I solve this ?

我写过这些行但是当Form [day]不包含任何值时,它会给出一个null对象异常。我怎么解决这个问题?

1 个解决方案

#1


3  

You have to check this value before access it. For example, like this:

您必须在访问它之前检查此值。例如,像这样:

var form = System.Web.HttpContext.Current.Request.Form;
if (form != null && !String.IsNullOrEmpty(day) && form.AllKeys.Contains(day))
{
    var test = form[day].ToString();
}

#1


3  

You have to check this value before access it. For example, like this:

您必须在访问它之前检查此值。例如,像这样:

var form = System.Web.HttpContext.Current.Request.Form;
if (form != null && !String.IsNullOrEmpty(day) && form.AllKeys.Contains(day))
{
    var test = form[day].ToString();
}