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(); } } }
查看全文
相关阅读:
解决linux下svn update 产生Node remains in conflict的问题
实现本地svn目录同步时,服务器的相应目录保持自动同步
linux下搭建SVN
linux下安装pip与pip安装
CentOS7下将Python的版本升级为3.7
Linux基础二:初识linux命令
泛型数组 + 记录类型 + Json 之间的转换
TDictionary字典 记录 的赋值。
TDictionary字典 对象的释放。。。
基于 Intraweb 和 JQuery 的开发套件
原文地址:https://www.cnblogs.com/zhangqs008/p/2398688.html
最新文章
为 PhpStorm 配置 Xdebug 来调试代码
PHPStorm + Xdebug 调试PHP代码 有大用
各操作系统下php.ini文件的位置在哪里
xampp默认mysql数据库root密码的修改
使用MAC OS X进行PHP开发的一些建议和技巧
NSProxy实现AOP方便为ios应用实现异常处理策略
Openstack 实现技术分解 (1) 开发环境 — Devstack 部署案例详解
Openstack 实现技术分解 (1) 开发环境 — Devstack 部署案例详解
Python 常用 PEP8 编码规范和建议
Python 常用 PEP8 编码规范和建议
热门文章
手动配置 ESXi 主机挂载 NFS 的最大值
手动配置 ESXi 主机挂载 NFS 的最大值
用 Flask 来写个轻博客 (37) — 在 Github 上为第一阶段的版本打 Tag
用 Flask 来写个轻博客 (37) — 在 Github 上为第一阶段的版本打 Tag
用 Flask 来写个轻博客 (36) — 使用 Flask-RESTful 来构建 RESTful API 之五
用 Flask 来写个轻博客 (36) — 使用 Flask-RESTful 来构建 RESTful API 之五
常见SMTP发送失败原因列表
python+selenium十五:CSS与Jquery
python+selenium十四:xpath和contains模糊匹配
Linux基础三:linux目录结构和目录文件的浏览、管理及维护
Copyright © 2011-2022 走看看