现实世界中的用例C#索引? [英] Real world use cases for C# indexers?

查看:102
本文介绍了现实世界中的用例C#索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多的C#索引器的例子,但以何种方式这将有助于我在现实生活中的情况。

I've seen lot of examples for c# Indexers, but in what way will it help me in real life situations.

我知道C#大师也不会增加这一点,如果它不是一个严重的功能,但我想不出一个现实世界的情况(而不是富巴东东)使用索引。

I know the C# guru wouldn't have added this if it wasn't a serious feature, but i cant think of a real world situation (not the foo bar stuff) to use indexers.

请注意:我认识一个有关问题的存在,但它不 ŧ帮助我很多。

Note:I realize a related question exists, but it doesn't help me much.

推荐答案

我的方式看索引是(正确或错误!),通过索引访问的东西应该比访问任何其他方式更有效,因为在一些这样,形状或形式,其索引我使用的存储某种形式的首页的允许访问的方式,当它来快速查找值的类。

The way I look at indexers is that (rightly or wrongly!), accessing something by index should be more efficient than accessing it any other way, because in some way, shape or form, the class whose indexer I'm using stores some form of index that allows it to quickly lookup values when accessed that way.

典型的例子是一个数组,数组的使用code myArray的[3],编译器/间preTER知道数组有多大(内存明智)的元素,当你访问元素n是,可以把它当作一个从数组的起始位置的偏移。你也可以的for(int i = 0; I< myarray.length;我++){如果(I = 3),那么{..做的东西}}(不是说你会永远想!),这将是效率较低。这也显示了数组是一个多么坏的榜样。

The classic example is an array, when you access element n of an array by using the code myarray[3], the compiler/interpreter knows how big (memory-wise) elements of the array are and can treat it as an offset from the start of the array. You could also "for(int i = 0; i < myarray.length; i++) { if (i = 3) then { .. do stuff } }" (not that you'd ever want to!), which would be less efficient. It also shows how an array is a bad example.

假设你有一个集合类店,嗯​​,DVD光盘,所以:

Say you had a collection class that stores, umm, DVDs, so:

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#索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆