C# 索引

索引

  • 索引可以让我们像使用数组那样访问类的数据成员
  • 在数组中,下标只能为整数,在索引中,有了更灵活的选择,既可以为 int 型,也可
    以为 double、string 等类型。比如下面这个例子中就使用了string类型作为下标。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IndexLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            Cube c1 = new Cube(5, 6, 7);
            Console.WriteLine("长{0},宽{1},高{2}", c1["length"], c1["width"], c1["height"]);
            //计算体积
            Console.WriteLine("体积:{0}", c1["length"] * c1["width"] * c1["height"]);
        }
    }

    class Cube
    {
        private double length;
        private double width;
        private double height;
        public Cube(double length,double width,double height)
        {
            this.length = length;
            this.width = width;
            this.height = height;
        }
        //索引
        public double this[string Index]
        {
            get
            {
                switch(Index)
                {
                    case "length":
                        return length;
                    case "width":
                        return width;
                    case "height":
                        return height;
                    default:
                        throw new IndexOutOfRangeException("下标出界!");          
                }
            }
            set
            {
                switch (Index)
                {
                    case "length":
                        this.length = value;
                        break;
                    case "width":
                        this.width = value;
                        break;
                    case "height":
                        this.height = value;
                        break;
                    default:
                        throw new IndexOutOfRangeException("下标出界!");
                }
            }
        }
    }
}

C# 索引_第1张图片

你可能感兴趣的:(C#,c#,开发语言,后端)