这里创建的还是class2的实例,不是class1的。但是以class1的模式使用class2这个实例。
呵呵,听起来有点抽象吧。举个简单的例子你理解一下。
using System;
using System.Collections.Generic;
using System.Text;
namespace virtualtest
{
class Food
{
public virtual void Cook()
{
Console.WriteLine("Nothing to do.");
}
public virtual void WhatThis()
{
Console.WriteLine("It's nothing.");
}
}
class Rice : Food
{
public override void Cook()
{
Console.WriteLine("Rice is cooked.");
}
public override void WhatThis()
{
Console.WriteLine("It's Rice");
}
}
class Bread : Food
{
public override void Cook()
{
Console.WriteLine("Bread is cooked.");
}
public override void WhatThis()
{
Console.WriteLine("It's Bread");
}
}
class Program
{
static void Main(string[] args)
{
Food food;
for (int i = 0; i < 3; i++)
{
switch (i)
{
case 0: food = new Rice(); break;
case 1: food = new Bread(); break;
default: food = new Food(); break;
}
food.WhatThis();
food.Cook();
Console.WriteLine();
}
}
}
}