程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#索引器簡單實例代碼

C#索引器簡單實例代碼

編輯: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();

        }

    }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved