C# Indexer Usage

我怕爱的太早我们不能终老 提交于 2019-12-13 05:08:04

问题


To have an indexer we use the following format:

class ClassName
{
    DataType[] ArrayName = new DataType[Length]; 

    public DataType this[int i]
    {
        get { return ArrayName[i]; }
    }
}

For the sake of simplicity I used the format, even though we can go for a custom indexer also. According to my understanding, we are keeping a propery array that is indexed.

My question is :

  1. Is it a templated property?
  2. When and where could we achieve high degree code optimization using this indexer?

回答1:


It is not about code optimization.
You could write a method in your class that can get you the item from the collection it holds.

e.g.

public DataType GetItemByIndex(int i)
{
}

Indexers are in a way, "syntactic sugar", to let users treat the instance as an array or collection.




回答2:


This isn't a templated property, it is a parameterful property - that is a property that accepts a parameter argument.

This boils down to simply a get_Item(Int32) method in place of a get_Item() method that would normally be emitted by the compiler in place of a parameterless property. As such this doesn't open up much opportunities for optimization.



来源:https://stackoverflow.com/questions/1307354/c-sharp-indexer-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!