字典,通过key---value键值对存储,访问数据的,可以通过继承DictionaryBase类来创建自定义字典,DictionaryBase类实现了IEnumerable和ICollection接口。
- public abstract class Animal//父类,抽象类
- {
- private string name;
- public string Name
- {
- set { this.name = value; }
- get { return this.name; }
- }
- public Animal() {
- this.name = "the animal no name";
- }
- public Animal(string name) {
- this.name = name;
- }
- public void Feed() => Console.WriteLine($"{name} has been fed");
- }
- //子类继承自Animal
- class Chicken:Animal
- {
- public Chicken(string name) : base(name) { }
- public void LayEgg() => Console.WriteLine($"{Name} has been Lay an Egg");
- }
- //子类继承自Animal
- class Cow:Animal
- {
- public Cow(string name) : base(name) { }
- public void Milk() => Console.WriteLine($"{Name}has been Milked");
- }
//IDictionary通过继承DictionaryBase实现自定义字典
- public class Animals : DictionaryBase
- {
- public Animals() { }
- public void Add(string index, Animal ani)//Add()方法通过添加key----value键值对添加
- {
- Dictionary.Add(index, ani);
- }
- public void Remove(string index)//Remove()方法通过索引删除
- {
- Dictionary.Remove(index);
- }
- public Animal this[int i]//索引器和this一起使用,通过索引器可以以Animal[0]的方式访问
- {
- get { return (Animal)Dictionary[i]; }
- set { Dictionary[i] = value; }
- }
- }
//Main() 方法
- staticvoidMain(string[] args){
- Animal animals = new Cow("ss");
- Animals aniDictionary = new Animals();//自定义字典对象
- aniDictionary.Add("001", animals);//添加key ---value对象
- aniDictionary.Add("002", new Cow("lily"));
- aniDictionary.Add("003", new Chicken("dark"));
- foreach (DictionaryEntry ani in aniDictionary)//foreach循环输出
- {//通过ani.key和ani.value来访问
- Console.WriteLine(ani.Key.ToString() + ":::" + ((Animal)ani.Value).Name.ToString());
- }
- Console.WriteLine();
- aniDictionary.Remove("001");//删除,通过索引删除
- foreach (DictionaryEntry it in aniDictionary)
- {
- Console.WriteLine(it.Key.ToString() + "|||" + ((Animal)it.Value).Name.ToString());
- }
- Console.WriteLine();
- }
-