[英]Built-in List that can be accessed by index and key
是否可以创建一个可以通过索引或密钥访问的列表?
我正在寻找已经存在但具有此功能的Collection类型,我想避免重新定义索引器
现有答案已经显示了如何添加自己的索引器。
您可能希望查看一些现有的基于键的集合,例如SortedList<,>
,其行为类似于Dictionary<,>
,但允许键和位置索引器使用。
此外 - 您应该能够为这类事物的大部分内容使用继承 - 例如,继承Collection<>
或List<>
。 请注意,如果您的集合实现IList
/ IList<T>
,我不推荐以下(我偶尔会看到):
public SomeType this[int someId] {...}
关键是,人们期望IList[<T>]
的整数索引器是位置的。
有一个类似的问题是什么是.NET中用于通过字符串键或数字索引查找的最佳数据结构? 。
看看KeyedCollection :
class IndexableDictionary<TKey, TItem> : KeyedCollection<TKey, TItem>
{ Dictionary<TItem, TKey> keys = new Dictionary<TItem, TKey>();
protected override TKey GetKeyForItem(TItem item) { return keys[item];}
public void Add(TKey key, TItem item)
{ keys[item] = key;
this.Add(item);
}
}
System.Collections.Specialized.NameValueCollection可以执行此操作,但它只能将字符串存储为值。
System.Collections.Specialized.NameValueCollection k =
new System.Collections.Specialized.NameValueCollection();
k.Add("B", "Brown");
k.Add("G", "Green");
Console.WriteLine(k[0]); // Writes Brown
Console.WriteLine(k["G"]); // Writes Green
public object this[int index]
{
get { ... }
set { ... }
}
除了只做一个整数索引,你可以提供你喜欢的任何其他类型的键
public object this[String key]
{
get { ... }
set { ... }
}
如果您不想定义自己的集合,只需继承List<T>
,或者只使用List<T>
类型的变量。
您可以通过将以下属性添加到集合来添加索引器:
public object this[int index]
{
get { /* return the specified index here */ }
set { /* set the specified index to value here */ }
}
可以通过键入索引器并按[tab] [tab]在Visual Studio中快速添加。
返回类型和索引器类型可以改变。 您还可以添加多个索引器类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.