Exemple #1
0
 public void demo8()
 {
     Animal[] animals = new Animal[3];
     animals[0] = new Cat();
     animals[1] = new Bird();
     animals[2] = new Dog();
     foreach (Animal animal in animals)
     {
         ILiveBirth live = animal as ILiveBirth;
         if (null != live)
         {
             Console.WriteLine("Baby is called: {0}", live.BabyCalled());
         }
     }
 }
Exemple #2
0
 static void Main()
 {
     Animal[] animalArray = new Animal[3];
     animalArray[0] = new Cat();
     animalArray[1] = new Bird();
     animalArray[2] = new Dog();
     foreach (Animal a in animalArray)
     {
         ILiveBirth b = a as ILiveBirth;
         if (b != null)
         {
             Console.WriteLine("Baby is called: {0}", b.BabyCalled());
         }
     }
 }
        static void Main()
        {
            Animal[] animalArray = new Animal[3];  // Create Animal array

            animalArray[0] = new Cat();            // Insert Cat class object
            animalArray[1] = new Bird();           // Insert Bird class object
            animalArray[2] = new Dog();            // Insert Dog class object

            foreach (Animal a in animalArray)      // Cycle through array
            {
                ILiveBirth b = a as ILiveBirth;    // if implements ILiveBirth...
                if (b != null)
                {
                    Console.WriteLine("Baby is called: {0}", b.BabyCalled());
                }
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            List <Animal> animals = new List <Animal> {
                new Cat(),
                new Bird(),
                new Dog()
            };                                                                //将各个动物类添加到泛型集合中

            foreach (Animal item in animals)                                  //遍历
            {
                ILiveBirth liveBirth = item as ILiveBirth;                    //转接口引用
                if (liveBirth != null)                                        //若实现接口
                {
                    Console.WriteLine("this is {0}", liveBirth.BabyCalled()); //执行实现方法
                }
            }
            Console.ReadKey();
        }
Exemple #5
0
        /// <summary>
        /// 示例:实现接口,同时对于as关键字的使用
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            //数组创建时,需要留意
            Animal[] animalArray = new Animal[3];

            //使用多态
            animalArray[0] = new Cat();
            animalArray[1] = new Bird();
            animalArray[2] = new Dog();

            foreach (Animal a in animalArray)
            {
                //判断是否实现ILiveBirth接口
                ILiveBirth b = a as ILiveBirth;//此处作为关键点
                if (b != null)
                {
                    Console.WriteLine("name is " + b.BabyCalled());
                }
            }

            Console.ReadKey();
        }