请求c#多态问题,谢谢

来源:百度知道 编辑:UC知道 时间:2024/05/22 13:02:30
using System;
using System.Collections.Generic;
using System.Text;

namespace TestVirtual
{
class Program
{
static void Main(string[] args)
{
Base b = new Base();
Derived d = new Derived();
b.Print();
d.Print();
b.Display();
d.Display();
b = d;
b.Print();//解释下这行
d.Print();
b.Display();//还有这行
d.Display();
}
}
}
class Base
{
public void Display()
{
Console.WriteLine("Display in Base");
}
public virtual void Print()
{
Console.WriteLine("Print in Base");
}
}

class Derived : Base
{
new public void Display()
{
Console.WriteLine("Display in Derived&qu

b和d实际上存储的都是个地址(对象的在内存中的储存地址)
所以将d赋值给b后
b和d实际上就是指的都是对象d
只是b是Base类型
就像是定义了一个父类型子对象(例如:Base a=new Derived())
而在调用方法的时候就时候就看类型了(变量.方法名())
所以当用b.Print()用的就是调用父类的方法
public virtual void Print()
{
Console.WriteLine("Print in Base");
}
如果用d.Print()用的则是调用子类的方法
public override void Print()
{
Console.WriteLine("Print in Derived");
}

在VS上调试一下就清楚了