【问题标题】:Adding value from a dictionary c#从字典c#中添加值
【发布时间】:2016-07-19 09:12:58
【问题描述】:

我有一个添加标签页的方法,我为标签页创建了一个字典,因为它们应该显示在它们的每个模式(键)中

我想在 forech 上迭代我的 SwitchMode 方法并添加标签页。

我的代码:

    [Flags]
    public enum Mode
    {
        Start = 1,
        Test = 1 << 1,
        Config = 1 << 2,
    }

迭代字典 - > 在这里我需要帮助 - 我如何添加所有标签页,而不仅仅是第一个标签页,这种迭代是否正确?

public void SwitchMode (Mode mode)
        {
            foreach (var m in _tabDict)
            {
                if (m.Value == Mode.Start)
                {
                    AddTabPage (_tabDict.First ().Key);
                }
                if (m.Value == Mode.Test)
                {
                    AddTabPage (_tabDict.First ().Key);
                    // AddTabPage (_tabDict.All ()); // doesn't work
                }
                if (m.Value == Mode.Config)
                {
                    AddTabPage (_tabDict.First ().Key);
                }

            }
        }

【问题讨论】:

  • m 是 KeyValuePair 并具有 Key 属性 (m.Key)。是你要找的吗?

标签: c# winforms dictionary foreach


【解决方案1】:

您可以遍历 Keys 集合

foreach (Type key in _tabDict.Keys) {
    AddTabPage(key);
}

我不明白你的场景中模式标志的功能是什么。它不在 AddTabPage 中使用。因此,一个选项卡和另一个选项卡之间没有区别。

【讨论】:

    【解决方案2】:

    你快到了,在你的循环中使用m.Key

    public void SwitchMode(Mode mode)
    {
        foreach (var m in _tabDict)
        {
            if (m.Value == Mode.Start)
            {
                AddTabPage(m.Key);
            }
            if (m.Value == Mode.Test)
            {
                AddTabPage(m.Key);
            }
            if (m.Value == Mode.Config)
            {
                AddTabPage(m.Key);
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多