c#索引实例

首次发布:2017-05-20 15:59
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 索引
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClass tc = new TestClass();
            for(int i = 0; i < tc.count; i++)
            {
                Console.WriteLine(tc[i]);
            }            
            Console.ReadKey();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 索引
{
    public class TestClass
    {
        public int count
        {
            get { return _name.Length; }
        }
        private string[] _name = { "lqwvje", "test", "罗分明" };
        //索引其实是一个属性,是一个非常特殊属性,其实是一个名叫Item的尾性
        public string this[int index]
        {
            get
            {
                if (index < 0 || index > _name.Length)
                {
                    return "超出索引";
                }
                return _name[index];
            }
            set
            {
                _name[index] = value;
            }
        }
    }
}