C# 对象在创建列表时未设置为对象错误的实例
我有一个需要在页面加载时填充的列表,下面是dal中的代码C# 对象在创建列表时未设置为对象错误的实例,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我有一个需要在页面加载时填充的列表,下面是dal中的代码 public List<KeyValuePair<Guid, string>> GetProjectName() { List<KeyValuePair<Guid, string>> List = null; try { using (LiveLeaseEntities db = LiveLeaseH
public List<KeyValuePair<Guid, string>> GetProjectName()
{
List<KeyValuePair<Guid, string>> List = null;
try
{
using (LiveLeaseEntities db = LiveLeaseHelper.GetDbLiveLeaseEntities())
{
var projects = (from p in db.t_Project
where p.IsActive == true
select p).ToList();
if (projects != null)
{
foreach (t_Project p in projects)
{
List.Add(new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName));
}
}
return List;
public List GetProjectName()
{
List=null;
尝试
{
使用(LiveLeaseEntities db=LiveLeaseHelper.GetDbLiveLeaseEntities())
{
var projects=(来自db.t_项目中的p)
其中p.IsActive==true
选择p.ToList();
如果(项目!=null)
{
foreach(项目中的t_项目p)
{
添加(新的KeyValuePair(p.ProjectId,p.ProjectName));
}
}
退货清单;
我获取的对象未设置为对象错误的实例。在项目中逐步执行显示计数为7,但我获取的是错误。您需要将
List
变量设置为null
以外的值,如下所示:
List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();
try {
using (LiveLeaseEntities db = LiveLeaseHelper.GetDbLiveLeaseEntities()) {
return db.t_Project
.Where(p => p.IsActive)
.Select(p => new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName))
.ToList();
}
} catch {
...
}
您需要将
List
变量设置为null
以外的值,如下所示:
List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();
try {
using (LiveLeaseEntities db = LiveLeaseHelper.GetDbLiveLeaseEntities()) {
return db.t_Project
.Where(p => p.IsActive)
.Select(p => new KeyValuePair<Guid, string>(p.ProjectId, p.ProjectName))
.ToList();
}
} catch {
...
}
您已经声明了变量
列表
(顺便说一句,绝对使用另一个名称)
List=null;
但从未初始化
List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();
List List=新列表();
当然,当您尝试使用此变量时,会得到NullReferenceException
List.Add(.....) <- NullReferenceException without the initialization
List.Add(…)您已经声明了变量List
(顺便说一句,使用另一个名称)
List=null;
但从未初始化
List<KeyValuePair<Guid, string>> List = new List<KeyValuePair<Guid, string>>();
List List=新列表();
当然,当您尝试使用此变量时,会得到NullReferenceException
List.Add(.....) <- NullReferenceException without the initialization
List.Add(…)您已通过此行将列表设置为null
List<KeyValuePair<Guid, string>> List = null;
List=null;
然后尝试将项添加到此列表中。因此,您需要创建该列表类型的实例,请执行以下操作
List<KeyValuePair<Guid, string>> list = new List<KeyValuePair<Guid, string>>();
List List=新列表();
现在尝试将项目添加到此列表中
您已通过此行将列表设置为null
List<KeyValuePair<Guid, string>> List = null;
List=null;
然后尝试将项添加到此列表中。因此,您需要创建该列表类型的实例,请执行以下操作
List<KeyValuePair<Guid, string>> list = new List<KeyValuePair<Guid, string>>();
List List=新列表();
现在尝试将项添加到此列表中ToList
从不返回null
,而是一个空列表,那么从何处获得异常呢?ToList
从不返回null
而是一个空列表,那么从何处获得异常呢?