泛型+多态
来源:互联网 发布:淘宝什么是运费险 编辑:程序博客网 时间:2024/05/08 07:38
问:泛型 T我们常说是类的占位符,但是这个"T"是通过什么机制,来正常运行得到正确的结果呢?
答:泛型是在多态上开花结果的。
举一个简单的例子:男女平均身高是不同的,所以判断男,女身高的标准就不同,但是两者的比较过程是完全一样的。如果我们只写一个比较身高的方法,如果按照男士的平均身高进行判断,那么对女士来说就是不准确的,如果按照女士的平均身高来判断,那么对男士来说是不准确的,那么如何做到判断男士身高根据男士平均身高,判断女士根据女士平均身高呢?对象为男士的话,调用男士对象的身高方法,对象为女士的话,调用女士的身高方法。
现在创建一个父类:
namespaceGeneric.demo{ public class Person { public double height; public string name; public Person() { this.height = 1.6; this.name = "小菜"; } public Person(string name,doubleheight) { this.height = height; this.name = name; } virtual public void IsTall() { if (height > 1.68) { Console.Write("The Personnamed {0} is tall", name); Console.WriteLine(); } else { Console.Write("The Personnamed {0} is short", name); Console.WriteLine(); } } }}
现在创建一个子类
namespaceGeneric.demo{ public class Woman : Person { public Woman() { this.height = 1.68; this.name = "小红"; } public Woman(string name, doubleheight) { this.height = height; this.name = name; } public override void IsTall() { if (height > 1.68) { Console.Write("The Womannamed {0} is tall", name); Console.WriteLine(); } else { Console.Write("The Womannamed {0} is short", name); Console.WriteLine(); } } }}
现在创建一个子类:
namespaceGeneric.demo{ public class Man : Person { public Man() { this.height = 1.78; this.name = "张亮"; } public Man(string name, double height) { this.height = height; this.name = name; } public override void IsTall() { if (height > 1.78) { Console.Write("The Mannamed {0} is tall", name); Console.WriteLine(); } else { Console.Write("The Womannamed {0} is short", name); Console.WriteLine(); } } }}
现在创建一个泛型类:
namespaceGeneric.demo{ public class HeightCompare<T> where T: Person { public void IsTall(T person) { person.IsTall(); } }}
现在对泛型类进行调用
static void Main(string[] args) { //人对象 Person person=newPerson("张",1.79); HeightCompare<Person> hc =new HeightCompare<Person>(); hc.IsTall(person); //男人对象 Man man = newMan("李",1.80); HeightCompare<Man> hcm = newHeightCompare<Man>(); hcm.IsTall(man); //女人对象 Woman woman = newWoman("杨", 1.69); HeightCompare<Woman> hcw =new HeightCompare<Woman>(); hcw.IsTall(woman); }
运行结果:
1 0
- 泛型+多态
- 多态 覆盖 重载 重写 模板 泛型
- 多态 虚方法 抽象类 泛型
- 面向对象三大特征:继承、封装、多态 (泛型)
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- 多态
- linux常用命令----tr
- 第七讲,三数最大值
- 在linux中install命令和cp命令的区别
- 写好规范的流程图是培养良好逻辑能力的起点
- 《C#高级编程》【第八章】委托、lambda表达式和事件 -- 学习笔记
- 泛型+多态
- Sax解析XML
- android配置oracle jdk
- XMPP系列(五)---文件传输
- hd1509 Windows Message Queue
- Objective-C中类属性的 copy, tetain, assign , readonly , readwrite, nonatomic区别
- Activity向Fragment中传值
- warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s inste
- WinForm自定义ListBox显示样式