【问题标题】:Can not check if an array is null无法检查数组是否为空
【发布时间】:2012-12-24 06:06:44
【问题描述】:

我的 asp.net mvc 应用程序中有以下操作方法:-

 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();
        }

但如果SelectRight Array 为空,那么它将绕过if (SelectRight == null) 检查并呈现CustomerDetails 视图并在视图内的以下代码上引发异常

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

那么我怎样才能使空检查正常工作呢?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    你必须返回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
          {
               '...
    

    【讨论】:

      【解决方案2】:

      您可以将条件更改为以下条件:

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

      这应该会有所帮助。

      编辑

      关于上面的代码需要注意的重要一点是,在 c# 中,or 运算符 || 是短路的。它看到数组为空(语句为真)并且不尝试评估第二条语句 (SelectRight.Length == 0),因此不会抛出 NPE。

      【讨论】:

      • 它仍然会中断,因为如果它为空,它会执行RedirectToAction("Index"); 并仍然呈现视图。卡布姆。
      • 从上面的描述看来,CustomerDetails 视图上抛出了异常:“它会渲染 CustomerDetails 视图并引发异常”
      • 描述说foreach会中断,foreach不会在空数组上中断,而是在空集合上。
      • 你说得对,约阿希姆。但是,如果您检查代码,您可以看到对于空的 SelectRight,赋值 Info = SelectRight.Select(GetAccount) 可能会将空值分配给 Info。然后@foreach (var item in Model.Info) 将抛出一个错误(如Info 如果为空)。所以检查数组是空还是空是有意义的。
      • 好吧,IEnumerable.Select 在一个空集合上不会返回 null,而是另一个空集合。问题是当SelectRight is null 时,它根本不会分配Info,而是调用RedirectToAction("Index");(或多或少是一个没有返回值的无操作)并失败到return View();,它将呈现CustomerDetails 视图而不设置Info。当然,如果调用的 Select 是用户实现的函数而不是 Linq 函数,那么所有关于返回值的赌注都将被取消:)
      【解决方案3】:

      您可以检查它不为空,并且长度不为零。

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

      if 语句会同时捕获空值和空数组。

      【讨论】:

        猜你喜欢
        • 2017-09-13
        • 1970-01-01
        • 2011-11-04
        • 2022-01-25
        • 2011-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        相关资源
        最近更新 更多