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

查看:1782
本文介绍了我如何重载在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:感谢所有的快速解答。简述:相关文件是在项目财产;重载的方法是通过声明属性如公共对象本[INT X,INT Y] {获得{...};设置{...}} ;为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.

ETA还是那句话:OK,即使文件使得它没有提到(淘气微软!),事实证明,对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天全站免登陆