索引器定义:索引器是封装了一组值的智能数组,它让用户可以自定义访问类型并以数组的形式访问类中的数据。索引实际上是有参属性
using System; using System.Collections.Generic; namespace 编码练习 { public class Student : ICloneable { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public Student(int id, string name, int age) { this.Id = id; this.Name = name; this.Age = age; } public void ShowData() { Console.WriteLine("id:" + this.Id + " name:" + this.Name + " age:" + this.Age); } //克隆,复制的是数据不是引用 public object Clone() { return (object)this.MemberwiseClone(); } } public class StudentIndexer { private List<Student> Fstudents { get; set; } public StudentIndexer() { Fstudents = new List<Student>(); } //按ID索引 public Student this[int id] { get { foreach (var stu in Fstudents) { if (stu.Id == id) { return (Student)stu.Clone(); } } return null; } set { Fstudents.Add(value); } } //按姓名索引 public Student this[string name] { get { foreach (var stu in Fstudents) { if (stu.Name == name) { return (Student)stu.Clone(); } } return null; } set { Fstudents.Add(value); } } //按姓名和id索引 public int this[string name, int id] { get { foreach (var stu in Fstudents) { if (stu.Name == name && stu.Id == id) { return stu.Age; } } return 0; } set { Fstudents.Add(new Student(id, name, value)); } } } public class Start { private static StudentIndexer FstudentIndexer; public static void Main() { //往索引里面添加元素 FstudentIndexer = new StudentIndexer(); FstudentIndexer[11] = new Student(11, "李四", 23); FstudentIndexer["李四"] = new Student(12, "李四", 23); FstudentIndexer["王五", 13] = 24; FstudentIndexer[11].ShowData(); FstudentIndexer["王五"].ShowData(); FstudentIndexer["李四"].ShowData(); } } }
附加知识点:
ICloneable接口的用法,该接口复制的是数据不是引用
public object Clone() { return (object)this.MemberwiseClone(); }