如何在 C# 中重载方括号运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/287928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I overload the square-bracket operator in C#?
提问by Coderer
DataGridView, for example, lets you do this:
例如,DataGridView 可让您执行以下操作:
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: 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:感谢所有快速回答。简而言之:相关文档在“Item”属性下;重载的方法是声明一个属性,如public object this[int x, int y]{ get{...}; set{...} }
; 至少根据文档,DataGridView 的索引器不会抛出。它没有提到如果您提供无效坐标会发生什么。
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.
ETA 再次:好的,即使文档没有提到它(顽皮的微软!),事实证明,如果您提供无效坐标,DataGridView 的索引器实际上会抛出 ArgumentOutOfRangeException。公平警告。
采纳答案by Ruben
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; }
}
If you only need a getter the syntax in answer belowcan be used as well (starting from C# 6).
如果您只需要一个 getter,也可以使用下面答案中的语法(从 C# 6 开始)。
回答by Patrick Desjardins
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!
For bracket:
对于支架:
public Object this[int index]
{
}
BUT
但
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).
数组索引运算符不能重载;但是,类型可以定义索引器,即带有一个或多个参数的属性。索引参数用方括号括起来,就像数组索引一样,但索引参数可以声明为任何类型(与数组索引不同,它必须是整数)。
From MSDN
来自MSDN
回答by Jason Miesionczek
public class CustomCollection : List<Object>
{
public Object this[int index]
{
// ...
}
}
回答by Ricardo Villamil
That would be the item property: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
那将是项目属性:http: //msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
Maybe something like this would work:
也许这样的事情会起作用:
public T Item[int index, int y]
{
//Then do whatever you need to return/set here.
get; set;
}
回答by Rob Prouse
Here is an example returning a value from an internal List object. Should give you the idea.
这是从内部 List 对象返回值的示例。应该给你思路。
public object this[int index]
{
get { return ( List[index] ); }
set { List[index] = value; }
}
回答by Charles Bretana
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<Employee>
{
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;
}
}
}
回答by Charles Bretana
For CLI C++ (compiled with /clr) see this MSDN link.
对于 CLI C++(使用 /clr 编译),请参阅此 MSDN 链接。
In short, a property can be given the name "default":
简而言之,属性可以命名为“default”:
ref class Class
{
public:
property System::String^ default[int i]
{
System::String^ get(int i) { return "hello world"; }
}
};
回答by amoss
If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:
如果您使用的是 C# 6 或更高版本,则可以将表达式主体语法用于 get-only 索引器:
public object this[int i] => this.InnerList[i];
public object this[int i] => this.InnerList[i];