索引示例

来源:百度文库 编辑:神马文学网 时间:2024/05/02 22:13:09
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace Property
{
    class Program
    {
        static void Main(string[] args)
        {
            Myclass class1 = new Myclass();
            for (int i = 0; i < 10; i++)
            {
                for (int j=0;j<10;j++)
                {
                    class1[i * 10, j] = i * 10 + j;
                    Console.WriteLine("No{0}{1}:{2}", i, j, class1[i * 10, j]);
                }
                Console.WriteLine();
            }
            for (int i = 0; i < class1.StrCount; i++)
            {
                Console.WriteLine(class1[i]);//调用第二个索引
            }
            class1.StrCount = 5;//设置StrCount值
            for (int i = 0; i < class1.StrCount; i++)
            {
                Console.WriteLine(class1[i]);//调用第二个索引
            }
            Console.WriteLine(Myclass.ClassName);//调用静态方法时必须用类名对象调用
            Console.Write("Press any key to continue");
            Console.ReadLine();        }    }
    class Myclass
    {
        private const int count = 100;
        private static int[] intArray = new int[count];
        //第一个索引函数,支持读和写
        public int this[int index, int offset]
        {
            get
            {
                if ((index + offset) > 0 && (index + offset) < count)
                {
                    return intArray[index + offset];
                }
                else
                    return 0;
            }
            set
            {
                if ((index + offset) > 0 && (index + offset) < count)
                {
                    intArray[index + offset] = value;
                }
            }
        }        private int count1 = 3;
        private string[] strArray = {"111","222","333" };//直接赋值法
        //第二个索引,只读
        public string this[int index]
        {
            get
            {
                if ((index) > 0 && (index) < count1)
                {
                    return strArray[index];
                }
                else
                {
                    return "null";
                }
            }
        }
        //实例属性可读可写
        public int StrCount
        {
            get
            {
                return count1;
            }
            set
            {
                if (value > count1)
                {
                    strArray=new string[value];
                    for (int i = 0; i < value; i++)
                    {
                        strArray[i] = string.Format("String NO.{0}",i);
                    }
                    count1 = value;
                }
            }
        }
        private static string str = "MyClass";
        public static string ClassName
        {
            get
            {
                return str;
            }
        }    }
}