以下方法调用有什么问题?

时间:2013-01-18 03:05:03

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

  

可能重复:
  What is a NullReferenceException in .NET?

我有一个名为HoursOfOperation的模型(ASP.NET MVC 4,C#):

public class HoursOfOperation
{
    public List<DayTimes> Monday { get; set; }
    public List<DayTimes> Tuesday { get; set; }
    public List<DayTimes> Wednesday { get; set; }
    public List<DayTimes> Thursday { get; set; }
    public List<DayTimes> Friday { get; set; }
    public List<DayTimes> Saturday { get; set; }
    public List<DayTimes> Sunday { get; set; }
}

和DayTimes

public class DayTimes
{
    public int Status { get; set; }
    public string From { get; set; }
    public string To { get; set; }
}

现在我正在尝试将新设置添加到星期一实体,如下所示:

var _vm = new HoursOfOperation();

_vm.Monday.Add(new DayTimes{
      From = day.From.ToString(),
      To = day.To.ToString(),
      Status = (int)day.Status
});

一旦上述陈述被解除,我就会得到"Object reference not set to an instance of an object."异常

现在我已经检查了day.From.ToString()有一个"08:00:00",day.To.ToString()有"09:30:00"和day.Status当时有一个1这句话引发了异常。

任何想法?

4 个答案:

答案 0 :(得分:5)

那是因为Monday没有实例化。

您应该执行类似

的操作
_vm.Monday = new List<DayTimes>();

或者,在HoursOfOperation的构造函数中进行所有实例化,如下所示:

public HoursOfOperation()
{
   Monday = new List<DayTimes>(),
   Tuesday = new List<DayTimes>(),
   Wednesday = new List<DayTimes>(),
   Thursday = new List<DayTimes>(),
   Friday = new List<DayTimes>(),
   Saturday = new List<DayTimes>(),
   Sunday = new List<DayTimes>()
};

答案 1 :(得分:2)

此时您的列表为空。所以

_vm.Monday

..将抛出异常。你必须在构造函数中new

public HoursOfOperation() {
    Monday = new List<DayTimes>();
    // ...etc
}

答案 2 :(得分:0)

各种List属性未初始化;你需要添加

_vm.Monday = new List<DayTime>();

答案 3 :(得分:0)

您需要创建日期列表的实例:

var hoursOfOperation = new HoursOfOperation
{
   Monday = new List<DayTimes>(),
   Tuesday = new List<DayTimes>(),
   Wednesday = new List<DayTimes>(),
   Thursday = new List<DayTimes>(),
   Friday = new List<DayTimes>(),
   Saturday = new List<DayTimes>(),
   Sunday = new List<DayTimes>()
};