Beispiel #1
0
        static void Main(string[] args)
        {
            //Class2 c3 = new Class3
            //{
            //    Name = "Kalle",
            //    Age = 45,
            //    Adress = "Blåbärsvägen 3"
            //};


            List <IDrive> vehicles = new List <IDrive>()
            {
                new FuelVehicle("ABC123", 100),
                new FuelCar("ABC123", 150)
                {
                    FuelLevel = 100
                },
                new Moped("ABD234"),
                new Vehicle("EFR567")
            };


            //Loopar på alla vehicles
            foreach (var vehicle in vehicles)
            {
                //Kör drive metoden den mest specialiserade metoden körs
                //Polymorfismens andra regel
                Console.WriteLine(vehicle.Drive(1));

                //Returnerar null om casten ej lyckas
                Moped moped3 = vehicle as Moped;

                //?. är en null check om moped3 är null avbryts executeringen och DoSound() anroppas aldrig
                Console.WriteLine(moped3?.DoSound());

                //Om vehicle är en Moped casta till en Moped och tilldela variabeln moped2 annars false
                if (vehicle is Moped moped2)
                {
                    //moped2 har en DoSound() metod
                    Console.WriteLine(moped2.DoSound());

                    //Unsafe cast generar en exeption om den misslyckas
                    Moped moped = (Moped)vehicle;
                    Console.WriteLine(moped.DoSound());
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            //Class2 c3 = new Class3
            //{
            //    Name = "Kalle",
            //    Age = 45,
            //    Adress = "Blåbärsvägen 3"
            //};

            List <Vehicle> vehicles = new List <Vehicle>()
            {
                new FuelVehicle("ABC123", 100),
                new FuelCar("AAA000", 150)
                {
                    FuelLevel = 100
                },
                new Moped("BBB111"),
                new Vehicle("CCC222")
            };

            foreach (var vehicle in vehicles)
            {
                Console.WriteLine(vehicle.Drive(1));

                Moped moped3 = vehicle as Moped;
                Console.WriteLine(moped3?.DoSound());

                if (vehicle is Moped moped2)
                {
                    Console.WriteLine(moped2.DoSound());
                    Moped moped = (Moped)vehicle;
                    Console.WriteLine(moped.DoSound());
                }
            }



            Console.ReadLine();
        }