"对象引用未设置为对象的实例。"

时间:2014-10-24 05:20:37

标签: c# nullreferenceexception

我有一个这个模型

public class Task
{
    public Task() { }

    public Task(int CategoryID)       
    {         
        this.TaskID = CategoryID;  
    }       

    public int TaskID { get; set; }
}

public class student
{      
    public List<Task> Task { get; set; }      
    public string Name { get; set; } 
    public int ID { get; set; }
}

在我的控制器中有一个错误,上面写着:'Object reference not set to an instance of an object.'

student student = new student(); 
var TaskQuery = from q in db.tblTasks
                select new
                {
                    TaskID = q.TaskID,                                
                };

qaTaskQuery = qaTaskQuery.OrderBy(x => x.TaskID );

foreach (var StudentTask_ in TaskQuery)
{
    student.Task.Add(new Task()  //Getting error
    {
        TaskID = StudentTask_.TaskID 
    });
}

请告诉我我的代码有什么问题?

2 个答案:

答案 0 :(得分:3)

您尚未实例化List<Task>

student.Task = new List<Task>();
foreach (var StudentTask_ in TaskQuery)
{
   student.Task.Add(new Task()  //Getting error
   {
     TaskID = StudentTask_.TaskID 

   });
}

或者您可以在Student类的构造函数中执行此操作:

public class student
{      
   public List<Task> Task { get; set; }      
   public string Name { get; set; } 
   public int ID { get; set; }

   public Student()
   {
     this.Task = new List<Task>();
   }
}

答案 1 :(得分:2)

在添加内容之前,您必须初始化任务列表:

public class student
{      
    public student()
    {
       Task = new List<Task>();
    }
    public List<Task> Task { get; set; }      
    public string Name { get; set; } 
    public int ID { get; set; }
}