Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class Animal { public virtual void Eat() { Console.WriteLine("Animal eat"); } }
public class Cat : Animal { public override void Eat() { Console.WriteLine("Cat eat"); } }
public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } }
class Tester { static void Main(string[] args) { Animal[] animals = new Animal[3];
animals[0] = new Animal(); animals[1] = new Cat(); animals[2] = new Dog();
for (int i = 0; i < 3; i++) { animals[i].Eat(); } } }
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class Animal { public virtual void Eat() { Console.WriteLine("Animal eat"); } }
public class Cat : Animal { public new void Eat() { Console.WriteLine("Cat eat"); } }
class Tester { static void Main(string[] args) { Animal a = new Animal(); a.Eat();
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class Animal { public virtual void Eat() { Console.WriteLine("Animal eat"); } }
public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } }
public class WolfDog : Dog { public override void Eat() { Console.WriteLine("WolfDog eat"); } }
class Tester { static void Main(string[] args) { Animal[] animals = new Animal[3];
animals[0] = new Animal(); animals[1] = new Dog(); animals[2] = new WolfDog();
for (int i = 0; i < 3; i++) { animals[i].Eat(); } } }
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> public abstract class Animal { public abstract void Eat(); }
public class Cat : Animal { public override void Eat() { Console.WriteLine("Cat eat"); } }
public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } }
public class WolfDog : Dog { public override void Eat() { Console.WriteLine("Wolfdog eat"); } }
class Tester { static void Main(string[] args) { Animal[] animals = new Animal[3];
animals[0] = new Cat(); animals[1] = new Dog(); animals[2] = new WolfDog();
for (int i = 0; i < animals.Length; i++) { animals[i].Eat(); } } }
运行结果为: Cat eat... Dog eat... Wolfdog eat... 从上面可以看出,通过使用abstract-override可以和virtual-override一样地实现多态,包括多层继承也是一样的。不同之处在于,包含虚拟方法的类可以被实例化,而包含抽象方法的类不能被实例化。 以上就是我对c#中多态的一些浅薄的认识,如有错误的地方,欢迎批评指正!