C# extend indexer?

安稳与你 提交于 2019-12-05 04:20:17

Indexers are actually properties, and extension properties do not exist in C#. So this can't be done the way you want.

See this blog post for some background on the subject, and an explanation as to why that feature was considered, but ultimately omitted from C# 3.0.

No, it isn't. Extension methods are just syntactic sugar for static method call, an indexer is a property.

Doing

object o = new object();
o.ExtensionMethod();

is equivalent to

object o = new object();
Extensions.ExtensionMethod(o);

Extension methods don't change the class in any way, they just provide you with a simpler interface to call static methods.

Unfortunately, no. This would effectively be an "extension property", which isn't supported. You must have it as a method, like your current code.

Note that extension properties have been requested on Connect on multiple occasions, but have never been included in the language.

No you cant extend operators, such as the indexer, with extension methods.

No this is not possible. Extension methods are limited to methods only. They can't provide properties, indexers or constructors

As a workaround for an extension property you can implement Getter and Setter Extension methods for object using reflection based object indexer code.

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