System.ArgumentNullException: 值不能为空。参数名称:来源

System.ArgumentNullException: Value cannot be null. Parameter name: source

我的代码显示您传递的参数为空:-

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if (Seats.Count(x => x.IsSelected) == 0)
     {
            return "you didnt select any seats";
     }
     else
     {
           StringBuilder sb = new StringBuilder();
           sb.Append("you selected");
           foreach (Seat seat in Seats)
           {
               if (seat.IsSelected)
               {
                   sb.Append(seat.Name + " ,");
               }
            }
           sb.Remove(sb.ToString().LastIndexOf(","), 1);
           return sb.ToString();
     }   
}

如果您在没有匹配数据/查询参数的情况下调用该方法,则 Seats 将为 null。您还需要检查一下,例如:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if ((Seats == null) || !Seats.Any(s => s.IsSelected))
     {
            return "you didnt select any seats";
     }
     else
     {
           return "you selected " + string.Join(", ", Seats.Where(s => s.IsSelected).Select(s => s.Name));
     }   
}

出现异常是因为 - 正如 Lucero 已经提到的 - Seatsnull。与通常的方法相反,您在这里没有得到 NullReferenceException 因为 Count 是 extension-method:

public static int Count(this IEnumerable<T> source)
{
    if (source == null) throw new ArgumentNullException("source");
}

因此如您所见,如果 sourcenull.

,该方法将抛出 ArgumentNullException 而不是 NullReferenceException

顺便说一句,不要使用 Count 检查您的 collection 是否有项目,请改用 Any,因为它不会枚举完整的 collection和 returns 当找到第一个匹配条件时。

编辑:如果你打算使用另一种正常的方法 instance-method 你会得到一个 NRE:

Seats.DoSomething(); // throws NRE when Seats = null

所以在使用之前检查参数是否是null:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
    if (Seats == null || !Seats.Any(x=> x.IsSelected))
        return "you didnt select any seats";
}