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: 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 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.
public T Item[int index, int y] { //Then do whatever you need to return/set here. get; set; }
回答3:
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!
The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
In short, a property can be given the name "default":
ref class Class { public: property System::String^ default[int i] { System::String^ get(int i) { return "hello world"; } } };
回答6:
If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:
public object this[int i] => this.InnerList[i];
回答7:
Here is an example returning a value from an internal List object. Should give you the idea.
public object this[int index] { get { return ( List[index] ); } set { List[index] = value; } }
回答8:
If you mean the array indexer,, You overload that just by writing an indexer property.. And you can overload, (write as many as you want) indexer properties as long as each one has a different parameter signature
public class EmployeeCollection: List { public Employee this[int employeeId] { get { foreach(var emp in this) { if (emp.EmployeeId == employeeId) return emp; } return null; } } public Employee this[string employeeName] { get { foreach(var emp in this) { if (emp.Name == employeeName) return emp; } return null; } } }