gpt4 book ai didi

c# - 如何在不获取 NULLREFERENCEEXCEPTION 的情况下添加到列表?

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:17 25 4
gpt4 key购买 nike

我一直在尝试添加到列表列表中,添加来自 sql 数据库的信息。将新信息添加到列表时出现的错误是:

“在 StatusScope.dll 中发生类型为‘System.NullReferenceException’的异常,但未在用户代码中处理

附加信息:未将对象引用设置到对象的实例。"

我该如何解决这个错误?

map 逻辑.cs

public static List<MapModel.ClientInfo> GetClientsData()
{
SqlConnection Connection = site.Models.Shared.DBConnection.GetConnection();
SqlDataReader Reader = null;
SqlCommand Command = new SqlCommand("SELECT DocInfo.DocID, DocInfo.DocName, DocInfo.DocPic, DocInfo.PatientAcceptance, ClientInfo.ClientName, ClientInfo.AddressLocal, ClientInfo.AddressBroad, ClientInfo.Phone, ClientInfo.Lat, ClientInfo.Long, ClientInfo.ClientID FROM DocInfo INNER JOIN ClientInfo ON DocInfo.ClientID = ClientInfo.ClientID;", Connection);
Reader = Command.ExecuteReader();

var ClientsData = new List<MapModel.ClientInfo> { };
int IDCounter = 0;
bool FirstRun = false;

while (Reader.Read())
{
if (!FirstRun)
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString(), DocNames = { } });
FirstRun = true;
}
else
{
for (var x = 0; x < ClientsData.Count; x++)
{
if (ClientsData[x].ClientID == Reader["ClientID"].ToString())
{
ClientsData[x].DocNames.Add("123"); //error occurs here
}
else
{
ClientsData.Add(new MapModel.ClientInfo { Id = IDCounter, ClientID = Reader["ClientID"].ToString(), ClientName = Reader["ClientName"].ToString(), DocPic = Reader["DocPic"].ToString(), PatientAcceptance = Reader["PatientAcceptance"].ToString(), AddressLocal = Reader["AddressLocal"].ToString(), AddressBroad = Reader["AddressLocal"].ToString(), Phone = Reader["Phone"].ToString(), latitude = Reader["Lat"].ToString(), longitude = Reader["Long"].ToString() });
}
}
}




IDCounter++;
}

Connection.Close();
return ClientsData;
}

map 模型.cs

public class ClientInfo
{
public int Id { get; set; }
public string ClientID { get; set; }
public string ClientName { get; set; }

public List<string> DocNames { get; set; }

public string DocPic { get; set; }

public string PatientAcceptance { get; set; }
public string AddressLocal { get; set; }
public string AddressBroad { get; set; }
public string Phone { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }


}

最佳答案

您是否曾经将 DocNames 设置为任何内容?如果不是,它将为空。

ClientInfo 的构造函数中你应该有

DocNames = new List<string>();

初始化一个空列表。

关于c# - 如何在不获取 NULLREFERENCEEXCEPTION 的情况下添加到列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20590600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com