C#索引器简单实例 C#索引器简单实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#索引器简单实例 C#索引器简单实例代码

  2021-03-18 我要评论
想了解C#索引器简单实例代码的相关内容吗,在本文为您仔细讲解C#索引器简单实例的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#,索引器,实例,下面大家一起来学习吧。

复制代码 代码如下:

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();

        }

    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们