在C#中为对象的属性值赋值报错
定义了对象:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;us...
定义了对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using test.Models;
namespace test.Models.ViewModel
{
public class de_item
{
public department de { get; set; }
public item item { get; set; }
}
}
在control的index方法中进行如下操作
public ActionResult Index()
{
de_item dei = new de_item();
var ab =from a in db.department
join b in db.item on a.departmentid equals b.departmentid
select new{a.departmentid,a.name,b.item_name,b.itemid};
if (ab == null)
{
return View();
}
else{
foreach (var d in ab.ToList())
{
dei.de.departmentid = d.departmentid;
dei.de.name = d.name;
dei.item.departmentid = d.departmentid;
dei.item.itemid = d.itemid;
dei.item.item_name = d.item_name;
};
return View(dei);
}
运行后报错,说未将对象引用设置到对象的实例,如下图: 展开
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using test.Models;
namespace test.Models.ViewModel
{
public class de_item
{
public department de { get; set; }
public item item { get; set; }
}
}
在control的index方法中进行如下操作
public ActionResult Index()
{
de_item dei = new de_item();
var ab =from a in db.department
join b in db.item on a.departmentid equals b.departmentid
select new{a.departmentid,a.name,b.item_name,b.itemid};
if (ab == null)
{
return View();
}
else{
foreach (var d in ab.ToList())
{
dei.de.departmentid = d.departmentid;
dei.de.name = d.name;
dei.item.departmentid = d.departmentid;
dei.item.itemid = d.itemid;
dei.item.item_name = d.item_name;
};
return View(dei);
}
运行后报错,说未将对象引用设置到对象的实例,如下图: 展开
展开全部
查查看是不是 dei.de 或者 dei是null
更多追问追答
追答
那就对了,我不知道 dei.de 和dei.item 分别有怎样的构造函数。
这里我假设 它们 都有不带参数的构造函数。把 de_item 类改成下面的定义形式
public class de_item
{
public department de { get; set; }
public item item { get; set; }
public de_item(){
this.de = new department();
this.item = new item();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询