[C#基础训练]FoodRobot食品管理部分代码-1

代码参考:

cs 复制代码
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();
        }
    }
}
相关推荐
临床数据科学和人工智能兴趣组3 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike6 小时前
php笔记
开发语言·笔记·php
Circ.7 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
波力海苔夹心脆6758 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
现任明教教主~8 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411369 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅9 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿11 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全