c# - C# 索引器的实际用例?

标签 c# indexer

我看过很多关于 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/

相关文章:

Eclipse Indexer 中的 C++11 设置与 git 冲突

c++ - 如何调整 Eclipse 的 C++ 索引器?

wpf - 如何将索引属性绑定(bind)到 WPF 中的控件

c# - Silverlight:如何在设置 DataContext 属性后强制绑定(bind)

c# - asp.net mvc url中的双引号

c# - catch block 没有在另一个线程中捕获异常

c# - 使用 Moq 通过任意键和值设置任意

c# - 如何避免格式化 Razor View 时的字符串损坏

c# - 转换来自不同 namespace 的相同对象?

c# - 在 C# 中使用索引器访问 "this"指针/引用