Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfacePractice
{
    class Program
    {
        static void Main(string[] args)
        {
            Animal myPet = new Animal();
            IBark pet;

            pet = new Dog();
            myPet.DoBark(pet);

            pet = new Cat();
            myPet.DoBark(pet);

            Console.ReadLine();
        }
    }
}

IBark.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfacePractice
{
    interface IBark
    {
        void Bark();
    }
}

Dog.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfacePractice
{
    class Dog : IBark
    {
        public Dog()
        {

        }

        public void Bark()
        {
            Console.WriteLine("汪汪");
        }
    }
}

Cat.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfacePractice
{
    class Cat : IBark
    {
        public Cat()
        {

        }

        public void Bark()
        {
            Console.WriteLine("喵喵");
        }
    }
}

Animal.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfacePractice
{
    class Animal
    {
        internal void DoBark(IBark pet)
        {
            pet.Bark();
        }
    }
}

 

arrow
arrow
    文章標籤
    c# interfaces example
    全站熱搜

    痞客興 發表在 痞客邦 留言(0) 人氣()