码迷,mamicode.com
首页 > 其他好文 > 详细

多态练习

时间:2016-04-16 00:37:01      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:


更改前超复杂


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("橡皮鸭子唧唧叫");
}

}

多态练习

标签:

原文地址:http://www.cnblogs.com/swlq/p/5397176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!