需要用其他方法检查字典,或将字典设为全局

问题描述 投票:0回答:3

我需要查看一个下拉框是否已从词典中选择了一个键。字典是另一种方法(我相信它叫做方法)。我一直在寻找如何使字典具有全局性,但我不知道如何做到这一点。也许有更好的方法?

感谢您的帮助,我写了一些代码来展示我要在下面完成的工作。

public void Dictionary()
        {
            var names = new Dictionary<string, double[]>();
            names.Add("Kevin", new[] { 74.5, 6.35});
            names.Add("Rob", new[] { 2.5, 9.46}); 
        }

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (var kvp in names)
            {
                if combobox.Text == kvp.Key
                {
                    solution = true;
                }
            }

        }
c# dictionary methods global
3个回答
0
投票

您可以处理此问题的另一种方法是返回字典。

    public Dictionary GetDictionary()
    {
        var names = new Dictionary<string, double[]>();
        names.Add("Kevin", new[] { 74.5, 6.35});
        names.Add("Rob", new[] { 2.5, 9.46}); 
        return names;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
     {
        foreach (var kvp in GetDictionary())
        {
           if (combobox.Text == kvp.Key) 
           {
             solution = true;
           }
        }
      }

0
投票

公开该方法是使其可以在全球范围内访问的原因。有几处缺失:方法本身缺少返回类型,需要直接从combobox1_SelectedIndexChanged方法中调用它。

最佳实践是不要在自定义代码中使用.NET框架中的保留名称-在这里,我已将方法名称更改为GetDropdownChoices,添加了返回类型,然后在foreach循环之外调用了该方法。对于性能优化,此代码中有两个建议-一个是使用.ContainsKey方法而不是==并循环浏览字典中的每个项目。

    public Dictionary<string, double[]> GetDropdownChoices()
    {
        var names = new Dictionary<string, double[]>();
        names.Add("Kevin", new[] { 74.5, 6.35});
        names.Add("Rob", new[] { 2.5, 9.46}); 
        return names;
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var choices = GetDropdownChoices();

        if (choices.ContainsKey(combobox.Text)) 
        {
             solution = true;
        }
    }

-1
投票
public class Foo
{
    private readonly Dictionary<string, double[]> _names;

    public Foo()
    {
        _names = new Dictionary<string, double[]>();
    }

    public void Dictionary()
    {
        _names.Add("Kevin", new[] { 74.5, 6.35 });
        _names.Add("Rob", new[] { 2.5, 9.46 });
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        foreach (var kvp in _names)
        {
            if (combobox.Text == kvp.Key) // assuming you have already a declared "combobox" member
            {
                solution = true;
            }
        }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.