c# - 对 BiDirection 字典使用集合初始值设定项

标签 c# dictionary ienumerable bidirectional

关于双向字典:Bidirectional 1 to 1 Dictionary in C#

我的双词典是:

    internal class BiDirectionContainer<T1, T2>
    {
        private readonly Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
        private readonly Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

        internal T2 this[T1 key] => _forward[key];

        internal T1 this[T2 key] => _reverse[key];

        internal void Add(T1 element1, T2 element2)
        {
            _forward.Add(element1, element2);
            _reverse.Add(element2, element1);
        }
    }

我想添加这样的元素:

BiDirectionContainer<string, int> container = new BiDirectionContainer<string, int>
{
    {"111", 1},
    {"222", 2},
    {"333", 3},    
}

但我不确定在 BiDirectionContainer 中使用 IEnumerable 是否正确? 如果是的话我应该返回什么?有没有其他方法可以实现这样的功能?

最佳答案

最简单的可能是枚举向前(或向后,无论看起来更自然)字典的元素,如下所示:

internal class BiDirectionContainer<T1, T2> : IEnumerable<KeyValuePair<T1, T2>>
{
    private readonly Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
    private readonly Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();

    internal T2 this[T1 key] => _forward[key];

    internal T1 this[T2 key] => _reverse[key];

    IEnumerator<KeyValuePair<T1, T2>> IEnumerable<KeyValuePair<T1, T2>>.GetEnumerator()
    {
        return _forward.GetEnumerator();
    }

    public IEnumerator GetEnumerator()
    {
        return _forward.GetEnumerator();
    }

    internal void Add(T1 element1, T2 element2)
    {
        _forward.Add(element1, element2);
        _reverse.Add(element2, element1);
    }
}

顺便说一句:如果您只想使用集合初始值设定项,则 C# 语言规范要求您的类实现 System.Collections.IEnumerable 还提供了适用于每个元素初始值设定项的 Add 方法(即参数的数量和类型基本上必须匹配)。该接口(interface)是编译器需要的,但初始化集合时不会调用 GetEnumerator 方法(只有 add 方法)。这是必需的,因为集合初始值设定项应该仅适用于实际上是集合的事物,而不仅仅是具有 add 方法的事物。 Therefore it is fine仅添加接口(interface)而不实际实现方法主体 (public IEnumerator GetEnumerator(){ throw new NotImplementedException(); })

关于c# - 对 BiDirection 字典使用集合初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38482454/

相关文章:

c# - 在 ASP.NET Core 2.x 中更改密码

c# - 如何 "query"列表<T>

c# - 检查GroupBy Key是否存在

c# - 将 IEnumerable<Dictionary<int, string>> 转换为 List<Dictionary<int, string>>

dictionary - 在Amazon AWS上运行自定义jar时遇到问题

.net - 在 C++ 中实现 GetEnumerator

c# - 在 Sharepoint 中按组获取用户

c# - 如何将此字符串保存到 XML 文件中?

javascript - 根据字典替换字符串中的短语

python - 在 Python 中使用字典作为 switch 语句