-1

我可以使用 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);
}
4

1 回答 1

2

I do not know how to access the Dictionary out-side of a foreach.

you are doing it yourself here

string en = dict["encrypt"];

But, i think your problem is that you are unable to access it elsewhere. if you are unable to access it somewhere, then you need to assign it to some variable that is accessible through out your form. As i see that you are trying to access it from your form frmControlProp. So, in your function setFrmControlTagProperties you need to assign dictionary to your form.

First of all create a public property that gets Dictionary. and then assign it like this

frmControlProp.Dict = dict;

then you can get it like this

public void textBox_LostFocus(object sender, EventArgs e)
{
    var c = (Control)sender;
    string cn = c.Name;

    //read the values here
    var cd = frmControlProp.Dict.Keys.ToArray();

}
于 2013-08-16T14:52:16.347 回答