C#自定义集合类(二)

在System.Collections 命名空间下,常用的集合类中,这两个类不属于集合,而是作为自定义集合类的基类。
内置的集合并不能满足所有的数据集合处理,c#为用户自定义集合提供条件。这两个基类如下:
CollectionBase:为强类型集合提供abstract 基类
DictionaryBase:为键/值对的强类型集合提供abstract基类。
集合类有键值对的字典集合和一般集合,这两个基类一个作为非字典集合的基类,一个作为字典集合的基类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;

namespace ConsoleApplication1
{
    public class Food
    {
        public String Name { get; set; }
        public double Price { get; set; }
        public Food(String name, double price)
        {
            this.Name = name;
            this.Price = price;
        }
    }

    public class FoodList : CollectionBase
    {
        //重写父类的Add方法
        public virtual int Add(Food food)
        {
            return base.InnerList.Add(food);
        }

        public new void RemoveAt(int index)//父类中该方法不允许重写,需要使用new关键字屏蔽父类的RemoveAt方法
        {
            InnerList.RemoveAt(index);
        }

        public Food GetItem(int index)
        {
            return (Food)base.List[index];
        }
    }

    class Program
    {
        static void Main()
        {
            Food food1 = new Food("苹果", 2.1);
            Food food2 = new Food("香蕉", 3.1);
            Food food3 = new Food("橘子", 4.1);
            Food food4 = new Food("西红柿", 5.1);
            FoodList foodlist = new FoodList();
            foodlist.Add(food1);
            foodlist.Add(food2);
            foodlist.Add(food3);
            foodlist.Add(food4);
            for (int i = 0; i < foodlist.Count; i++)
            {
                Console.WriteLine("名称:{0} 价格:{1}", foodlist.GetItem(i).Name, foodlist.GetItem(i).Price);
            }

            Console.WriteLine("删除index=1的元素后:");
            foodlist.RemoveAt(1);
            for (int i = 0; i < foodlist.Count; i++)
            {
                Console.WriteLine("名称:{0} 价格:{1}", foodlist.GetItem(i).Name, foodlist.GetItem(i).Price);
            }

            Console.ReadLine();
        }
    }
}
View Code

posted @ 2020-04-30 14:59  LuckyZLi  阅读(261)  评论(0编辑  收藏  举报