·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 黑马程序员-集合和索引器

黑马程序员-集合和索引器

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

黑马程序员-集合和索引器

索引器

为了方便将类、结构或接口当做数组来使用。

索引器用于封装内部集合或数组

定义语法

[访问修饰符] 返回类型 this[索引类型 索引名]

{

  //get或set方法体

}

索引本质就是属性

利用索引可以用key得到项,亦可用项得到序号

集合具有很强的通用性(方法名应该记住)

增加

Add、AddRange

移除

Remove、RemoveAt

清空

Clear

排序

Sort、Reverse

查找

IndexOf、LastIndexOf

判存

Contains

集合的总数

Count属性

浅复制

Clone

索引

集合也可以通过“下标”来访问,叫做索引

namespaceIndexer

{

classPRogram

{

staticvoidMain(string[]args)

{

MyCollectionmc=newMyCollection();

int[]nums={0,1,2,3,4,5,6,7,8,9};

//添加的功能

mc.Add(100);

mc.AddRange(nums);

//插入,在3位置上添加一个100

mc.Insert(3,100);

//移除

//mc.Remove(100);

mc.RemoveAt(2);

//清空

//mc.Clear();

//读取位置为3的数据

Console.WriteLine(mc[2]);

Console.ReadKey();

}

}

//咱们手动写一个集合

classMyCollection

{

//int[]nums;

ArrayListal;

//用来测试的方法

privatevoidTest()

{

this.Clear();

//this在类的内部,表示当前实例

//this[3];

}

//索引

//索引的本质是属性;属性的本质是方法。

publicobjectthis[intindex]

{

get{returnal[index];}

set{al[index]=value;}

}

publicMyCollection()

{

al=newArrayList();

}

//Add方法

//最不好的办法

#region不好的方法

//publicintAdd(intnum)

//{

//if(nums==null)

//{

//nums=newint[]{num};

//}

//else

//{

//int[]temp=newint[nums.Length+1];

//for(inti=0;i<nums.Length;i++)

//{

//temp[i]=nums[i];

//}

//temp[temp.Length-1]=num;

//nums=temp;

//}

//returnnums.Length+1;

//}

#endregion

publicintAdd(objecto)

{

returnal.Add(0);

}

publicvoidAddRange(ICollectionic)

{

al.AddRange(ic);

}

publicvoidRemove(objecto)

{

al.Remove(o);

}

publicvoidRemoveAt(intindex)

{

al.RemoveAt(index);

}

publicvoidClear()

{

al.Clear();

}

publicvoidInsert(intindex,objecto)

{

al.Insert(index,o);

}

}

}