更改前超复杂:
static void Main(string[] args)
{
//真的鸭子嘎嘎叫 木头鸭子吱吱叫 橡皮鸭子唧唧叫
RealDuck rd = new RealDuck();
rd.Bark();
MuDuck md = new MuDuck();
md.Bark();
XpDuck xp = new XpDuck();
xp.Bark();
Console.ReadKey();
}
}
public class RealDuck
{
public void Bark()
{
Console.WriteLine("真的鸭子嘎嘎叫");
}
}
public class MuDuck
{
public void Bark()
{
Console.WriteLine("木头鸭子吱吱叫");
}
}
public class XpDuck
{
public void Bark()
{
Console.WriteLine("橡皮鸭子唧唧叫");
}
}
运用多态实现:
static void Main(string[] args)
{
//真的鸭子嘎嘎叫 木头鸭子吱吱叫 橡皮鸭子唧唧叫
RealDuck rd = new RealDuck();
MuDuck md = new MuDuck();
XpDuck xp = new XpDuck();
RealDuck[] ducks = {rd,md,xp };
for (int i = 0; i < ducks.Length; i++)
{
ducks[i].Bark();
}
Console.ReadKey();
}
}
public class RealDuck
{
public virtual void Bark()
{
Console.WriteLine("真的鸭子嘎嘎叫");
}
}
public class MuDuck:RealDuck
{
public override void Bark()
{
Console.WriteLine("木头鸭子吱吱叫");
}
}
public class XpDuck:RealDuck
{
public override void Bark()
{
Console.WriteLine("橡皮鸭子唧唧叫");
}
}