【问题标题】:What is the best C# collection with two keys and an object?具有两个键和一个对象的最佳 C# 集合是什么?
【发布时间】:2009-07-23 13:44:36
【问题描述】:

我有一个 MenuManager 类,每个模块都可以向其中添加要加载到主要内容中的键和元素:

private Dictionary<string,object> _mainContentItems = new Dictionary<string,object>();
public Dictionary<string,object> MainContentItems
{
    get { return _mainContentItems; }
    set { _mainContentItems = value; }
}

所以客户模块像这样注册它的视图:

layoutManager.MainContentViews.Add("customer-help", this.container.Resolve<HelpView>());
layoutManager.MainContentViews.Add("customer-main", this.container.Resolve<MainView>());

所以稍后我会说:

layoutManager.ShowMainContentView("customer-help");

为了获得默认视图(注册的第一个视图),我说:

layoutManager.ShowDefaultView("customer");

这很好用。

但是,我想用分隔模块名称和视图名称的连字符消除“代码异味”,所以我想用这个命令注册:

layoutManager.MainContentViews.Add("customer","help", this.container.Resolve<HelpView>());

但是替换我当前字典的最佳方法是什么,例如想到的是这些:

  • Dictionary&lt;string, string, object&gt; (doesn't exist)
  • Dictionary&lt;KeyValuePair&lt;string,string&gt;, object&gt;
  • Dictionary&lt;CUSTOM_STRUCT, object&gt;

新集合需要能够做到这一点:

  • 获取带有模块和视图键的视图(例如,“客户”、“帮助”返回 1 个视图)
  • 按模块键获取所有视图的集合(例如“客户”返回 5 个视图)

【问题讨论】:

    标签: c# wpf collections prism


    【解决方案1】:

    严格满足您的条件,使用Dictionary&lt;string, Dictionary&lt;string, object&gt;&gt; ;

    var dict = new Dictionary<string, Dictionary<string, object>>();
    ...
    object view = dict["customer"]["help"];
    Dictionary<string, object>.ValueCollection views = dict["customer"].Values;
    

    【讨论】:

      【解决方案2】:

      similar thread 中所述,在 .NET 4 中表示 2 键字典的一种好方法是使用 Tuple 类:

      IDictionary<Tuple<K1, K2>, V>
      

      【讨论】:

        【解决方案3】:

        您所描述的内容听起来像是字典中的复合键,而不是两个键。我建议设置一个简单的结构来表示这个键:

        struct Section {
           string Area { get; set; } 
           string Area2 { get; set; }
        
           // override ToHashCode, Equals and implement IComparable.
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-01
          • 2020-11-26
          • 2019-11-28
          • 1970-01-01
          • 2016-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多