当前位置: 移动技术网 > IT编程>开发语言>c# > C#索引器简单实例代码

C#索引器简单实例代码

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:public class fruit {         string pea

复制代码 代码如下:

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

        }

    }

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网