Item property in c#

◇◆丶佛笑我妖孽 提交于 2021-02-19 03:20:18

问题


Is item property in c# is always used like indexer in c#? Let me explain with an example. ArrayList is having many properties like count,capacity, and one of them is Item.Item Property unlike count and capacity which are accessed by putting dot after name of ArrayList ,is not used by keyword Item but directly by Indexer. e.g.

ArrayList MyList = new ArrayList();
MyList.add(100);
MyList[0] = 200;

Like in above e.g. uses the Item keyword to define the indexers instead of implementing the Item property.

My Query : Can i say whenever in c# Item property is explained it should be implicitly understood that it's referring Indexer in term?


回答1:


MyList[0] is an indexer, it makes you access the object like an array. Definition syntax is like this:

public T this[int index]
{
   // reduced for simplicity
   set { internalArray[index] = value; }
   get { return internalArray[index]; }
}

The compiler generate methods:

public T get_Item(inde index)
{
    return internalArray[index];
}

and

public void set_Item(inde index, T value)
{
    internalArray[index] = value;
}

There is no relation between List.Add(something) and List[0] = something. The first is a method that appends a values to the end of the list. The second is a syntactic sugar that calls a method List.set_Item(0, something).

Unless the [] syntax is directly supported by the CLR (as is array), then it is an indexer defined inside the class that uses syntactic sugar as explained above.




回答2:


According to the documentation above, the indexer is defined as follows.

public virtual object this[
    int index
] { get; set; }

More precisely, there is actually no Item property, but the indexer is termed as 'Item property' in the documentation.



来源:https://stackoverflow.com/questions/38260565/item-property-in-c-sharp

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