日期:2014-05-19  浏览次数:20765 次

初级问题 ,索引器
一个类中能有几个索引器??索引器必须用   this定义么??我看例子是

class   SampleCollection <T>
{
        private   T[]   arr   =   new   T[100];
        public   T   this[int   i]
        {
                get
                {
                        return   arr[i];
                }
                set
                {
                        arr[i]   =   value;
                }
        }
}
这里的this是关键字还是只是一个属性名称??


为啥我定义2个索引器救出一堆错呢,我要疯了


private   int[]   x=new   int[10];

public   int   bbb[int   i]
        {
                get
                {
                        return   x[i];
                }
                set
                {
                        x[i]   =   value;
                }
        }


public   int   fff[int   i]
        {
                get
                {
                        return   x[i];
                }
                set
                {
                        x[i]   =   value;
                }
        }




------解决方案--------------------
this是关键字。索引器有规定,索引名只能采用下列形式之一:
type this [formal-index-parameter-list]
type interface-type.this [formal-index-parameter-list]
也就是说在这普通的索引器中,只能使用this。

索引器一般只有一个,但一个索引器类中确实可定义多个索引,只要是this的参数(注意是参数,而和返回类型无关)不同就行。例如:
namespace indexorExample2
{
class Program
{
static void Main(string[] args)
{
MyIndexer indexer_Int = new MyIndexer();
indexer_Int[0] = "aaa ";
indexer_Int[3] = "bbb ";
indexer_Int[5] = "ccc ";
for (int i = 0; i < 10; i++)
{
Console.WriteLine( " indexer_Int[{0}] : {1} ", i, indexer_Int[i]);
}


//没意义
MyIndexer indexer_string = new MyIndexer();
indexer_string[ "a "] = "