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(); } } }
查看全文
相关阅读:
Flink中的广播流之BroadcastStream
啊。。这是为什么。。 花甜的工作笔记
我那庞大身躯,脆弱心灵的3250 花甜的工作笔记
好吧,我承认,我不是一个专一的人。。。 花甜的工作笔记
沾沾自喜 花甜的工作笔记
我高调的来啦。。。。 花甜的工作笔记
今天偶听一词云终端 花甜的工作笔记
我开始出轨了。 花甜的工作笔记
软件限制策略。。。。。辛苦中。。 花甜的工作笔记
推荐系统建构精选文章
原文地址:https://www.cnblogs.com/zhangqs008/p/2398688.html
最新文章
C++编程学习50个经典网站 强力推荐
智能指针(auto_ptr 和 shared_ptr)
图像处理中的一些基本问题解释
DALSA Coreco 图像处理软件(Sapera LT )
Qt动画框架
孟摘取(Dalsa)
智能指针学习
Qt之实现360安全卫士主界面(一)
CentOS 6.3下Samba服务器的安装与配置
PHP正则表达式屏蔽电话号码中间段
热门文章
UltraEdit下载
函数去抖(debounce)& 函数节流(throttle)总结
mobx在hooks中使用
for in 和for of的区别
关于Js debounce 函数小结
Flink使用connect实现双流join全外连接
重新编译flinkclickhouseconnector后在使用FlinkSQL时报Could not find any factory for identifier 'clickhouse' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath
深入理解maven构建生命周期和各种plugin插件
zookeeper源码编译时在某一个类中找不到引入的类
shell 脚本里的 特殊字符 $(( ))、$( )、``与${ }的区别
Copyright © 2011-2022 走看看