zoukankan      html  css  js  c++  java
  • 索引器

          通过对类定义个索引器可以把对象的域当做一个数组元素。例如在Car类中定义一个索引器,用来读写make和model域,定义一个类myCar

    myCar[0]访问make,myCar[1]访问model。

    /*
      Example10_11.cs illustrates the use of an indexer
    */
    
    using System;
    
    
    // declare the Car class
    public class Car
    {
    
      // declare two fields
      private string make;
      private string model;
    
      // define a constructor
      public Car(string make, string model)
      {
        this.make = make;
        this.model = model;
      }
    
      // define the indexer
      public string this[int index]
      {
        get
        {
          switch (index)
          {
            case 0:
              return make;
            case 1:
              return model;
            default:
              throw new IndexOutOfRangeException();
          }
        }
        set
        {
          switch (index)
          {
            case 0:
              this.make = value;
              break;
            case 1:
              this.model = value;
              break;
            default:
              throw new IndexOutOfRangeException();
          }
        }
      }
    
    }
    
    
    class Example10_11
    {
    
      public static void Main()
      {
    
        // create a Car object
        Car myCar = new Car("Toyota", "MR2");
    
        // display myCar[0] and myCar[1]
        Console.WriteLine("myCar[0] = " + myCar[0]);
        Console.WriteLine("myCar[1] = " + myCar[1]);
    
        // set myCar[0] to "Porsche" and myCar[1] to "Boxster"
        Console.WriteLine("Setting myCar[0] to \"Porsche\" " +
          "and myCar[1] to \"Boxster\"");
        myCar[0] = "Porsche";
        myCar[1] = "Boxster";
        // myCar[2] = "Test";  // causes IndeXOutOfRangeException to be thrown
    
        // display myCar[0] and myCar[1] again
        Console.WriteLine("myCar[0] = " + myCar[0]);
        Console.WriteLine("myCar[1] = " + myCar[1]);
    
      }
    
    }
    
  • 相关阅读:
    TX2 刷机教程
    ROS2 树莓派SBC镜像安装
    OP3 默认ID图
    OP3 镜像恢复
    ROS2 BringUp
    学习笔记3:Linux面试题
    学习笔记2:Linux简单指令
    学习笔记1:Git简单指令
    编程小白入门分享五:Vue的自定义组件
    编程小白入门分享四:Vue的安装及使用快速入门
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2039403.html
Copyright © 2011-2022 走看看