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方法的狀況下,對新增長的類進行實現
相關文章
相關標籤/搜索