在Dictionary<>中重命名Key和Value属性的最简单方法是什么?子类

时间:2014-01-24 08:40:07

标签: c# .net dictionary

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

但拥有KeyValue属性会使其不直观且难以使用。

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

更新

PatrykĆwiek:如果您实施IDictionary<TKey, TValue>,您也无法重命名属性,因为它们是合同的一部分。

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

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

1 个答案:

答案 0 :(得分:3)

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

要保持代码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"];