我如何重载C#中的方括号运算符?

DataGridView,例如,让你这样做:

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

但在我的生活中,我无法find索引/方括号运算符的文档。 他们叫什么? 它在哪里实施? 它可以扔? 我怎样才能在自己的课堂上做同样的事情?

ETA:感谢所有的快速回答。 简而言之:相关文件在“项目”属性下; 重载的方法是通过声明一个像public object this[int x, int y]{ get{...}; set{...} } public object this[int x, int y]{ get{...}; set{...} } ; DataGridView的索引器不会抛出,至less根据文档。 它没有提到如果你提供无效的坐标会发生什么。

ETA再次:好的,尽pipe文档没有提到它(顽皮的微软!),事实certificate,DataGridView的索引器实际上会抛出一个ArgumentOutOfRangeException,如果你提供了无效的坐标。 公平的警告。

你可以在这里find如何做到这一点 。 总之是:

 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] { } 

数组索引操作符不能重载 ; 但是,types可以定义索引器,这些属性需要一个或多个参数。 索引器参数包含在方括号中,就像数组索引一样,但索引器参数可以声明为任何types(不同于数组索引,必须是整数)。

来自MSDN

 public class CustomCollection : List<Object> { public Object this[int index] { // ... } } 

对于CLI C ++(使用/ clr编译),请参阅此MSDN链接 。

简而言之,一个属性可以被命名为“default”:

 ref class Class { public: property System::String^ default[int i] { System::String^ get(int i) { return "hello world"; } } }; 

如果您使用的是C#6或更高版本,则只能使用expression式索引器的expression式语法:

public object this[int i] => this.InnerList[i];

这是一个从内部List对象返回一个值的例子。 应该给你的想法。

  public object this[int index] { get { return ( List[index] ); } set { List[index] = value; } } 

如果你指的是数组索引器,那么你只需通过编写一个索引器属性来重载即可。只要每个索引器属性都有不同的参数签名,就可以重载(只要你想写多less)索引器属性

 public class EmpployeeCollection: List<Employee> { public Employee this[int employeeId] { get { foreach(Employee emp in this) if (emp.EmployeeId == employeeId) return emp; return null; } } public Employee this[string employeeName] { get { foreach(Employee emp in this) if (emp.name == employeeName) return emp; return null; } } }