我可以使用 foreach 遍历 Dictionary 的值。但是,我不知道如何在 foreach 之外访问字典。
代码:
Dictionary<string, dynamic> frmControlProp =
new Dictionary<string, dynamic>();
public void setFrmControlTagProperties(string n, string tagVal)
{
var dict = tagVal.Split('|')
.Select(x => x.Split(':'))
.Where(x => x.Length > 1 && !String.IsNullOrEmpty(x[0].Trim())
&& !String.IsNullOrEmpty(x[1].Trim()))
.ToDictionary(x => x[0].Trim(), x => x[1].Trim());
string en = dict["encrypt"];
string sn = dict["settingName"];
var conTag = new { Encrypt = en, SettingName = sn };
frmControlProp.Add(n, new object());
frmControlProp[n] = conTag;
}
foreach 按预期工作:
foreach (var area in frmControlProp.Keys.ToArray())
{
var areaname = frmControlProp[area].Encrypt;
//MessageBox.Show(areaname.ToString());
}
不确定如何在 foreach 之外访问字典:
public void textBox_LostFocus(object sender, EventArgs e)
{
var c = (Control)sender;
string cn = c.Name;
//var cd = frmControlProp[cn];
//MessageBox.Show(frmControlProp.Keys.ToArray()..ToString());
}
编辑
此代码按预期工作:
public void textBox_LostFocus(object sender, EventArgs e)
{
var c = (Control)sender;
string cn = c.Name.ToString();
MessageBox.Show(frmControlProp[cn].Encrypt);
}