zoukankan
html css js c++ java
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(); } } }
查看全文
相关阅读:
LeetCode
在linux服务器下部署python工程(爬虫)
linux安装python3.6 及 beautifulsoup
HDU 1561 The more, The Better[树形dp/01背包]
POJ 3107 Godfather[树的重心]
POJ 1655 Balancing Act[树的重心/树形dp]
HDU 2169 Computer[树形dp]
HDU
POJ1721--CARDS [置换]
POJ 1026 Cipher[置换]
原文地址:https://www.cnblogs.com/zhangqs008/p/2398688.html
最新文章
Internet History,Technology,and Security
福大软工1816 · 第三次作业
福大软工1816 · 第二次作业
福大软工1816 · 第一次作业
MySQL学习(三): 初识数据表
MySQL学习(一): MySQL的初步操作与命令
MySQL学习(二): 数据类型记录
经典匹配问题0.0
数学拆分问题--贪心与乘法逆元
关于二叉树某点到各点的距离问题
热门文章
poj 1741 树的分治
视频课程
对1001. A+B Format (20)的描述
大一下学期的自我目标
LeetCode
LeetCode
Git 服务器搭建
数据链路层协议
LeetCode
模板
Copyright © 2011-2022 走看看