索引器(Indexer)

来源:<>

Code:

using System;

namespace CsDev
{
     class Class1
    {
        string a;
        string b;
        string c;
         public string this[int index]//索引器定义
     {
         set 
         {
             switch (index)
             {
                 case 0: a = value; break;
                 case 1: b = value; break;
                 case 2: c = value; break;
             }
         }

         get
         {
             switch (index)
             {
                 case 0: return a ;
                 case 1: return b;
                 case 2: return c;
                 default: return "";
             }
         }
     }
    }

     public class cl
     {
         public static void Main()
         {
             Class1 cc = new Class1();
             cc[0] = "aaa";//使用索引器
             cc[1] = "bbb";
             cc[2] = "ccc";
             Console.WriteLine(cc[0]);
             Console.WriteLine(cc[1]);
             Console.WriteLine(cc[2]);

             Console.ReadKey();
         }
     }
}

输出:

aaa
bbb
ccc

你可能感兴趣的:(C#)