志在指尖
用双手敲打未来

c#索引器

索引器界说:索引器是封装了一组值的智能数组,它让用户能够自界说拜访类型并以数组的形式拜访类中的数据。索引实际上是有参属性
usingSystem;usingSystem.Collections.Generic;namespace编码操练
{publicclassStudent:ICloneable
{publicintId{get;set;}publicstringName{get;set;}publicintAge{get;set;}publicStudent(intid,stringname,intage)
{this.Id=id;this.Name=name;this.Age=age;C#
}publicvoidShowData()
{
Console.WriteLine(“id:”+this.Id+”name:”+this.Name+”age:”+this.Age);
}//克隆,仿制的是数据不是引用publicobjectClone()
{return(object)this.MemberwiseClone();
}
}publicclassStudentIndexer
{privateListFstudents{get;set;}publicStudentIndexer()
{
Fstudents=newList();
}//按ID索引publicStudentthis[intid]
{get{foreach(varstuinFstudents)
{if(stu.Id==id)
{return(Student)stu.Clone();
}
}returnnull;
}set{Fstudents.Add(value);}
}//按名字索引publicStudentthis[stringname]
{get{foreach(varstuinFstudents)
{if(stu.Name==name)
{return(Student)stu.Clone();
}
}returnnull;
}set{Fstudents.Add(value);}
}//按名字和id索引publicintthis[stringname,intid]
{get{foreach(varstuinFstudents)
{if(stu.Name==name&&stu.Id==id)
{returnstu.Age;
}
}return0;
}set{Fstudents.Add(newStudent(id,name,value));}
}
}publicclassStart
{privatestaticStudentIndexerFstudentIndexer;publicstaticvoidMain()
{//往索引里面添加元素FstudentIndexer=newStudentIndexer();
FstudentIndexer[11]=newStudent(11,”李四”,23);
FstudentIndexer[“李四”]=newStudent(12,”李四”,23);
FstudentIndexer[“王五”,13]=24;
FstudentIndexer[11].ShowData();
FstudentIndexer[“王五”].ShowData();
FstudentIndexer[“李四”].ShowData();
}
}
}

未经允许不得转载:IT技术网站 » c#索引器
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载