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(); } } }
查看全文
相关阅读:
数据持久化的基础知识
svn常用命令
关于SVN 目录结构
linux查看CPU信息
一个服务器上启动两台tomcat
centos6.0 配置SVN
mysql插入表情
MAC 安装 PIL
安装freetype
Hadoop基本文件命令
原文地址:https://www.cnblogs.com/zhangqs008/p/2398688.html
最新文章
python爬虫之淘宝宝贝图片抓取
关于cocos2dx 2.x CCLabelBMFont的解析优化
xp安装序列号
python学习笔记 ——python写的猜数字游戏 002
Python笔记 001
Android 开发错误信息001
Android列出所有应用,点击可运行~
一张图彻底明白 ++
解决吐司连续触发一直显示的问题
重写ScrollView 解决ScrollView嵌套viewpager事件冲突
热门文章
popwindow设置背景半透明
I/O Techie 社区 --欢迎您的加入
svn: E155004 is already locked 解决方案
Xcode的清除缓存
判读字符串是否为空的全局宏-分享
CocoaPods pod install/pod update更新慢的问题
视图加载生命周期
现在的我
使用TFHelp解析Html
视图置顶 导航栏遮挡
Copyright © 2011-2022 走看看