代码参考:文章来源地址https://www.toymoban.com/news/detail-719602.html
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();
}
}
}
文章来源:https://www.toymoban.com/news/detail-719602.html
到了这里,关于[C#基础训练]FoodRobot食品管理部分代码-1的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!