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方法的情況下,對新增加的類進行實現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM