C#有序字典索引
我正在考虑使用OrderedDictionary。作为一个键,我想使用一个长值(id),该值将是一个自定义对象 我使用OrderedDictionary是因为我希望通过对象的Id获取对象,并且希望通过对象的“集合”索引获取对象 我想这样使用OrderedDictionary:C#有序字典索引,c#,winforms,ordereddictionary,C#,Winforms,Ordereddictionary,我正在考虑使用OrderedDictionary。作为一个键,我想使用一个长值(id),该值将是一个自定义对象 我使用OrderedDictionary是因为我希望通过对象的Id获取对象,并且希望通过对象的“集合”索引获取对象 我想这样使用OrderedDictionary: public void AddObject(MyObject obj) { _dict.Add(obj.Id, obj); // dict is declared as OrderedDictionary _dict
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;
}
在我的代码的其他地方,我有类似的东西:
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;
因此,当我传递_currentIndex时,它看到它是一个int,因此它知道查找索引而不是id,因为类型为long?的id@马丁,对不起,我从来没有注意到你使用的是
OrderedDictionary
请查看我的更新答案。没问题。但是_currentIndex是一个int,用于按索引而不是Id获取MyObject。所以我想我不必强制转换_currentIndex?当我想按id检索MyObject时,我只需要使用索引器,对吗?@Martijn:啊,我以为你想按id检索它,它一直按索引进行检索。在这种情况下,不需要进行任何强制转换,只要传递的值是一个显式的整数,就可以了。啊,好的,OrderedDictionary足够聪明,可以确定我想要什么:根据Id或索引获取对象,因为值类型。。?