我正在寻找 C# 中类似于 Dictionary 的数据结构,我可以在其中使用索引和键访问值。值的类型是 Class 而不是字符串。
我正在创建一个类库,我试图在其中创建一个名为 Item
的方法,该方法从我的值和键对数据结构中返回值。但是如果我将整数参数传递给 Item
那么它应该通过使用索引获取值,如果将字符串类型传递给 Item
那么它应该通过使用键访问值(如在字典中)
注意:我提到了this关联 。但是 System.Collections.Specialized.NameValueCollection 不能使用,因为它只能将字符串存储为值,但我想要类类型作为值。我想使用键和索引访问值。
最佳答案
如果非通用集合满足您的需求,您可以使用 OrderedDictionary
.不过,如果您使用值类型,则需要进行大量的装箱和拆箱操作。
如果您绝对想要通用版本,则必须构建自己的版本。例如:
public class OrderedDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> _innerDictionary = new Dictionary<TKey, TValue>();
private List<TKey> _keys = new List<TKey>();
public TValue this[TKey key]
{
get
{
return _innerDictionary[key];
}
set
{
if(!_innerDictionary.ContainsKey(key))
{
_keys.Add(key);
}
_innerDictionary[key] = value;
}
}
public TValue this[int index]
{
get
{
return _innerDictionary[_keys[index]];
}
set
{
_innerDictionary[_keys[index]] = value;
}
}
public void Add(TKey key, TValue value)
{
_innerDictionary.Add(key, value);
_keys.Add(key);
}
public void Clear()
{
_innerDictionary.Clear();
_keys.Clear();
}
public bool Remove(TKey key)
{
if (_innerDictionary.Remove(key))
{
_keys.Remove(key);
return true;
}
else
{
return false;
}
}
}
您可能需要更多的异常处理,但大多数功能都在这里。另外,如果你想实现 IDictionary<TKey,TVale>
从那里,缺失的成员应该是微不足道的。
关于c# - 以键和值作为类类型并使用键和索引访问值的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750897/