未添加到词典中的项
本文关键字:添加 | 更新日期: 2023-09-27 17:59:10
我想将sql数据库中的项添加到字典中,但在对象引用中输入的值为null,这是使用atm 的代码im
public static Dictionary<string, prizedbinfo> dbprizes = new Dictionary<string, prizedbinfo>();
private void LoadData(string dataloc)
{
if (!File.Exists(dataloc))
{
MessageBox.Show(dataloc + " not found.");
return;
}
var connection = new SQLiteConnection("Data Source=" + dataloc);
connection.Open();
var datacommand = new SQLiteCommand("SELECT prizeID, createdOn, expiresOn, modifiedOn, status, redeemedOn, giftedOn, claimedOn FROM mySnackData", connection);
List<string[]> datas = ExecuteStringCommand(datacommand, 9);
foreach (string[] row in datas)
{
if (!Program.dbprizes.ContainsKey(row[0]))
{
Program.dbprizes.Add(row[0], new prizedbinfo(row));
}
}
connection.Close();
}
prizedbinfo对象是
class prizedbinfo
{
public prizedbinfo(string[] dbdata)
{
string prizeID = dbdata[0];
string createdOn = dbdata[1];
string expiresOn = dbdata[2];
string modifiedOn = dbdata[3];
string status = dbdata[4];
string redeemedOn = dbdata[5];
string giftedOn = dbdata[6];
string claimedOn = dbdata[7];
string name = dbdata[8];
}
public string prizeID { get; set; }
public string createdOn { get; set; }
public string expiresOn { get; set; }
public string modifiedOn { get; set; }
public string status { get; set; }
public string redeemedOn { get; set; }
public string giftedOn { get; set; }
public string claimedOn { get; set; }
public string name { get; set; }
}
我已经用断点测试过了,所有的数据都被正确地添加到了数据和行中,但由于某种原因,没有添加到prizedbinfo对象中。
从prizedbinfo
构造函数中的所有变量中删除string
关键字。您正在创建立即超出范围的局部变量,因此您正在丢失您的值。
public prizedbinfo(string[] dbdata)
{
prizeID = dbdata[0];
createdOn = dbdata[1];
expiresOn = dbdata[2];
modifiedOn = dbdata[3];
status = dbdata[4];
redeemedOn = dbdata[5];
giftedOn = dbdata[6];
claimedOn = dbdata[7];
name = dbdata[8];
}