简体   繁体   English

无法检查数组是否为空

[英]Can not check if an array is null

i have the folloiwng action method inside my asp.net mvc application:- 我在asp.net mvc应用程序中有folloiwng动作方法: -

 public ActionResult CustomersDetails(long[] SelectRight)
        {

            if (SelectRight == null)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                RedirectToAction("Index");
            }
            else
            {
                var selectedCustomers = new SelectedCustomers
                {
                    Info = SelectRight.Select(GetAccount)
                };




                return View(selectedCustomers);
            }
            return View();
        }

But if the SelectRight Array is empty then it will bypass the if (SelectRight == null) check and it will render the CustomerDetails view and raise an exception on the following code inside the view 但是如果SelectRight Array为空,那么它将绕过if (SelectRight == null)检查,它将呈现CustomerDetails视图并在视图内的以下代码上引发异常

@foreach (var item in Model.Info) {
    <tr>

So how can i make the null check works fine? 那么如何使空检查工作正常呢?

You have to return the result of RedirectToAction(..) . 您必须返回 RedirectToAction(..)的结果。

 public ActionResult CustomersDetails(long[] SelectRight)
 {
      if (SelectRight == null)
      {
           ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
           return RedirectToAction("Index");
      }
      else
      {
           '...

You can change the condition to the following one: 您可以将条件更改为以下条件:

...
if (SelectRight == null || SelectRight.Length == 0)
...

That should help. 这应该有所帮助。

EDIT 编辑

The important thing to note about the code above is that in c#, the or operator || 关于上面代码的重要注意事项是在c#中,或运算符|| is short circuiting. 是短路的。 It sees that the array is null (statement is true) and does NOT attempt to evaluate the second statement ( SelectRight.Length == 0 ) so no NPE is thrown. 它看到数组为null(语句为true)并且不会尝试计算第二个语句( SelectRight.Length == 0 ),因此不会抛出NPE。

You could check that it isn't null, and doesn't have a length of zero. 您可以检查它是否为空,并且长度不为零。

if (SelectRight == null || SelectRight.Length == 0) {
    ModelState.AddModelError("", "Unable to save changes...");
    return RedirectToAction("Index");
}

Above if-statement would catch both null-values and empty arrays. 上面的if语句将捕获空值和空数组。

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

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