1. 程式人生 > >C#中索引器初使用

C#中索引器初使用

今天開始改學.NET
C#索引器的使用
類外部通過索引器呼叫內部私有屬性
索引器就是一個特別的屬性
首先新建一個類ItcaseClass

注意常規情況下索引器會被編譯成一個Item屬性,所以在使用了索引器之後不能再寫一個名為Item的屬性

 public class ItcaseClass
    {
        private string[] names = { "德龍", "海狗", "liuyang", "goubao", "jierke" };
        public int Count
        {
            get
            {
                return names.Length;
            }
        }
        public string this[int index]   //  這就是索引器
        {
            get
            {
                if (index < 0 || index >= names.Length)
                {
                    throw new AggregateException();
                }
                return names[index];
            }
            set
            {
                names[index] = value;
            }
        }
     }

外部類

 class Program
    {
        static void Main(string[] args)
        {
            ItcaseClass ic = new ItcaseClass();
            for(int i = 0; i < ic.Count; i++)
            {
                Console.WriteLine(ic[i]);
                
             }
            Console.ReadKey();
        }
    }