C# 索引器的使用

xiaoxiao2021-02-28  114

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Index : MonoBehaviour { // Use this for initialization void Start () {         print("访问类实例的结果:");         IndexText array = new IndexText();         array[-5] = -5;         array[0] = 2;         array[1] = 3;         array[2] = 5;         array[11] = 87;         print("array[-5]=" + array[-5]);         print("array[0]="+array[0]);         print("array[1]="+array[1]);         print("array[2]="+array[2]);         print("array[11]="+array[11]);         print("访问类成员的结果:");         WeekIndex we = new WeekIndex();        print(we["星期 3"]);        print(we["星期 5"]);        print(we["星期日"]);        print(we["星期 8"]);     }     public class Clerk     {         //属性的定义         private string name;         public string Name {             get {  return name;    }             set {   name = value;  }         }         //索引器声明         private int[] myInt = new int[10];         //public int this[int index]         //{         //    get { return myInt[index]; }         //    set { myInt[index] = value; }         //}         //public virtual int this[int index]         //{         //    get { return myInt[index]; }         //    set { myInt[index] = value; }         //}         //public extern int this[int index]         //{         //    get;         //    set;         //}     }     public abstract class IndexExample {         //抽象索引器必须在抽象类中声明         public abstract int this[int index]         {             get;             set;         }     }         private class IndexText     //   用于访问类的实例     {         private int[] array = new int[10];         public int this[int index] {             get {                 if (index < 0 || index >= 10) return 0;                 else return array[index];             }             set             {                 if (index >= 0 && index < 10) array[index] = value;             }         }     }     private class WeekIndex    //    用于访问类的成员     {         string[] week = { "星期 1", "星期 2", "星期 3", "星期 4", "星期 5", "星期 6", "星期日" };         private int GetDay( string weekText)         {             int i = 0;             foreach (string str in week) {                 if (weekText == str) return i;                 i++;             }             return -1;         }         public int this[string week]         {             get { return GetDay(week); }         }     } }
转载请注明原文地址: https://www.6miu.com/read-80471.html

最新回复(0)