1.利用继承,让派生类来重写父类的方法
[csharp] view plaincopy
class Program
{
static void Main(string[] args)
{
Anmial a1 = new Anmial();
Dog d1 = new Dog();
Anmial da = new Dog();
List<Anmial> list = new List<Anmial>();
list.Add(a1);
list.Add(d1);
list.Add(da);
foreach(Anmial a in list)
{
a.Say();
}
Console.ReadKey();
}
}
class Anmial
{
public virtual void Say()
{
Console.WriteLine("Anmial Say");
}
}
class Dog : Anmial
{
public override void Say()
{
Console.WriteLine("Dog Say");
}
}
class Mouse : Anmial
{
public override void Say()
{
Console.WriteLine("Mouse Say");
}
}
class Cat:Anmial
{
//........没有重写方法的时候,调用的是父类的方法,(因为是继承了父类的方法)
}
运行结果:
Anmial Say
Dog Say
Dog Say
2.抽象类的抽象方法实现多态
[csharp] view plaincopy
class Program
{
static void Main(string[] args)
{
Anmial a1 = new Cat();
Anmial d1 = new Dog();
List<Anmial> list = new List<Anmial>();
list.Add(a1);
list.Add(d1);
foreach (var a in list)
{
a.Say();
}
Console.ReadKey();
}
}
/// <summary>
/// 抽象类中只能声明,方法,属性,索引器,字段等,不能被实例化
/// </summary>
public abstract class Anmial
{
public void Fly()
{
Console.WriteLine("飞");
}
public abstract void Say();//抽象方法,没有方法的实现体
}
class Cat:Anmial
{
public override void Say()
{
Console.WriteLine("猫叫");
}
}
class Dog : Anmial
{
public override void Say()
{
Console.WriteLine("狗叫");
}
}
3.接口实现多态
[csharp] view plaincopy
class Program
{
static void Main(string[] args)
{
Anmial a1 = new Dog();
Anmial c1 = new Cat();
List<Anmial> list = new List<Anmial>();
list.Add(a1);
list.Add(c1);
foreach(var a in list)
{
a.Say();
}
Console.ReadKey();
}
}
interface Anmial
{
void Say();
}