C# 面向对象——多态
多态分三种:1.虚方法
2.抽象类
3.接口
1、虚方法
1、将父类的方法标记为虚方法 ,使用关键字 virtual,这个函数可以被子类重新写一个遍。
如:
class Program { static void Main(string[] args) { Chinese cn1 = new Chinese("韩梅梅"); Chinese cn2 = new Chinese("李雷"); American a1 = new American("科比布莱恩特"); American a2 = new American("奥尼尔"); Person[] pers = { cn1, cn2, a1, a2, }; for (int i = 0; i < pers.Length; i++) { pers[i].SayHello(); } Console.ReadKey(); } } /// <summary> /// 父类——人类 /// </summary> public class Person { private string _name; public string Name { get { return _name; } set { _name = value; } } public Person(string name) { this.Name = name; } public virtual void SayHello() { Console.WriteLine("我是人类"); } } /// <summary> /// 子类——中国人 /// </summary> public class Chinese : Person { public Chinese(string name) : base(name) { } public override void SayHello() { Console.WriteLine("我是中国人,我叫{0}", this.Name); } } /// <summary> /// 子类——美国人 /// </summary> public class American : Person { public American(string name) : base(name) { } public override void SayHello() { Console.WriteLine("我叫{0},我是米国人", this.Name); } }
2、抽象类
当父类中的方法不知道如何去实现的时候,可以考虑将父类写成抽象类,将方法写成抽象方法。
class Program { static void Main(string[] args) { //狗狗会叫 猫咪会叫 Animal a = new Cat();//new Dog(); a.Bark(); Console.ReadKey(); } } /// <summary> /// 父类——动物 /// </summary> public abstract class Animal { public virtual void T() { Console.WriteLine("动物有声明"); } private int _age; public int Age { get { return _age; } set { _age = value; } } public Animal(int age) { this.Age = age; } public abstract void Bark(); public abstract string Name { get; set; } public Animal() { } } /// <summary> /// 子类——测试 /// </summary> public abstract class Test : Animal { } /// <summary> ///子类——狗 /// </summary> public class Dog : Animal { public override void Bark() { Console.WriteLine("狗狗旺旺的叫"); } public override string Name { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } /// <summary> /// 子类——猫 /// </summary> public class Cat : Animal { public override void Bark() { Console.WriteLine("猫咪喵喵的叫"); } public override string Name { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } }