What is the easiest way to rename key and value properties to subclasses Dictionary <>

I have a complex data container with several levels of nested dictionaries.

But the presence of the properties Keyand Valuemakes it unintuitive and difficult to use.

Please provide the easiest way to rename key and value properties into subclasses Dictionary<,>.

Update:

Patryk ฤ†wiek: if you implement IDictionary<TKey, TValue>, you also cannot rename properties because they are part of the contract.

You're right. My question was wrong. Using KeyValuePairin IDictionarylimits the properties of the pair Keyand Value. Therefore, if we need a pair without a key / value, we had to implement it IDictionarywith a custom structure KeyValuePair. Or maybe some other complicated way?

PS. Maybe someone will suggest a code generation template IDictionary?

+4
source share
1 answer

Create your own interface with the property names you want. Then, your specific class implements your user interface.

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"];
+3

Source: https://habr.com/ru/post/1523480/


All Articles