这是工作代码:
static class Global
{
private static Dictionary<string, int> emails_compsIDs;
private static Dictionary<string, int> set_emails_compsIDs { set { emails_compsIDs = value; } }
private static DataTable MultiCompReport;
static Global()
{
string e = string.Empty;
Dictionary<string, int> emails_compsIDs = new Dictionary<string, int>();
DataTable t = MySql.ExecuteSelect("SELECT Email, Company_ID FROM potencial_contact WHERE Email != '' AND Email IS NOT NULL");
foreach (DataRow r in t.Rows)
{
int comp_id = Convert.ToInt32(r["Company_ID"]);
e = r["Email"].ToString().Replace("\r", "").Replace("\t", "").Replace("\n", "").Trim().ToLower().Trim();
if (!string.IsNullOrWhiteSpace(e) && !emails_compsIDs.ContainsKey(e))
{
try
{
emails_compsIDs.Add(e, comp_id);
}
catch (Exception ex)
{
throw ex;
}
}
}
if (emails_compsIDs.ContainsKey("linda@andatrade.com"))
Console.WriteLine("Eureka");
set_emails_compsIDs = emails_compsIDs;
}
}
但是,当我只是emails_compsIDs = new Dictionary<string, int>();
为了在构造函数中初始化字典时,代码只填充了第一行。通过在 ctor 中创建一个实例,然后将结果放入我的静态字典中,它填充了所有行。