码迷,mamicode.com
首页 > Windows程序 > 详细

c#里面的索引器注意

时间:2017-06-25 11:58:12      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:static   other   数组   oid   turn   void   索引   new   访问   

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;

}
}

 

  

c#里面的索引器注意

标签:static   other   数组   oid   turn   void   索引   new   访问   

原文地址:http://www.cnblogs.com/ilrc/p/7076375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!