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

查看:21
本文介绍了如何在 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:感谢所有快速回答.简而言之:相关文档在Item"属性下;重载的方法是声明一个属性,如 public object this[int x, int y]{ get{...};设置{...} };至少根据文档,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 再次:好的,即使文档没有提到它(顽皮的微软!),事实证明,如果您提供无效坐标,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; }
}

如果您只需要一个 getter,也可以使用答案中的语法(从 C# 6 开始).

If you only need a getter the syntax in answer below can be used as well (starting from C# 6).

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

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