C#基础:定义集合

我们可以创建自己的集合,可以从System.Collections.CollectionBase类中派生,CollectionBase实现了接口IEnumerable,ICollection,IList.

  1.  public abstract class Animal//父类,抽象类
  2.     {
  3.         private string name;
  4.         public string Name
  5.         {
  6.             set { this.name = value; }
  7.             get { return this.name; }
  8.         }
  9.         public Animal() {
  10.             this.name = "the animal no name";
  11.         }
  12.         public Animal(string name) {
  13.             this.name = name;
  14.         }
  15.         public void Feed() => Console.WriteLine($"{name} has been fed");
  16.     }
  17. //子类继承自Animal
  18.  class Chicken:Animal
  19.     {
  20.         public Chicken(string name) : base(name) { }
  21.         public void LayEgg() => Console.WriteLine($"{Name} has been Lay an Egg");
  22.     } 
  23. //子类继承自Animal
  24. class Cow:Animal
  25.     {
  26.         public Cow(string name) : base(name) { }
  27.         public void Milk() => Console.WriteLine($"{Name}has been Milked");
  28.     } 
  29.  

 //IList CollectionBase   通过继承CollectionBase类实现自定义集合

  1.     public  class Animals : CollectionBase
  2.     {
  3.         public void Add(Animal ani)//添加方法
  4.         {
  5.             List.Add(ani);
  6.         }
  7.         public void Remove(Animal ani)//删除方法
  8.         {
  9.             List.Remove(ani);
  10.         }
  11.         public Animal this[int i]//索引器,和this关键字一起使用,使用索引器就可以使用Animal[0]这种方式访问。
  12.         {
  13.             get { return (Animal)List[i]; }
  14.             set { List[i] = value; }
  15.         }  
  16.     }
  17. //Main方法
  18. static void Main(string[] args){
  19.            Animal animal = new Cow("ss");
  20.            //定义初始化自定义集合方法
  21.             Animals aniCollection = new Animals//
  22.             {
  23.                 new Cow("Lea"),
  24.                 new Chicken("Deer")   
  25.             };
  26.            //方法2,使用Add()方法添加
  27.             aniCollection.Add(animal);
  28.             foreach (Animal a in aniCollection)
  29.             {
  30.                 Console.WriteLine($"New {a.ToString()}" + $" Name={a.Name}");
  31.             }
  32.           //Remove方法
  33.             aniCollection.Remove(animal);
  34.             foreach (Animal a in aniCollection)
  35.             {
  36.                 Console.WriteLine($"New {a.ToString()}" + $" Name={a.Name}");
  37.             }
  38.             aniCollection[0].Feed();//使用索引器访问

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值