我看过很多关于 c# 索引器的例子,但它在现实生活中对我有什么帮助。
我知道 C# 大师不会添加它,如果它不是一个重要的功能,但我无法想到使用索引器的真实世界情况(不是 foo bar 的东西)。
注意:我实现了一个related question存在,但对我帮助不大。
最佳答案
我看待索引器的方式是(正确或错误!),通过索引访问某些东西应该比以任何其他方式访问它更有效,因为在某种程度上,形状或形式,我正在使用其索引器的类存储某种形式的索引,允许它在以这种方式访问时快速查找值。
经典示例是一个数组,当您使用代码 myarray[3] 访问数组的元素 n 时,编译器/解释器知道数组的元素有多大(内存方面)并且可以将其视为从数组开始的偏移量。你也可以 "for(int i = 0; i < myarray.length; i++) { if (i = 3) then { .. do stuff } }"
(不是你想要的!),这会降低效率。它还显示了数组是一个糟糕的例子。
假设您有一个存储 DVD 的集合类,那么:
public class DVDCollection
{
private Dictionary<string, DVD> store = null;
private Dictionary<ProductId, string> dvdsByProductId = null;
public DVDCollection()
{
// gets DVD data from somewhere and stores it *by* TITLE in "store"
// stores a lookup set of DVD ProductId's and names in "dvdsByProductid"
store = new Dictionary<string, DVD>();
dvdsByProductId = new Dictionary<ProductId, string>();
}
// Get the DVD concerned, using an index, by product Id
public DVD this[ProductId index]
{
var title = dvdsByProductId[index];
return store[title];
}
}
只是我的 2p,但是,就像我说的,..我一直认为“索引器”是从某物中获取数据的权宜之计。
关于c# - C# 索引器的实际用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2185071/