例如,DataGridView允许您执行此操作:
DataGridView dgv = ...; DataGridViewCell cell = dgv[1,5];
但对于我的生活,我找不到索引/方括号运算符的文档.他们怎么称呼它?它在哪里实施?可以扔吗?我怎么能在自己的课上做同样的事情?
ETA:感谢所有快速解答.简而言之:相关文件属于"项目"属性; 重载的方法是声明一个属性,如public object this[int x, int y]{ get{...}; set{...} }
; 至少根据文档,DataGridView的索引器不会抛出.它没有提到如果提供无效坐标会发生什么.
再次ETA:好的,即使文档没有提到它(顽皮的微软!),事实证明,如果你为它提供无效的坐标,DataGridView的索引器实际上会抛出一个ArgumentOutOfRangeException.公平的警告.
你可以在这里找到如何做到这一点.简而言之就是:
public object this[int i] { get { return InnerList[i]; } set { InnerList[i] = value; } }
这将是项目属性:http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
也许这样的事情会起作用:
public T Item[int index, int y] { //Then do whatever you need to return/set here. get; set; }
Operators Overloadability +, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded. +, -, !, ~, ++, --, true, false All C# unary operators can be overloaded. ==, !=, <, >, <= , >= All relational operators can be overloaded, but only as pairs. &&, || They can't be overloaded () (Conversion operator) They can't be overloaded +=, -=, *=, /=, %= These compound assignment operators can be overloaded. But in C#, these operators are automatically overloaded when the respective binary operator is overloaded. =, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded [ ] Can be overloaded but not always!
信息来源
对于括号:
public Object this[int index] { }
数组索引操作符不能重载 ; 但是,类型可以定义索引器,即带有一个或多个参数的属性.索引器参数用方括号括起来,就像数组索引一样,但索引器参数可以声明为任何类型(与数组索引不同,它必须是整数).
来自MSDN
public class CustomCollection : List