zoukankan      html  css  js  c++  java
  • C#索引器简单示例

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

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

            }

        }

    执行结果:

  • 相关阅读:
    python求余、除法运算、向下圆整、round圆整
    【转】从入门到实践 json练习详解~~和ython : groupby 结果浅解,&之后的 y_list=[v for _,v in y]
    ### 模块“*.dll”已加载,但对DllRegisterServer的调用失败,错误代码为0x80070005
    python从excel里读取数据
    文本文件和二进制文件的区别
    析构函数 声明为protected
    c语言中ln,lg,log的表示。c语言中ln,lg,log的表示。
    js设计模式--创建型--单例模式
    js设计模式--创建型--工厂模式
    解决ElementUI的table组件在flex布局下宽度不能自适应的问题
  • 原文地址:https://www.cnblogs.com/zhangchenliang/p/2971062.html
Copyright © 2011-2022 走看看