|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
使用虚方法(virtual)和覆写(override)方法可以使基类的引用访问“升级”到派生类中。
而在最高继承使用了new之后,基类的引用不会再最高继承中出现,只能到最后一个覆写(override)方法中体现。
namespace 使用声明的虚方法和覆盖的实例
{
class Program
{
static void Main(string[] args)
{
SecondDerived derived = new SecondDerived(); //实例化
MyBaseClass mybc = derived; //强制转换成基类
derived.Print();
mybc.Print();
Console.ReadKey();
}
}
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 SecondDerived : MyDerivedClass //派生类
{
override public void Print()
{
Console.WriteLine("This is the second derived class.");
}
}
}
输出结果
This is the second derived class.
This is the second derived class.
namespace 使用new声明的虚方法和覆盖的实例
{
class Program
{
static void Main(string[] args)
{
SecondDerived derived = new SecondDerived(); //实例化
MyBaseClass mybc = derived; //强制转换成基类
derived.Print();
mybc.Print();
Console.ReadKey();
}
}
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 SecondDerived : MyDerivedClass //派生类
{
new public void Print() //隐藏继承成员
{
Console.WriteLine("This is the second derived class.");
}
}
}
输出结果
This is the second derived class.
This is the derived class. |
|