2013-01-18 29 views
0

可能重複:
What is a NullReferenceException in .NET?以下方法調用有什麼問題?

我有一個模型(ASP.NET MVC 4,C#)調用HoursOfOperation:

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

如上述聲明excecuted我得到一個"Object reference not set to an instance of an object."異常

現在我已經檢查過:3210

現在我想了一組新加入到週一實體像下面day.From.ToString()有一個"08:00:00",day.To.ToString()有"09:30:00"和day.Status有一個1在這個語句拋出異常的時間。

任何想法?

+0

幾乎NullReferenceException異常的所有情況都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 –

回答

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

哇,我對C#和OOP很陌生,但我確實知道並錯過了它。謝謝大家,謝謝大家的回覆。 – hjavaher

0

各種列表屬性沒有被初始化;您需要添加

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

此時您的列表爲空。所以

_vm.Monday 

..會拋出異常。你必須new起來在構造函數中:

public HoursOfOperation() { 
    Monday = new List<DayTimes>(); 
    // ...etc 
} 
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>() 
};