Unity学习之接口的回顾

欢迎大家来到我的博客http://unity.gopedu.com/home.php?mod=space&uid=3352&do=blog&view=me&from=space

上一次的考试,有点忘了接口的经典用法,下面介绍个例子,来回顾一下接口的用法。

中国人吃中餐,西方人吃西餐

namespace Test

{

    //声明一个吃的接口

    interface EatBehavior

    {

         void Eat();

}

//中国人吃的方法

   class ChineseMeal : EatBehavior

    {

        public void Eat() {

            Console.WriteLine("Chniese Food");

        }

}

//西方人吃的方法

    class WesternStyleFood : EatBehavior

    {

        public void Eat()

        {

            Console.WriteLine("Western Food");

        }

    }

    abstract class Person

    {

       private string name;

       private int age;

       private string eatBehavior;

 

       public void SetName(string name) {

           this.name = name;

       }

       public string GetName() {

           return name;

       }

       public void SetAge(int age) {

           this.age = age;

       }

       public int GetAge() {

           return age;

       }

       public void SetEatBehavior(string eatBehavior) {

           this.eatBehavior = eatBehavior;

       }

       public string GetEatBehavior() {

           return eatBehavior;

       }

//接口的妙用,利用接口做参数,只需要传不同的实现类,便会调用不同的方法

       public void PerformEat(EatBehavior eb) {

           eb.Eat();

       }

    }

    class Chinese:Person

    {

        public Chinese(string name) {

            Console.Write(name);

        }

    }

    class American:Person

    {

        public American(string name) {

            Console.Write(name);

        }

    }

      class A

      {

        static void Main(string[] args) {

            Chinese c = new Chinese("Chinese");

            c.PerformEat(new ChineseMeal());

 

            American a = new American("American");

            a.PerformEat(new WesternStyleFood());

            Console.ReadKey();

        }

    }

}

请继续关注我的博客

http://unity.gopedu.com/home.php?mod=space&uid=3352&do=blog&view=me&from=space

更多精彩尽在http://www.gopedu.com/

你可能感兴趣的:(Unity学习,U3D培训,Unity培训)