——摘自Rocky Ren
对于抽象类,只需要将它看成一种其他类实现某些功能的模版,例如我们定义一个事物模版,那么它有身高,体重,语言,国籍,语言......这样的一系列的特征我们知道他应该描述的是一个人,只要我们将这些特性一一赋值,就能知道这个事物的具体存在。因此我们不能实例化这个模版(不能使用new关键字),他不代表任何一个现实的存在,只是为利用它而进行实例化的实例提供了若干接口,因为他是模版所以不能私有化,即不能使用private关键字。同时抽象方法隐含为virtual方法,以重写(override)的方式达到实例化的目的,但是不能使用virtual关键字。
在对抽象类测试的过程中,我发现了如下特性:
1.抽象类中可以包含非抽象的虚方法或非抽象的非虚方法。
2.非抽象类中不可以包含抽象成员
3.因为不能实例化因此不能使用this或base关键字代替实例,即继承自抽象类的类中不能通过base关键字访问基类成员。
4.不能实例化抽象类,但是可以实例化抽象类类型的数组类型。
.5一个类若是继承了一个抽象类但是没有完全重写基类的抽象成员,那么这个类依旧只能是抽象类,此规则对继承该类的子类继续有效。
6.对于一个抽象类中包含非抽象的虚方法,若是抽象类或非抽象类继承该方法简单都是做简单的重写处理,但是抽象类可以使用抽象方法二次重写该虚方法,同时继续继承该抽象类的非抽象类中必须重写其基类的抽象方法。
以下是我的测试代码:
using System;
namespace Abctract{ public abstract class Person { public abstract string Language { get; } public abstract void Work(); public string language; } class Chinese : Person { public override string Language { get { return "SPeaking Chinese"; } } public override void Work() { Console.WriteLine("programmer"); Console.WriteLine(Language); } /*void trybase() { //base.Work();//error:the Work() is abstract method }*/ } class Canadian : Person { public override string Language { get { return "Speaking English"; } } public override void Work() { Console.WriteLine("teacher"); Console.WriteLine(Language); } } #region( test use an abstract method overrides the base class's virtual method) //start: class p { public virtual void F() { Console.WriteLine("call: p.F()"); } } abstract class p1 : p { public abstract override void F();// overrides the base class's virtual method } class p1_1 : p1 { public override void F() { Console.WriteLine("call: p1_1.F()"); //Abstract methods must be rewritten } } //:end #endregion( test use an abstract method overrides the base class's virtual method) abstract class Military : Person//Non-abstract methods can not be here { public void G() { Console.WriteLine("Non-abstract methods in abstract Class"); } } class Soldier : Military { public override string Language { get { return "Speaking English"; } } public override void Work() { Console.WriteLine("Fight"); } } class Test { public static void Main() { //error: Person person = new Person(); Person[] person = new Person[2]; person[0] = new Chinese(); person[1] = new Canadian(); for (int i = 0; i < person.Length; i++) { person[i].Work(); Console.WriteLine("=========="); } p1_1 n = new p1_1(); n.F(); /*Here if the p1_1 not override inherited abstract methods, else occurs tips of an exception For example: class p1_1 : p1 { } */ Console.WriteLine("=========="); Soldier s = new Soldier(); s.Work(); s.G(); Console.WriteLine(s.Language); Console.ReadKey(); } } }