索引器

来源:互联网 发布:淘宝联盟 分享领券 编辑:程序博客网 时间:2024/04/30 13:51

索引器一般只有一个,但一个索引器类中确实可定义多个索引,只要是this的参数(注意是参数,而和返回类型无关)不同就行。例如:
namespace indexorExample2
{
    class Program
    {
        static void Main(string[] args)
        {
            MyIndexer indexer_Int = new MyIndexer();
            indexer_Int[0] = "aaa";
            indexer_Int[3] = "bbb";
            indexer_Int[5] = "ccc";
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" indexer_Int[{0}] : {1} ", i, indexer_Int[i]);
            }


            //没意义
            MyIndexer indexer_string = new MyIndexer();
            indexer_string["a"] = "this is a";
            indexer_string["b"] = "this is b";
            indexer_string["c"] = "this is b";
            Console.WriteLine("indexer_string[/"a/"] : " + indexer_string["a"]);
            Console.WriteLine("indexer_string[/"b/"] : " + indexer_string["b"]);
        }
    }


    public class MyIndexer
    {
        private string[] indexer_Int = new string[10];
        public string this[int index]
        {
            get
            {
                if (index < 0 || index >10 )
                    return "非法";
                else
                    return indexer_Int[index];
            }
            set
            {
                indexer_Int[index] = value;
            }
        }

        //此例没有意义,仅供参考。你能知道这样有什么用啊 ^_^
        private string[] indexer_string = new string[10];
        public string this[string index]
        {
            get
            {
                if (index.Equals("a"))
                    return indexer_string[1];
                else if (index.Equals("b"))
                    return indexer_string[2];
                else 
                    return "没定义";
            }
            set
            {
                if (index.Equals("a"))
                    indexer_string[1] = value;
                else if (index.Equals("b"))
                    indexer_string[2] = value;
                else
                    Console.WriteLine("非法");
            }
        }

    }
}
原创粉丝点击