- public interface ISay
- {
- void Say();
- }
-
- public class RealDuck : ISay
- {
- public void Say()
- {
- Console.WriteLine("我是真鸭子");
- }
- }
-
- public class WoodDuck : ISay
- {
- public void Say()
- {
- Console.WriteLine("我是木鸭子");
- }
- }
-
- public class FakeDuck : ISay
- {
- public void Say()
- {
- Console.WriteLine("我是假鸭子");
- }
- }
-
- public class TestDuck
- {
- public static void Test()
- {
- //接口多态
- List<ISay> ducks = new List<ISay>{
- new RealDuck(), new FakeDuck(), new WoodDuck()
- };
-
- foreach (var duck in ducks)
- {
- duck.Say();
- }
-
- Console.WriteLine("---------------------------");
- List<Duck> ducks2 = new List<Duck>{
- new RealDuck2(), new FakeDuck2(), new WoodDuck2()
- };
-
- foreach (var duck in ducks2)
- {
- duck.Say();
- }
-
- }
- }
-
- public class Duck
- {
- public virtual void Say(){}
- }
-
- public class RealDuck2 : Duck
- {
- public override void Say()
- {
- Console.WriteLine("我是RealDuck2");
- }
- }
-
- public class WoodDuck2 : Duck
- {
- public override void Say()
- {
- Console.WriteLine("我是WoodDuck2");
- }
- }
-
- public class FakeDuck2 : Duck
- {
- public override void Say()
- {
- Console.WriteLine("我是FakeDuck2");
- }
- }
复制代码 以前回答的别人的答案,可以参考下 |