C#索引器简单实例代码

所属分类: 软件编程 / C#教程 阅读数: 94
收藏 0 赞 0 分享

复制代码 代码如下:

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

        }

    }

更多精彩内容其他人还在看

C# SendInput 模拟鼠标操作的实现方法

C# SendInput 模拟鼠标操作的实现方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中 paint()与Onpaint()的区别

paint是事件onpaint方法onpaint方法是调用paint事件的,用哪一个,效果是一样,就看那一个方便了内部是这样实现的:
收藏 0 赞 0 分享

c#中GetType()与Typeof()的区别

c#中GetType()与Typeof()的区别,需要的朋友可以参考一下
收藏 0 赞 0 分享

将字符串转换成System.Drawing.Color类型的方法

将字符串转换成System.Drawing.Color类型的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

C# 抓取网页内容的方法

C# 抓取网页内容的方法,需要的朋友可以参考一下
收藏 0 赞 0 分享

基于C#后台调用跨域MVC服务及带Cookie验证的实现

本篇文章介绍了,基于C#后台调用跨域MVC服务及带Cookie验证的实现。需要的朋友参考下
收藏 0 赞 0 分享

使用C#获取远程图片 Form用户名与密码Authorization认证的实现

本篇文章介绍了,使用C#获取远程图片 Form用户名与密码Authorization认证的实现。需要的朋友参考下
收藏 0 赞 0 分享

Winform跨线程操作的简单方法

线程间操作无效:从不是创建控件“label1”的线程访问它
收藏 0 赞 0 分享

C# WINFORM 强制让窗体获得焦点的方法代码

C# WINFORM 强制让窗体获得焦点的方法代码,需要的朋友可以参考一下
收藏 0 赞 0 分享

C#中方括号[]的语法及作用介绍

C#中方括号[]可用于数组,索引、属性,更重要的是用于外部DLL类库的引用。
收藏 0 赞 0 分享
查看更多