索引器
為了方便將類、結構或接口當做數組來使用。
索引器用于封裝內部集合或數組
定義語法
[訪問修飾符] 返回類型 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);
}
}
}
新聞熱點
疑難解答