gpt4 book ai didi

C# 有序字典索引

转载 作者:行者123 更新时间:2023-11-30 17:22:09 25 4
gpt4 key购买 nike

我正在考虑使用 OrderedDictionary。作为键,我想使用一个长值 (id),该值将是一个自定义对象。

我使用 OrderedDictionary 是因为我想通过它的 Id 获取一个对象,并且我想通过它的“集合”索引获取一个对象。

我想像这样使用 OrderedDictionary:

public void AddObject(MyObject obj)
{
_dict.Add(obj.Id, obj); // dict is declared as OrderedDictionary _dict = new OrderedDictionary();
}

在我的代码的其他地方,我有类似这样的东西:

public MyObject GetNextObject()
{
/* In my code keep track of the current index */

_currentIndex++;
// check _currentindex doesn't exceed the _questions bounds
return _dict[_currentIndex] as MyObject;
}

现在我的问题是。在最后一种方法中,我使用了索引。假设 _currentIndex 设置为 10,但我还有一个 id 为 10 的对象。我已将 Id 设置为键。

MyObject 的Id 是long 类型?。这会出错吗?

最佳答案

已更新,因为我从未注意到 OrderedDictionary 部分!索引器覆盖了将通过键检索值的 object 或将通过索引检索值的 int 。如果您希望通过键检索索引,则需要将索引转换为对象,例如

_dict[(object)_currentIndex] as MyObject;

关于C# 有序字典索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2855843/

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