C# 接口 简单示例

using System;
using static System.Console;

namespace ImplementingInterface
{
    class Program
    {
        static void Main(string[] args)
        {
            Zoo zoo = new Zoo();
            zoo.Show(new Dog());
            zoo.Show(new Cat());
            ReadLine();
        }
    }

    class Zoo
    {
        public void Show(IAnimal animal)
        {
            animal.LikeFood();
        }
    }

    //class Animal
    interface IAnimal
    {
        void LikeFood();
    }

    class Dog : IAnimal
    {
        public void LikeFood()
        {
            WriteLine("I'm a Dog, I like eat meat.");
        }
    }

    class Cat : IAnimal
    {
        public void LikeFood()
        {
            WriteLine("I'm a Cat, I like eat fish.");
        }
    }
}
  • 主要意义在于不更改Zoo方法的情况下,对新增加的类进行实现
posted @ 2018-08-27 16:59  码农吉小星  阅读(1304)  评论(2编辑  收藏  举报