代码改变世界

c#里面的索引器注意

2017-06-25 11:21  hello,逗比  阅读(247)  评论(0编辑  收藏  举报

1、特此说明,下面代码是从完整部分复制了部分,未必能直接拷贝执行。

2、索引器里注意  1)如果没有设置数组保存,不能连续访问per2[0],per[1],因为里面的比如 Name是被替换的。 2)我们创建数组保存,需要 创建空间,我们可以

string[] ArrName=new string[10] ; 也可以在这里分配空间
也可以写个构造方法,动态分配空间,如下面代码。

3、索引器里另外灵活运用例子,将索引号不同,给对象不同字段赋值。

public string this [int index]
            {
                set
                {
                    if (index == 0)
                    { Name = "test1"; }
                    else if (index == 1)
                        Name = "testOther";
                    else
                        Name = value;
                }
                get
                {
                    if (index == 0)
                        return Name;
                    else if (index == 1)
                        return Name + 1;
                    else
                        return Name;
                  
                }调用      //索引器,不能一次性访问per2【0】,per2【1】,除非把 return保存到数组里面
           person per2 = new person();
            per2[0] = "11";
            Console.WriteLine(per2[0]);
            per2[1] = "22";
            Console.WriteLine(per2[1]);
            per2[2] = "33";
            Console.WriteLine(per2[2]);
            Console.WriteLine(per2[0]+" "+per2[1]+" "+per2[2]+" "+per2[3]);

 

static void Main(string[] args)
{

person per2 = new person();
per2[0] = "11";
Console.WriteLine(per2[0]);
per2[1] = "22";
Console.WriteLine(per2[1]);
per2[2] = "33";
Console.WriteLine(per2[2]);
Console.WriteLine(per2[0]+" "+per2[1]+" "+per2[2]+" "+per2[3]);

 

Console.ReadKey();
}



public class person
{
int age;
string name;
// string[] ArrName=new string[10] ; 也可以在这里分配空间
string[] ArrName;
private bool sex;
public person(int i)//构造方法,为ArrName分配空间
{
ArrName = new string[i];
}
public string this [int index]
{
set
{
if (index == 0)
{ ArrName[0] = "test1"; }
else if (index == 1)
ArrName[1] = "testOther";
else
ArrName[index] = value;
}
get
{
if (index == 0)
return ArrName[index];
else if (index == 1)
return ArrName[index];
else
return ArrName[index] +100;

}
}