【问题标题】:C# Ordered dictionary indexC# 有序字典索引
【发布时间】:2011-02-20 19:13:27
【问题描述】:

我正在考虑使用 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?。这有问题吗?

【问题讨论】:

    标签: c# winforms ordereddictionary


    【解决方案1】:

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

    _dict[(object)_currentIndex] as MyObject;
    

    【讨论】:

    • 所以当我通过 _currentIndex 时,它会看到它是一个 int,因此它知道要查找索引而不是 id,因为 id 类型为 long?。 ?
    • @Martin,抱歉,我从未注意到您使用的是 OrderedDictionary,请查看我的更新答案。
    • 没问题。但是 _currentIndex 是一个 int,用于通过索引而不是 Id 获取 MyObject。所以我想我不必强制转换 _currentIndex?当我想要 MyObject 按 id 时,我只需要强制转换索引器,对吧?
    • @Martijn:啊,我以为您希望通过 ID 检索它,它一直按索引进行检索。在这种情况下,只要您传递的值是明确的整数,您就不必进行任何转换,它应该没问题。
    • Aah okee,OrderedDictionary 足够聪明,可以确定我想要什么:由于值类型,通过 Id 或索引获取对象..?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2017-03-17
    • 2015-05-06
    • 2022-10-26
    • 2014-06-06
    • 2011-09-16
    • 2019-02-15
    相关资源
    最近更新 更多