0

可能重复:
.NET 中的 NullReferenceException 是什么?

我有一个名为 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; }
}

和一个白天

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

现在我正在尝试向 Monday 实体添加一个新集合,如下所示:

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.Status1在该语句引发异常的时间有一个。

有任何想法吗?

4

4 回答 4

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>()
};
于 2013-01-18T03:08:16.607 回答
2

此时您的列表为空。所以

_vm.Monday

..会抛出异常。您必须new在构造函数中添加它们:

public HoursOfOperation() {
    Monday = new List<DayTimes>();
    // ...etc
}
于 2013-01-18T03:09:24.747 回答
0

各种 List 属性没有被初始化;你需要添加

_vm.Monday = new List<DayTime>();
于 2013-01-18T03:08:52.027 回答
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>()
};
于 2013-01-18T03:09:46.760 回答