C#索引器的真实世界用例?

Viv*_*ard 44 c# indexer

我已经看过很多关于c#Indexers的例子,但它在现实生活中会以什么方式帮助我.

我知道如果它不是一个严肃的功能,C#guru就不会添加它,但我不能想到使用索引器的真实世界情况(不是foo bar的东西).

注意:我意识到存在一个相关的问题,但它对我没有多大帮助.

Rob*_*Rob 33

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

经典示例是一个数组,当您使用代码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];
    }
}
Run Code Online (Sandbox Code Playgroud)

只是我的2p,但是,就像我说的那样......我一直认为"索引器"是一种从数据中获取数据的权宜之计.


Jon*_*eet 24

Skurmedel提到的最明显的例子是List<T>Dictionary<TKey, TValue>.你更喜欢什么:

List<string> list = new List<string> { "a", "b", "c" };
string value = list[1]; // This is using an indexer

Dictionary<string, string> dictionary = new Dictionary<string, string>
{
    { "foo", "bar" },
    { "x", "y" }
};
string value = dictionary["x"]; // This is using an indexer
Run Code Online (Sandbox Code Playgroud)

?现在,您需要编写索引器(通常在创建类似集合的类时)可能相对较少,但我怀疑您经常使用它们.


Rob*_*vey 9

Microsoft 有一个使用索引器将文件视为字节数组的示例.

public byte this[long index]
{
    // Read one byte at offset index and return it.
    get 
    {
        byte[] buffer = new byte[1];
        stream.Seek(index, SeekOrigin.Begin);
        stream.Read(buffer, 0, 1);
        return buffer[0];
    }
    // Write one byte at offset index and return it.
    set 
    {
        byte[] buffer = new byte[1] {value};
        stream.Seek(index, SeekOrigin.Begin);
        stream.Write(buffer, 0, 1);
    }
}
Run Code Online (Sandbox Code Playgroud)


sco*_*ttm 5

假设您有一组对象,您希望能够通过除了它在集合中的顺序之外的其他内容进行索引.在下面的示例中,您可以看到如何使用某个对象的"Location"属性并使用索引器,返回集合中与您所在位置匹配的所有对象,或者在第二个示例中,返回包含特定Count的所有对象(对象.

class MyCollection {

  public IEnumerable<MyObject> this[string indexer] {
    get{ return this.Where(p => p.Location == indexer); }
  }

  public IEnumerable<MyObject> this[int size] {
    get{ return this.Where(p => p.Count() == size);}
  }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*att 5

一旦.NET得到泛型,我实现索引器(实现强类型集合)的最大原因就消失了.

  • 为什么索引器的需求会减少泛型?或者你的意思是你不再需要编写自己的收藏品? (12认同)