gpt4 book ai didi

c# - 为双向字典使用集合初始值设定项

转载 作者:行者123 更新时间:2023-11-30 23:23:10 24 4
gpt4 key购买 nike

关于双向字典: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# - 为双向字典使用集合初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38482454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com