本文介绍了请让我清楚了解抽象类和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我一些真实的简单示例,它可以使我清楚地知道我们使用接口可以执行的操作,而不能使用抽象类实现.

Please give me some real life simple example which can make me clear what exactly we can do using interface and can''t do with abstract class

推荐答案

class Program
    {
        static void Main(string[] args)
        {
            //abstract classes in list<t>
            List<car> cars = new List<car>();
            cars.Add(new Honda());
            cars.Add(new Renult());

            foreach (Car car in cars)
                car.Manufactured();           

            //interfaces in list<t>:
            List<ibike> bikes = new List<ibike>();
            bikes.Add(new Suzuki());
            bikes.Add(new Ducatti());
            foreach (IBike bike in bikes)
                bike.Manufactured();

            //as you can see in my example there is the same implementation of both types
            Console.ReadLine();

        }
    }

    //ABSTRACT:
    public abstract class Car
    {
        public abstract void Manufactured(); //abstract method
    }

    public class Honda : Car
    {
        public override void Manufactured()
        {
            Console.WriteLine("Honda is a Japanese car.");
        }
    }

    public class Renult : Car
    {
        public override void Manufactured()
        {
            Console.WriteLine("Renault is a Franch car.");
        }
    }

    //INTERFACE:
    public interface IBike
    {
        void Manufactured();
    }

    public class Suzuki : IBike
    {
        public void Manufactured()
        {
            Console.WriteLine("Suzuki is prodused on Japan.");
        }
    }

    public class Ducatti : IBike
    {
        public void Manufactured()
        {
            Console.WriteLine("Ducatti is prodused in Italy.");
        }
    }




这篇关于请让我清楚了解抽象类和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:04