当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在C#中重载方括号运算符?》经验,为你挑选了4个好方法。

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

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

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

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

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



1> Ruben..:

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

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}


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

2> Ricardo Vill..:

这将是项目属性: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; 
}


就它如何实现而言,它是"Item",但在C#术语中,它是"this"

3> Patrick Desj..:
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


它在底部.

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


实际上,这非常危险 - 您现在有两个竞争实现:任何类型为List 或IList 或IList等的变量都不会执行您的自定义代码.
推荐阅读
手机用户2402851155
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有