C#关于多态的应用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Father
{
public void SpeakName()
{
Console.WriteLine("Father的方法");
}
}
class Son : Father
{
public new void SpeakName()
{
Console.WriteLine("Son的方法");
}
}
class GameObject
{
public string name;
public GameObject(string name)
{
this.name = name;
}
public virtual void Atk()
{
Console.WriteLine("游戏对象进行攻击");
}
}
class Player:GameObject
{
public Player(string name):base(name)
{
}
//重写虚函数
public override void Atk()
{
// base.Atk();
Console.WriteLine("玩家对象进行攻击");
}
}
class Monstor : GameObject
{
public Monstor(string name):base(name)
{
}
public override void Atk()
{
// base.Atk();
Console.WriteLine("怪物对象进行攻击");
}
}
class Duck
{
public virtual void Speak()
{
Console.WriteLine("嘎嘎叫");
}
}
class WoodDuck:Duck
{
public override void Speak()
{
Console.WriteLine("吱吱叫");
}
}
class RubberDuck:Duck
{
public override void Speak()
{
Console.WriteLine("叽叽叫");
}
}
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("多态vob");
//Father f = new Son();
//f.SpeakName();
(f as Son).SpeakName();
//GameObject p = new Player("黄老师");
//p.Atk();
//GameObject m = new Monstor("小怪物");
//m.Atk();
Duck d = new Duck();
d.Speak();
WoodDuck wd = new WoodDuck();
wd.Speak();
RubberDuck rd = new RubberDuck();
rd.Speak();
}
}
}