mhy_0210 2021-05-29 22:13 采纳率: 0%
浏览 30

C#下标为字符串类型的索引器重载

补全程序

测试输入: 红楼梦 西游记 三国演义 水浒传 43 29 39 27 红楼梦 预期输出: 43

using System;
namespace IndexSample
{
    class Book
    {
        string id;
        int price;
        public string ID
        {
            get
            { return id; }
            set
            { id = value; }
        }
        public int Price
        {
            get
            { return price; }
            set
            { price = value; }
        }
        public Book()
        {
            id = ""; price = 0;
        }
    }
    class MyClass
    {
        private Book[] data;
        public int Length
        {
            get
            { return data.Length; }
        }
        // 索引器定义,根据下标访问data
        public Book this[int index]
        {
            get
            {
                if (index >= 0 && index <= Length - 1)
                    return data[index];
                else
                    return null;
            }
            set
            {
                if (index >= 0 && index <= Length - 1)
                    data[index] = value;
            }
        }
        // 重载下标为字符串类型的索引器
        public Book this[string index]
        {
            get
            {
                //************BEGIN****************
                

                //*************END*****************
            }
        }
        public MyClass(Book[] st1)
        {
            data = st1;
        }
        public MyClass(string[] id1, int[] price1)
        {
            data = new Book[id1.Length];
            for (int i = 0; i < id1.Length; i++)
            {
                data[i] = new Book();
                (data[i]).ID = id1[i]; ;
                (data[i]).Price = price1[i];
            }
        }
    }
    class MyClient
    {
        static void Main(string[] args)
        {
            //将测试集输入的第一行中的每个单词组成字符串数组
            string[] str = (Console.ReadLine()).Split(' ');
            //将测试集输入的第一行中的每个字符串组成价格数组
            string[] prices = (Console.ReadLine()).Split(' ');
            int[] price = new int[prices.Length];
            for (int i = 0; i < price.Length; i++)
            {
                price[i] = Convert.ToInt32(prices[i]);
            }
            MyClass mc = new MyClass(str, price);
            //提取第三行-要查看价格的书名
            string book = Console.ReadLine();
            // 输出此书的价格
            Console.WriteLine("The price of {0} is {1}", mc[book].ID, mc[book].Price);
        }
    }
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 winform的chart曲线生成时有凸起
    • ¥15 msix packaging tool打包问题
    • ¥15 finalshell节点的搭建代码和那个端口代码教程
    • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
    • ¥15 Centos / PETSc / PETGEM
    • ¥15 centos7.9 IPv6端口telnet和端口监控问题
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答