如何重载C#中的方括号运算符? [英] How do I overload the square-bracket operator in C#?

查看:289
本文介绍了如何重载C#中的方括号运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,DataGridView允许您这样做:

DataGridView, for example, lets you do this:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];

但对于我的生活我找不到索引/方括号运算符。他们叫什么?它在哪里实现?它可以投掷吗?如何在我自己的课程中做同样的事?

but for the life of me I can't find the documentation on the index/square-bracket operator. What do they call it? Where is it implemented? Can it throw? How can I do the same thing in my own classes?

ETA:感谢所有的快速答案。简要说明:相关文档在项目属性下;重载的方法是通过声明一个属性 public object this [int x,int y] {get {...}; set {...}} ; DataGridView的索引器不会抛出,至少根据文档。

ETA: Thanks for all the quick answers. Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation. It doesn't mention what happens if you supply invalid coordinates.

再次:好的,即使文档没有提到它(淘气的微软!),它转向如果你为它提供无效的坐标,DataGridView的索引器实际上会抛出一个ArgumentOutOfRangeException。公平警告。

ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates. Fair warning.

推荐答案

您可以找到如何执行此处
简而言之:

you can find how to do it here. In short it is:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}

这篇关于如何重载C#中的方括号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆