Is list[i] an alias for list.get_item(i) in C#?

久未见 提交于 2019-12-23 16:22:04

问题


I'm passing a lambda expression as a parameter.

In this case, someObject has a property called property accessible with someObject.property.

When I pass: o => o.childListOfObjects[0].property,

where childListOfObjects is a List<someObejct> and ,

expression.Body returns o => o.childListOfObjects.get_Item(0).property.

Skip to the end:

Is list[i] an alias for list.get_item(i) in C#?


回答1:


Yes, properties in general are just syntactic sugar around get_PropertyName and set_PropertyName methods.

Indexers -- for example, list[i] -- are just a special type of property, basically syntactic sugar around get_Item(i) and set_Item(i) methods.

(Note that the indexer property doesn't necessarily have to be called Item, but that's what it's called on List<T>, and that's the default name given to indexers on custom types too unless you override it using IndexerNameAttribute.)




回答2:


The documentation for List<T> says it this way:

The default Item property (the indexer in C#) is used to retrieve an item

So yes, list[i] is the indexer, which is the default property, which in this case is Item. It will get or set Item[i] depending on whether the context is reading or writing.

See also: Indexers




回答3:


The square brackets can be overloaded, they're called indexers. So we need to know what class list is an instance of.

EDIT: Whoops, didn't see that list is a List. I'm not sure what method you mean, though, there is no List<T>.getItem().




回答4:


not necessarily. List defines an indexer that will most likely just call the get_item but that's not guaranteed, there might be more hidden logic defined in the indexer... but the answer is probably yes.



来源:https://stackoverflow.com/questions/6202523/is-listi-an-alias-for-list-get-itemi-in-c

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