首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

初级有关问题 ,索引器

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

初级问题 ,索引器
一个类中能有几个索引器??索引器必须用   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 "] = "this is a ";
indexer_string[ "b "] = "this is b ";


indexer_string[ "c "] = "this is b ";
Console.WriteLine( "indexer_string[\ "a\ "] : " + indexer_string[ "a "]);
Console.WriteLine( "indexer_string[\ "b\ "] : " + indexer_string[ "b "]);
}
}


public class MyIndexer
{
private string[] indexer_Int = new string[10];
public string this[int index]
{
get
{
if (index < 0 || index > 10 )
return "非法 ";
else
return indexer_Int[index];
}
set
{
indexer_Int[index] = value;
}
}

//此例没有意义,仅供参考。你能知道这样有什么用啊 ^_^
private string[] indexer_string = new string[10];
public string this[string index]
{
get
{
if (index.Equals( "a "))
return indexer_string[1];
else if (index.Equals( "b "))
return indexer_string[2];
else
return "没定义 ";
}
set
{
if (index.Equals( "a "))
indexer_string[1] = value;
else if (index.Equals( "b "))
indexer_string[2] = value;
else
Console.WriteLine( "非法 ");
}
}

}
}


你要实现你说的, 我感觉 多定义几个索引器类就可以拉吧
[解决办法]
一个类中能有几个索引器??
-----------------
多个...


索引器必须用 this定义么??
-----------------
yes...


这里的this是关键字还是只是一个属性名称??
-----------------
关键字


为啥我定义2个索引器救出一堆错呢
-----------------
因为多个索引器必须具有不同的签名...

public int bbb[int i]
public int fff[int i]
------------------
这是错误的...应该这样

public int this[int i]
...
public int this[string key]
...

热点排行