使用BiDirection字典的集合初始值设定项

本文关键字:BiDirection 字典 集合 使用 | 更新日期: 2023-09-27 17:57:47

关于双向字典:C#中的双向1对1字典

我的双字典是:

    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是否正确?如果是,我应该返回什么?是否有其他方法可以实现此类功能?

使用BiDirection字典的集合初始值设定项

最简单的方法可能是枚举正向(或反向,看起来更自然的)字典的元素,如下所示:

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方法(即,基本上参数的数量和类型必须匹配)。该接口是编译器所必需的,但在初始化集合时不会调用GetEnumerator方法(只有add方法是)。它是必需的,因为集合初始值设定项应该只适用于实际是集合的东西,而不仅仅是具有add方法的东西。因此,只添加接口而不实际实现方法体(public IEnumerator GetEnumerator(){ throw new NotImplementedException(); })是可以的