首先,要判断是否使用抽象类,可以从下面两个方面进行判断:
1、是不是需要被实例化
2、父类中有没有默认的实现
如果不需要被实例化,父类中没有默认的实现,则用抽象类(否则用虚方法来实现)
下面举个简单的例子:
namespace 抽象类实现多态案例 { class Program { static void Main(string[] args) { //Student s = new Student(); Person p = new Student(); p.SayHi(); p.Standup(); } //尽量用抽象来传输,不要用具体 //static void M1(Person p) //{ // p.Standup(); //} //static Person M2() //{ //} } abstract class Person { public abstract void SayHi(); public abstract void Standup(); } class Student : Person { public override void SayHi() { throw new NotImplementedException(); } public override void Standup() { throw new NotImplementedException(); } } class Teacher : Person { public override void SayHi() { throw new NotImplementedException(); } public override void Standup() { throw new NotImplementedException(); } } }
抽象类的另一个练习
namespace 抽象练习 { class Program1 { static void Main(string[] args) { Duck duck = new RubberDuck(); duck.Swim(); duck.Bark(); Console.ReadKey(); } } public abstract class Duck { public void Swim() { Console.WriteLine("鸭子水上漂。。。"); } public abstract void Bark(); } public class RubberDuck: Duck { public override void Bark() { Console.WriteLine("橡皮鸭的叫声。。。"); } } public class RealDuck : Duck { public override void Bark() { Console.WriteLine("真鸭的叫声。。。"); } } }