【问题标题】:Use collection initializer for BiDirection dictionary对 BiDirection 字典使用集合初始化器
【发布时间】:2016-07-20 13:18:25
【问题描述】:

关于双向字典: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 是否正确? 如果是我应该返回什么?有没有其他方法可以实现这样的功能?

【问题讨论】:

  • @Dirk Vollmar 我所需要的只是简单的初始化。我不打算在 foreach 语句中使用它。但我担心我的课会混淆其他可以使用它的人。

标签: c# dictionary ienumerable bidirectional


【解决方案1】:

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

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 方法的事物。 Therefore it is fine 只是添加接口而不实际实现方法体(public IEnumerator GetEnumerator(){ throw new NotImplementedException(); }

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2018-10-05
    • 2018-03-01
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多