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

Cod*_*rer 242 c# collections operator-overloading operators

例如,DataGridView允许您执行此操作:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];
Run Code Online (Sandbox Code Playgroud)

但对于我的生活,我找不到索引/方括号运算符的文档.他们怎么称呼它?它在哪里实施?可以扔吗?我怎么能在自己的课上做同样的事情?

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

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

Rub*_*ben 363

你可以在这里找到如何做到这一点.简而言之就是:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}
Run Code Online (Sandbox Code Playgroud)

  • 一个小评论:取决于你正在做什么,你可能会发现它更合适:get {return base [i]; } set {base [i] = value; } (9认同)
  • 这不是运算符重载.它是索引器 (7认同)
  • 索引器,也可以是一元运算符. (4认同)

Ric*_*mil 40

这将是项目属性: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; 
}
Run Code Online (Sandbox Code Playgroud)

  • 就它如何实现而言,它是"Item",但在C#术语中,它是"this" (5认同)

Pat*_*ins 26

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!
Run Code Online (Sandbox Code Playgroud)

信息来源

对于括号:

public Object this[int index]
{

}
Run Code Online (Sandbox Code Playgroud)

数组索引操作符不能重载 ; 但是,类型可以定义索引器,即带有一个或多个参数的属性.索引器参数用方括号括起来,就像数组索引一样,但索引器参数可以声明为任何类型(与数组索引不同,它必须是整数).

来自MSDN

  • 它在底部. (3认同)
  • 抱歉,如果我误读了您的帖子,但是您指的是什么条件? (2认同)

amo*_*oss 13

如果您使用的是 C# 6 或更高版本,则可以将表达式主体语法用于 get-only 索引器:

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


Jas*_*zek 6

public class CustomCollection : List<Object>
{
    public Object this[int index]
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,这非常危险 - 您现在有两个竞争实现:任何类型为List <T>或IList <T>或IList等的变量都不会执行您的自定义代码. (4认同)