【问题标题】:What is the simplest way to rename Key and Value properties in Dictionary<> subclasses在 Dictionary<> 子类中重命名 Key 和 Value 属性的最简单方法是什么
【发布时间】:2014-01-24 08:40:07
【问题描述】:

我有一个包含多层嵌套字典的复杂数据容器。

但拥有Key 和Value 属性使其不直观且难以使用。

请建议在Dictionary&lt;,&gt; 子类中重命名 Key 和 Value 属性的最简单方法。

更新:

Patryk Ćwiek:如果你实现了IDictionary&lt;TKey, TValue&gt;,你也不能重命名属性,因为它们是契约的一部分。

你是对的。我的问题不正确。在IDictionary 中使用KeyValuePair 会将对属性限制为Key 和Value。因此,如果我们想要非键/值对,我们必须使用自定义 KeyValuePair 结构来实现 IDictionary。或者可能有其他一些棘手的方法?

PS。也许有人建议使用IDictionary 代码生成模板?

【问题讨论】:

  • 如果它是一个子类,那么你不能。如果你实现IDictionary&lt;TKey, TValue&gt;,你也不能重命名属性,因为它们是契约的一部分。您可能可以做的是组合而不是继承。
  • 我有一个包含多层嵌套字典的复杂数据容器。如果你只是为了拥有一个复合键而嵌套它们,那么创建一个struct MyKey { string x; int y; },但让它们成为属性。做 gethashcode/平等的东西。现在您没有嵌套字典。
  • @PatrykĆwiek 你总是可以做显式接口实现来“隐藏”一些你需要实现的成员。
  • @ta.speot.is 是的。但在 OP 的情况下,他似乎想打破字典合同,这可能暗示他的数据结构既不应该 be 也不应该 behave 像 Dictionary&lt;_,_&gt;/@ 987654335@,无法替代。
  • 我同意上述所有 cmets,但我不同意原始 OP 所说的字典的键/值属性名称是“非直观的”。如果字典没有这些属性,我会有点困惑!我想知道他想用什么代替它们?

标签: c# .net dictionary


【解决方案1】:

使用您想要的属性名称制作您自己的界面。然后,让您的具体类实现您的自定义接口。

要保持代码 DRY,请创建一个私有字典,将所有工作委托给它。您甚至可以通过将所需的方法委托给您的私有变量,让您的自定义接口成为 Enumerable(或 IDictionary 实现的任何其他接口)。

这是一个例子。您只需将代码从使用 IDictionary 更改为 IComplexDataContainer。

  interface IComplexDataContainer<TKey, TValue>
    : IEnumerable<KeyValuePair<TKey,TValue>>
  {
    TValue this[TKey index] { get; set; }
  }

  class MyComplexDataContainer<TKey, TValue>
    : IComplexDataContainer<TKey, TValue>
  {
    IDictionary<TKey, TValue> hiddenHelper { get; set; }

    public MyComplexDataContainer()
    {
      hiddenHelper = new Dictionary<TKey, TValue>();
    }

    // delegate all of the work to the hidden dictionary
    public TValue this[TKey index]
    {
      get
      {
        return hiddenHelper[index];
      }
      set
      {
        hiddenHelper[index] = value;
      }
    }

    // Just delegate the IEnumerable interface to your hidden dictionary
    // or any other interface you want your class to implement
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
      return hiddenHelper.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }

那么你就可以这样使用:

  IComplexDataContainer<string, int> myData = new MyComplexDataContainer<string,int>();
  myData["tom"] = 18;
  myData["dick"] = 22;
  myData["harry"] = myData["tom"];

【讨论】:

  • 感谢您的回答。问题是 KeyValuePair 约束 Key 和 Value 属性,我想重命名。
猜你喜欢
  • 1970-01-01
  • 2021-03-25
  • 1970-01-01
  • 2014-06-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
相关资源
最近更新 更多