c# . net和直接对象集合
本文关键字:对象 集合 net | 更新日期: 2023-09-27 18:10:00
嘿,有没有像arrayList这样的集合类型,我可以使用ID添加对象?
作为我的文章的标题,有效地暗示了一个直接对象集合。例如:
DirectCollection.addAt(23, someobject);
和
DirectCollection.getAt(23);
等等
我知道arraylist在这种情况下是可用的,但我必须生成一个空引用对象的初始条目,如果如果对象有一个像23这样的ID,我必须生成22个其他条目来添加它,这显然是不切实际的。
基本上使用对象位置值作为唯一ID。
任何想法吗?
许多谢谢。您可以使用Dictionary<int, YourType>
这样的:
var p = new Dictionary<int, YourType>();
p.Add(23, your_object);
YourType object_you_just_added = p[23];
使用字典
Dictionary<int, YourType>
它允许您添加/获取/删除具有给定键和非连续范围的项。
你可以使用Dictionary
您的示例代码将非常简单:
Dictionary<int, AType> directCollection = new Dictionary<int, AType>();
directCollection.Add(23, someObjectOfAType);
AType anObject = directCollection[23];
我认为KeyedCollection或Dictionary是你需要的。
使用System.Collections.Hashtable
。它允许存储异构类型的对象(一个Hashtable
可以保存多种类型的对象)。
的例子:
System.Collections.Hashtable keyObjectMap = new System.Collections.Hashtable();
//Add into Hashtable
keyObjectMap["Key_1"] = "First String";
keyObjectMap["Key_2"] = "Second String";
//Add the value type
keyObjectMap["Key_3"] = 1;
keyObjectMap["Key_4"] = new object();
//Get value/object from Hashtable
string value = (string)keyObjectMap["Key_2"];
int intValue = (int)keyObjectMap["Key_3"];