首页 > 代码库 > C#多态
C#多态
C#多态本质重载,一个方法实现不同的功能,分为静态多态和动态多态
一、静态多态(包括对方法重装和对操作符重载)
1.1 对方法重载
声明:
private static void SayHello() { Console.WriteLine("hello!"); } private static void SayHello(string name) { Console.WriteLine(name + " say hello!"); }
调用:
SayHello();SayHello("mr.tian");
1.2 对运算符重载
声明:
class Complex { public Complex() { } public Complex(int i) { Num = i; } public int Num { get; set; } public static Complex operator +(Complex com1, Complex com2) { Complex result = new Complex(); result.Num = com1.Num + com2.Num; return result; } }
调用:
Complex test1 = new Complex(5);Complex test2 = new Complex(10);Complex test3 = test1 + test2;Console.WriteLine(test3.Num);
二、动态多态,通过override来重载
声明:
class Human { public virtual void CleanRoom() { Console.WriteLine("Human clean room"); } } class Man :Human { public override void CleanRoom() { Console.WriteLine("Man clean room"); } } class Woman : Human { public override void CleanRoom() { Console.WriteLine("Woman clean room"); } }
使用:
Human human1 = new Man(); Human human2 = new Woman(); human1.CleanRoom(); human2.CleanRoom();
结果:
C#多态
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。