7.5使用基类的引用
派生类的实例由基类的实例加上派生类附加的成员组成,派生类引用指向整个类对象,包括基类部分。
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
using System;
namespace Examples
{
class MyBaseClass
{
public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass
{
new public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class Program
{
static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
derived.Print();
mybc.Print();
}
}
}
This is the derived class.
This is the base class.
请按任意键继续. . .
7.5.1 虚方法和覆写方法
虚方法可以使基类的引用方式“升至”派生类内。
using System;
namespace Examples
{
class MyBaseClass
{
virtual public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass
{
override public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class Program
{
static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
derived.Print();
mybc.Print();
}
}
}
This is the derived class.
This is the derived class.
请按任意键继续. . .
7.5.2 覆写标记为override的方法
当使用对象基类部分的引用调用一个覆写方法时,方法的调用被沿派生层次上溯执行,一直到标记为override的方法的最派生(most-derived)版本。
情况1:使用override声明Print()
using System;
namespace Examples
{
class MyBaseClass // Base class
{
virtual public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass // Derived class
{
override public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class SecondDerived : MyDerivedClass
{
override public void Print() //这里使用override
{
Console.WriteLine("This is the second derived class.");
}
}
class Program
{
static void Main()
{
SecondDerived derived = new SecondDerived(); // Use SecondDerived.
MyBaseClass mybc = (MyBaseClass)derived; // Use MyBaseClass.
derived.Print();
mybc.Print();
}
}
}
This is the second derived class.
This is the second derived class.
请按任意键继续. . .
情况2:使用new声明Print()
class MyDerivedClass : MyBaseClass
{
new public void Print()
{
Console.WriteLine("This is the derived class.");
}
}
class Program
{
static void Main()
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass mybc = (MyBaseClass)derived;
derived.Print();
mybc.Print();
}
}
This is the second derived class.
This is the derived class.
请按任意键继续. . .
7.8 成员访问修饰符
internal 同一程序集访问
protected 派生类可访问
protected internal 听那个一程序集和派生类可访问
7.10 抽象类 abstract
7.11 密封类 sealed
抽象方法必须是基类,它不能实例化。密封类恰好相反。
7.12 静态类
类必须为静态,类成员也必须为静态。