DictionaryBase
基类DictionaryBase 实现了 IEnumerable和ICollection 。IList接口 IDictionary接口都有add()、remove()方法。
话不多说直接上案例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace DictionaryBase_Test { public abstract class Animal { public string Name { get; set; } public Animal() => Name = "The animal with no name"; public Animal(string newName) => Name = newName; public void Feed() => Console.WriteLine($"{Name} 在吃东西!"); } public class Animals:DictionaryBase { public void Add(string newID, Animal newAnimal) => Dictionary.Add(newID, newAnimal); public void Remove(string animalID) => Dictionary.Remove(animalID); public Animals() { } public Animal this[string animalID] { get { return (Animal)Dictionary[animalID]; } set { Dictionary[animalID] = value; } } } public class Cow:Animal { public Cow(string newName) : base(newName) { } public void Milk() { Console.WriteLine($"{this.Name} 在被挤奶!"); } } public class Chick:Animal { public Chick(string newName) : base(newName) { } public void LayEgg() { Console.WriteLine($"{this.Name}在下蛋!"); } } class Program { static void Main(string[] args) { Animals animalsDictionary = new Animals(); animalsDictionary.Add("1", new Cow("晖晖")); animalsDictionary.Add("2", new Chick("昕昕")); foreach(DictionaryEntry myEntry in animalsDictionary ) { Console.WriteLine($"KEY:{myEntry.Key} VALUE:{((Animal)myEntry.Value).Name} "); //Console.WriteLine(myEntry.Value.ToString()); } animalsDictionary["1"].Feed(); ((Chick)animalsDictionary["2"]).LayEgg(); Console.ReadKey(); } } }