using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// C# 的继承是为实现创建一个新类,同时重用,扩展,修改已有的另一个类里的一种方式。 /// 同时它应该遵循 Is-A 原则。还重点介绍了实现继承的几个关键字。 /// override 与 new 的区别 /// </summary> namespace lesson9 { class Program { static void Main(string[] args) { Dog dog = new Dog();//实例化的时候先会调用父类的构造函数 dog.Age = 10; dog.Bite(); dog.GetAge(); dog.BiteMan(); Animal oldDog = new Dog();//隐式的类型转换 实例化一个animal 类型的 dog对象 oldDog.Bite();//overwrite 是重写了父类的方法 oldDog.BiteMan();//new 出来 子类对父类影藏 父类中的biteman并没有重写 ((Dog)oldDog).BiteMan(); Console.ReadLine(); } } class Animal{ public Animal() { Console.WriteLine("Animal constructor"); } public int Age { get; set; } public virtual void Bite()//virtual 意思在与继承中可以重写 { Console.WriteLine("Animal bite"); } public virtual void GetAge() { Console.WriteLine(Age); } public void BiteMan() { Console.WriteLine("Animal bite man"); } } sealed class Dog:Animal //这里的Dog 前面加了sealed就无法被继承 { public Dog() { Console.WriteLine("Dog constructor"); } public override void Bite() { Console.WriteLine("Dog bite"); } public new void BiteMan()//把父类的方法,在子类中影藏 { Console.WriteLine("Dog bite man"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// 1.C#的静态多态 在编译时就已经实现了多态 ///2.C#的动态多态 在运行时实现的多态 /// </summary> namespace lesson10 { class Program { static void Main(string[] args) { PrintHello(); PrintHello("world");//这里是方法的多态 重载 Complex c1 = new Complex(); Complex c2 = new Complex(); c1.Number = 2; c2.Number = 3; Console.WriteLine((c1 + c2).Number); Human human1 = new Man();//这里实现了动态的重载 Human human2 = new Woman(); human1.CleanRoom(); human2.CleanRoom(); Console.WriteLine(c2); //some logic //Human h=new Human(); //if(he is man) //h.CleanRoomSlowly(); //else if (h is woman) //h.cleanroomqucik(); //some logic Console.ReadLine(); } public static void PrintHello() { Console.WriteLine("Hello"); } public static void PrintHello(string toWho) { Console.WriteLine("Hello {0}", toWho); } //运算符的重载 对加号的重载 class Complex { public int Number { get; set; } public static Complex operator +(Complex c1, Complex c2) { Complex c = new Complex(); c.Number = c1.Number + c2.Number; return c; } //实现了对toString 方法的重写 public override string ToString() { return Number.ToString(); } } class Human{ public virtual void CleanRoom() { Console.WriteLine("Human clean room"); } } class Man:Human { public override void CleanRoom() { Console.WriteLine("man Clean slowly"); } } class Woman : Human { public override void CleanRoom() { Console.WriteLine("women Clean quaikly"); } } } }