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(); } } }
查看全文
相关阅读:
JZOJ 100019.A
idea突然无法智能提示了
C基于 postgresql-devel 连接postgresql 数据库,实现增删改查的代码封装
gcc 编译第三方库
C 语言中的指针函数写法
java 基于RXTX配置linux和window串口
springboot 在windows 中打jar包运行正常, 但是在linux 环境中报错 加载不到主类
求4 的余数
win10 定时重启某个程序
win10 使用ssh远程 linux机器并修改了hostname, 然后重新连接的时候连接不上, 但是其它机器可以远程上
原文地址:https://www.cnblogs.com/zhangqs008/p/2398688.html
最新文章
js中数组移除未知位置的已知内容项
Vue中provide/inject
Vue中$ref、$emit、props三中传参方式区别和使用
Vue.js中 watch
在vsCode中react中写html不会自动补全
vue项目中 路径使用的@和~的区别
[SDOI2013]项链
JZOJ 3423.Vani和Cl2捉迷藏 & [CTSC2008]祭祀
JZOJ 4366. 【GDKOI2016】项链
JZOJ 3304. Theresa与数据结构
热门文章
LG P5043 树同构
斯坦那树学习笔记
LG P3653 小清新数学题
Luogu P3601 签到题
二进制枚举子集
JZOJ 3242. Spacing
JZOJ 3293. 【SHTSC2013】阶乘字符串
[POI2011]MET-Meteors
Dynamic Rankings
JZOJ 3889
Copyright © 2011-2022 走看看