【C#学习笔记】Indexer索引器

C#的索引器允许我们对一个实例像数组一样进行索引。当我们在一个类中定义了索引器之后,我们可以通过数组操作符([ ])像操作数组一样来访问这个类的实例。

  • 索引器的好处就是简化的数组和集合成员的存取操作。
  • 索引器可被重载。
  • 索引器可以有多个形参,例如当访问二维数组时。

syntax -- from MSDN

public int this[int index]    // Indexer declaration
{
    // get and set accessors
}

例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class Student
    {
        public int Number { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
    }

    class IndexerExample
    {
        private IList students = new List();

        public IndexerExample()
        {
            students.Add(new Student
            {
                Number = 1,
                Name = "Jason",
                Sex = "Male"
            });
            students.Add(new Student
            {
                Number = 2,
                Name = "Maggie",
                Sex = "Female"
            });
            students.Add(new Student
            {
                Number = 3,
                Name = "Lucy",
                Sex = "Female "
            });
        }

        public Student getStudent(string name)
       {
           foreach (Student student in students)
           {
               if (student.Name == name)
               {
                   return student;
               }
           }
           return null;
       }

        public Student getStudent(int num)
       {
           foreach (Student student in students)
           {
               if (student.Number == num)
               {
                   return student;
               }
           }
           return null;
       }

        //define indexer
        public Student this[int num]
        {
            get
           {
               foreach (Student student in students)
               {
                   if (student.Number == num)
                   {
                       return student;
                   }
               }
               return null;
           }
        }

        // overload indexer
        public Student this[string name]
        {
            get
           {
               foreach (Student student in students)
               {
                   if (student.Name == name)
                   {
                       return student;
                   }
               }
               return null;
           }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            IndexerExample myStudents = new IndexerExample();

            Console.WriteLine(myStudents.getStudent(1).Sex);
            Console.WriteLine(myStudents[1].Sex);
            Console.WriteLine(myStudents.getStudent("Maggie").Sex);
            Console.WriteLine(myStudents["Maggie"].Sex);
            Console.ReadLine();
        }
    }  
}
// Output
// "Male"
// "Male"
// "Female"
// "Female"

你可能感兴趣的:(【C#学习笔记】Indexer索引器)