代码参考:
- using System;
-
- namespace FoodRobotDemo
- {
- public class FoodRobot
- {
- private int[] foodCountArr;
- private string[] foodNameArr;
-
- public FoodRobot()
- {
- foodCountArr = new int[3];
- foodNameArr = new string[3] {"航天","航空","宇航" };
- }
- public int this[string name]
- {
- get
- {
- int i = Array.IndexOf(foodNameArr, name);
- if (i != -1 && i >= 0 && i < 3)
- return foodCountArr[i];
- else
- {
- Console.WriteLine("读取操作有误,找不到{0}食品",name);
- return -1;
- }
- }
- set
- {
- int i = Array.IndexOf(foodNameArr, name);
- if (i != -1)
- foodCountArr[i] = value;
- else
- Console.WriteLine("赋值操作有误,找不到{0}食品", name);
- }
- }
-
- }
-
-
- class Program
- {
- static void Main(string[] args)
- {
- //多参数索引器和索引器重载
- FoodRobot foodRobot = new FoodRobot();
- foodRobot["航天"] = 11;
- foodRobot["航空"] = 22;
- foodRobot["宇航"] = 33;
- foodRobot["行行"] = 44;
- Console.WriteLine(foodRobot["航天"]);
- Console.WriteLine(foodRobot["天天"]);
- Console.ReadKey();
- }
- }
- }