首页 > 代码库 > 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#多态