.NET dictionary with two keys and one value

前端 未结 13 2973
盖世英雄少女心
盖世英雄少女心 2020-12-14 00:23

Is there a dictionary available in .NET that could hold 2 keys and one value. Like

Dictionary(Of TKey, Of TKey, TValue)

I have

13条回答
  •  再見小時候
    2020-12-14 00:37

    At first I thought I could create a class that implmented IDictionary and IDictionary, and just have a single Dictionary as a field and delegate most methods to the single dictionary with minimal logic.

    The problem with this approach is that TKey1 and TKey2 could be of the same type, which is a problem because this new class would be implementing the same interface twice. Which method should the runtime invoke when TKey1 is a string and TKey2 is also a string?

    As others above have suggested, it is best to create your own data structure that utilizes one or two dictionaries behind the scenes. For example, if you knew ahead of time that you wanted to use a string and an int as your keys, you could use this approach:

    public class StringIntDictionary : IDictionary, IDictionary
    {
        private IDictionary _dictionary = new Dictionary();
        // implement interface below, delegate to _dictionary
    }
    

    That would allow you to look use both string and int keys:

    var dict = StringIntDictionary();
    dict["abc"] = true;
    dict[123] = true;
    

提交回复
热议问题