C# 扩展索引器?
是否可以使用扩展方法来扩展索引器?我希望能够使用如下标题文本从给定 DataGridViewRow
的 DataGridViewCell
获取单元格的值:
object o = row["HeaderText"];
我有此代码
public static class Ext
{
public static object Cells(this DataGridViewRow r, string header)
{
foreach (DataGridViewCell c in r.Cells)
{
if (c.OwningColumn.HeaderText == header)
{
return c.Value;
}
}
return null;
}
}
,并且我想要类似的索引器。谢谢。
Is it possible to use extension methods to extend an indexer? I want to be able to get cell's value from DataGridViewCell
of given DataGridViewRow
using header text like this:
object o = row["HeaderText"];
I have this code
public static class Ext
{
public static object Cells(this DataGridViewRow r, string header)
{
foreach (DataGridViewCell c in r.Cells)
{
if (c.OwningColumn.HeaderText == header)
{
return c.Value;
}
}
return null;
}
}
and I want similar indexer. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
索引器实际上是属性,而扩展属性在 C# 中不存在。所以这不能按照你想要的方式完成。
请参阅此博文了解一些信息该主题的背景,以及为什么考虑该功能但最终在 C# 3.0 中省略的解释。
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
is equivalent to
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
作为扩展属性的解决方法,您可以使用基于反射的对象索引器代码为对象实现 Getter 和 Setter 扩展方法。
As a workaround for an extension property you can implement Getter and Setter Extension methods for object using reflection based object indexer code.