C#自定义泛型

using System; using System.Collections.Generic; using System.Text; namespace CustomGenericCollection { #region 汽车的定义 public class Car { public string PetName; public int Speed; public Car(string name, int currentSpeed) { PetName = name; Speed = currentSpeed; } public Car() { } } public class SportsCar : Car { public SportsCar(string p, int s) : base(p, s) { } // 其他方法 } public class MiniVan : Car { public MiniVan(string p, int s) : base(p, s) { } // 其他方法 } #endregion #region 自定义泛型集合 public class CarCollection<T> : IEnumerable<T> where T : Car//:下面的泛型集合类的项目必须是Car 或Car的继承类 { private List<T> arCars = new List<T>(); public T GetCar(int pos) { return arCars[pos]; } public void AddCar(T c) { arCars.Add(c); } public void ClearCars() { arCars.Clear(); } public int Count { get { return arCars.Count; } } // IEnumerable<T>扩展自IEnumerable的,因此,我们需要实现的GetEnumerator()方法的两个版本。 System.Collections.Generic.IEnumerator<T> IEnumerable<T>.GetEnumerator() { return arCars.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return arCars.GetEnumerator(); } public void PrintPetName(int pos) { Console.WriteLine(arCars[pos].PetName); } } #endregion class Program { static void Main(string[] args) { Console.WriteLine("***** Custom Generic Collection *****\n"); CarCollection<Car> myCars = new CarCollection<Car>(); myCars.AddCar(new Car("Rusty", 20)); myCars.AddCar(new Car("Zippy", 90)); foreach (Car c in myCars) { Console.WriteLine("PetName: {0}, Speed: {1}", c.PetName, c.Speed); } Console.WriteLine(); // CarCollection<Car> can hold any type deriving from Car. CarCollection<Car> myAutos = new CarCollection<Car>(); myAutos.AddCar(new MiniVan("Family Truckster", 55)); myAutos.AddCar(new SportsCar("Crusher", 40)); foreach (Car c in myAutos) { Console.WriteLine("Type: {0}, PetName: {1}, Speed: {2}", c.GetType().Name, c.PetName, c.Speed); } Console.ReadLine(); } } }

转载于:https://www.cnblogs.com/zhangqs008/archive/2012/02/10/2398688.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值