记录.NET学习的点滴,欢迎收藏我的博客

作者:路过秋天 http://cyq1162.cnblogs.com | www.mmic.net.cn欢迎大家交流,这里是我记录的空间方便以后工作查找
公告信息
记录.NET学习的点滴,欢迎收藏我的博客
文章分类
文章档案
文章
C#索引器简单示例制作方法
2011/8/15 0:11:58

打开.Net Framework源代码随便看几个类,就会发现索引器的影子。索引器可以被重载,可以接收一个或者多个参数,ic买卖但是不可以定义为静态的。可以用关联数组的方式访问索引器。

public class Fruit

{

        string peach = "a round juicy fruit that has a soft yellow or red skin and a large hard seed in the center, or the tree that this fruit grows on";

        string orange = "a round fruit that has a thick orange skin and is divided into parts inside";

        string banana = "a long curved tropical fruit with a yellow skin";

        string apple = "a hard round fruit that has red, light green, or yellow skin and is white inside ";

        public string this[string fruitName]

        {

            get

            {

                switch (fruitName)

                {

                    case "peach":

                        return peach;

                    case "orange":

                        return orange;

                    case "banana":

                        return banana;

                    case "apple":

                        return apple;

                    default:

                        throw new Exception("wrong fruit name");

                }

            }

            set

            {

                switch (fruitName)

                {

                    case "peach":

                        peach = value;

                        break;

                    case "orange":

                        orange = value;

                        break;

                    case "banana":

                        banana = value;

                        break;

                    case "apple":

                        apple = value;

                        break;

                    default:

                        throw new Exception("wrong fruit name");

                }

            }

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            Fruit f = new Fruit();

            //关联数组的方式访问get方法

            Console.WriteLine(f["peach"]);

            //关联数组的方式访问set方法

            f["peach"] = "I like to eat peach.";

            Console.WriteLine(f["peach"]);

            Console.ReadLine();

        }

    }

新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"
 MyQBlog   浏览(2154)   评论(0)   关键字
  
Copyright © 2010-2020 power by CYQ.Blog - 秋色园 v2.0 All Rights Reserved