C# 对双向字典使用集合初始值设定项

C# 对双向字典使用集合初始值设定项,c#,dictionary,ienumerable,bidirectional,C#,Dictionary,Ienumerable,Bidirectional,关于双向词典: 我的bi字典是: internal class BiDirectionContainer<T1, T2> { private readonly Dictionary<T1, T2> _forward = new Dictionary<T1, T2>(); private readonly Dictionary<T2, T1> _reverse = new Dictionary<T

关于双向词典:

我的bi字典是:

    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);
        }
    }
内部类双向容器
{
专用只读词典_forward=新词典();
专用只读词典_reverse=新词典();
内部T2本[T1键]=>_前向[key];
内部T1此[T2键]=>_反向[键];
内部空白添加(T1元素1、T2元素2)
{
_前进。添加(元素1、元素2);
_反向。添加(元素2,元素1);
}
}
我想添加如下元素:

BiDirectionContainer<string, int> container = new BiDirectionContainer<string, int>
{
    {"111", 1},
    {"222", 2},
    {"333", 3},    
}
BiDirectionContainer=新的BiDirectionContainer
{
{"111", 1},
{"222", 2},
{"333", 3},    
}
但是我不确定在双向容器中使用
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);
    }
}
内部类双向容器:IEnumerable
{
专用只读词典_forward=新词典();
专用只读词典_reverse=新词典();
内部T2本[T1键]=>_前向[key];
内部T1此[T2键]=>_反向[键];
IEnumerator IEnumerable.GetEnumerator()
{
返回_forward.GetEnumerator();
}
公共IEnumerator GetEnumerator()
{
返回_forward.GetEnumerator();
}
内部空白添加(T1元素1、T2元素2)
{
_前进。添加(元素1、元素2);
_反向。添加(元素2,元素1);
}
}

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

@Dirk Vollmar我只需要简单的初始化。我不打算在每个国家使用它。但我担心我的课会把其他会用它的人弄糊涂。