码迷,mamicode.com
首页 > 其他好文 > 详细

索引器

时间:2014-11-30 15:26:38      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   on   数据   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class C1
    {
        public string name1;
        public string name2;
        public string this[int index]
        {
            set
            {
                switch (index)
                {
                    case 0: name1 = value; break;
                    case 1: name2 = value; break;
                    
                }

            }
            get
            {
                switch (index)
                {
                    case 0: return name1;
                    case 1: return name2;
                    default: return ""; ;//这行代码一定要有不然会出现错误的
                }
            }
        }
    }
 
    class Program
    {
        static void Main(string[] args)//没有索引的简单类
        {
            C1 C = new C1();
            C[0]="lei";           
            Console.WriteLine("name1:{0}", C[0] );
            C[1] = "cao";
            Console.WriteLine("name1:{0}", C[1]);
            Console.ReadLine();
         }
    }
}
bubuko.com,布布扣
//总结:属性和索引在很多方面都是一样的索引和属性都主要被用来访问其他数据成员; //属性通常表示单个数据成员,索引通常表示多个数据成员。可以认为索引器是为类的 // 的多个数据成员提供get和set属性!

 

索引器

标签:style   blog   http   io   ar   color   sp   on   数据   

原文地址:http://www.cnblogs.com/leijiangtao/p/4133107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!