示例#1
0
        static void Main(string[] args)
        {
            Human oHuman1   = new Human();
            Human oHuman2   = new Human("Angelina", "Draguts", 21);
            Human refHuman2 = oHuman2 as Human;

            Car oCar1   = new Car();
            Car oCar2   = new Car("Volvo XC90", 220, "Germany", 80000, true);
            Car refCar2 = oCar2 as Car;


            Transformer oTransfromer1   = new Transformer();
            Transformer oTransfromer2   = new Transformer(true, 4);
            Transformer refTransfromer2 = oTransfromer2 as Transformer;

            Printer oPrinter = new Printer();

            Object[] arr = { refHuman2, refCar2, refTransfromer2 };

            foreach (object element in arr)
            {
                Console.WriteLine(oPrinter.IAmPrinting(element) + "\n_____________________________\n");
            }

            Console.ReadKey();
        }
示例#2
0
文件: Program.cs 项目: Allemel/123
        static void Main(string[] args)
        {
            Tovar  tov     = new Tovar();
            Scaner scan    = new Scaner();
            Komp   kompich = new Komp();
            IAlla  scaner  = new Scaner();
            IAlla  tovar   = new Tovar();
            IAlla  kom     = new Komp();
            var    fds     = scaner as Scaner;

            if (fds != null)
            {
                Console.WriteLine(fds.Dod());
            }
            Printer pri = new Printer();

            IAlla[] allmass = new IAlla[3];
            allmass[0] = scaner;
            allmass[1] = tovar;
            allmass[2] = kom;
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(pri.IAmPrinting(allmass[i]));
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            #region task4
            Console.WriteLine("\nTask 4");
            Circle circle1 = new Circle("yellow", 3);
            circle1.input(3);
            circle1.resizing();
            circle1.input(-3);
            circle1.resizing();
            #endregion

            #region task5
            Console.WriteLine("\nTask 5");
            Rectangle rect1 = new Rectangle("red", 5, 8);
            if (rect1 is Figure)
            {
                Console.WriteLine("Объект rect1 принадлежит классу Figure.");
            }
            else
            {
                Console.WriteLine("Объект rect1 не принадлежит классу Figure.");
            }

            if (rect1 is IControl)
            {
                Console.WriteLine("Объект rect1 принадлежит интерфейсу IControl.");
            }
            else
            {
                Console.WriteLine("Объект rect1 не принадлежит интерфейсу IControl.");
            }

            Button btn1 = new Button(true);
            if (btn1 is ControlElement)
            {
                ControlElement ce1 = btn1 as ControlElement;
                ce1.Switch();
                ce1.Status();
            }
            #endregion

            #region task6
            Console.WriteLine("\nTask 6");
            Console.WriteLine(circle1.ToString());
            #endregion

            #region task7
            Console.WriteLine("\nTask 7");

            Printer  printer = new Printer();
            Figure[] figures = new Figure[] { circle1, rect1 };
            foreach (var item in figures)
            {
                printer.IAmPrinting(item);
            }
            #endregion
        }
示例#4
0
        static void Main(string[] args)
        {
            PrintEdition PrintEdition1    = new PrintEdition("Книга");
            Book         Book             = new Book("Немного ненависти", "русский", 2019, 702);
            Author       AuthorOfBook     = new Author("Джо", "Аберкромби");
            Publishing   PublishingOfBook = new Publishing("FanZone");

            PrintEdition PrintEdition2       = new PrintEdition("Журнал");
            Magazin      Magazin             = new Magazin("Мурзилка", "русский", 2019, 193);
            Author       AuthorOfMagazin     = new Author("Виктория", "Абрамова");
            Publishing   PublishingOfMagazin = new Publishing("Детский мир");

            PrintEdition PrintEdition3        = new PrintEdition("Учебник");
            Textbook     Textbook             = new Textbook("EnglishInfo", "английский", 2020, 408);
            Author       AuthorOfTextbook     = new Author("Ellen", "Page");
            Publishing   PublishingOаTextbook = new Publishing("Express Publishin");

            Printer Printer = new Printer();

            Object[] mas = new Object[] { PrintEdition1, Book, AuthorOfBook, PublishingOfBook, PrintEdition2, Magazin, AuthorOfMagazin, PublishingOfMagazin, PrintEdition3, Textbook, AuthorOfTextbook, PublishingOаTextbook };

            for (int i = 0; i < mas.Length; i++)
            {
                Console.WriteLine(Printer.IAmPrinting(mas[i]));
                Console.WriteLine();
            }
            AuthorOfTextbook.Show();
            PublishingOаTextbook.Show();

            Console.WriteLine();
            Console.Write(AuthorOfBook.Name + " " + AuthorOfBook.Surname);
            if (AuthorOfBook is IShow1)
            {
                Console.WriteLine("-- очень известный автор");
            }
            else
            {
                Console.WriteLine("-- начинающий автор");
            }

            Console.WriteLine();
            PrintEdition1.Equals(Magazin);
            Console.ReadKey();
        }
示例#5
0
        /// <summary>
        /// Проверка метода <c><see cref="Printer.IAmPrinting(Plant)"/></c>
        /// </summary>
        public static void CheckMethod()
        {
            Shrub shrub = new Shrub();

            shrub.Name = "Куст";
            shrub.Size = 50;

            Printer.IAmPrinting(shrub);

            Flower flower = new Flower();

            flower.Name = "Василек";
            flower.Size = 7;

            Printer.IAmPrinting(flower);

            Rose rose = new Rose();

            rose.Name  = "Французская роза";
            rose.Size  = 10.5;
            rose.Color = (Colors)1;

            Printer.IAmPrinting(rose);
        }
示例#6
0
        static void Main(string[] args)
        {
            Human creator = new Human("Danil", 1, 18, 4, 1, 2001, 130);

            string[] someargs  = { "diff args", "something" };
            Button   butStart  = new Button(false, 10, 3, "Start", "romb", "green", "solid", 1);
            Button   butExit   = new Button(false, 10, 2, "Exit", "circle", "black", "solid", 10);
            Button   butNext   = new Button(true, 15, 4, "Next", "Triangle", "gradient", "not", 0);
            IButton  butIHello = new Button(false, 1, 1, "Hello", "square", "not", "not", 0);
            Decor    decor;

            decor = butExit as Decor;
            Console.WriteLine("\t Part 1");
            Console.WriteLine("________________________________________________");
            Console.WriteLine("================================================");
            Console.WriteLine("Вывод созданных объектов");
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(butStart.ToString());
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(butExit.ToString());
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(butNext.ToString());
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(butIHello.ToString());
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(decor.ToString());
            Console.WriteLine("================================================");
            Console.WriteLine("\n================================================");
            Console.WriteLine("Абстрактный метод vs Интерфейсовый метод");
            Console.WriteLine("------------------------------------------------");
            butExit.onClickRightButton(creator, someargs);
            Console.WriteLine("------------------------------------------------");
            butIHello.onClickRightButton(creator, someargs);
            Console.WriteLine("================================================");
            Console.WriteLine("\n================================================");
            IButton buttonInterface;

            buttonInterface = butStart as IButton;
            Console.WriteLine("Что то что есть только в интерфейсе");
            Console.WriteLine("------------------------------------------------");
            buttonInterface.somethingOnlyInInterface();
            buttonInterface.GetMainInfo();
            butIHello.somethingOnlyInInterface();
            butIHello.GetMainInfo();
            Console.WriteLine("================================================");

            Console.WriteLine("\n\t Part 2");
            Console.WriteLine("________________________________________________");
            Console.WriteLine("================================================");
            Console.WriteLine("Printer");
            Console.WriteLine("------------------------------------------------");
            IKristian    manager1 = new Manager();
            INotKristian manager2 = new Manager();
            Printer      printer  = new Printer();
            Printer      printerA = new A();

            Console.WriteLine(printer.IAmPrinting(manager1));
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(printerA.IAmPrinting(manager1));
            Console.WriteLine("------------------------------------------------");
            manager1.WriteManagedKristian();
            manager2.WriteManagedNoKristian();
            Console.WriteLine("================================================");
            Console.WriteLine("\n================================================");
            Console.WriteLine("Window");
            Console.WriteLine("------------------------------------------------");
            Window mywindow = new Window("ARCTICA", 100, 20);

            mywindow.ToString();
            mywindow.Add(butStart);
            mywindow.Add(butExit);
            mywindow.Add(butNext);
            mywindow.ToConsole();

            Console.WriteLine(mywindow.ListofElements[0].GetType());
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine(Window_controler.FreeSpace(mywindow));
            Console.WriteLine("------------------------------------------------");
            Console.WriteLine("Поиск по имени : (Next)");
            Console.WriteLine(Window_controler.FindButton("Next", mywindow).ToString());
            Console.WriteLine("------------------------------------------------");

            try
            {
                Button buttonExeption = new Button(false, 10, -5, "Name", "romb", "green", "solid", 1); // отрицательный размер
            }
            catch (CreatingClassException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
                Console.WriteLine("Класс который вызвал ошибку: " + exception.Source);
                Console.WriteLine("Тип поля которое вызвало ошибку: " + exception.WhatData);
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                Button buttonExeption = new Button(false, 10, 3, "", "romb", "green", "solid", 1); // нет имени
            }
            catch (CreatingClassException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
                Console.WriteLine("Класс который вызвал ошибку: " + exception.Source);
                Console.WriteLine("Тип поля которое вызвало ошибку: " + exception.WhatData);
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                Button buttonExeption = new Button(false, 10, 3, "Ex", "", "green", "solid", 1); // нет формы
            }
            catch (CreatingClassException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
                Console.WriteLine("Класс который вызвал ошибку: " + exception.Source);
                Console.WriteLine("Тип поля которое вызвало ошибку: " + exception.WhatData);
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                IButton[] arr  = { butIHello, buttonInterface };
                int[]     arr1 = { 1, 2, 3 };
                int       i    = 8;
                if (i > arr1.Length || i < 0)
                {
                    throw new OutofRangeException(i, arr1.Length);
                }
                else
                {
                    Console.WriteLine(arr[i].ToString());
                }
            }
            catch (OutofRangeException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
                Console.WriteLine("Вышло за пределы типа на значение: " + exception.OutValue.ToString());
                Console.WriteLine("Вышло за пределы массива на значение: " + exception.OutRange.ToString());
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                long i = 12;
                long x = i + int.MaxValue;
                if (x > int.MaxValue || x < int.MinValue)
                {
                    throw new OutofRangeException(x);
                }
            }
            catch (OutofRangeException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
                Console.WriteLine("Вышло за пределы типа на значение: " + exception.OutValue.ToString());
                Console.WriteLine("Вышло за пределы массива на значение: " + exception.OutRange.ToString());
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                int x      = 10;
                int y      = 0;
                int result = (y == 0) ? throw new ArithmeticException() : x / y;
            }
            catch (ArithmeticException exception)
            {
                Console.WriteLine(exception.GetMessage);
                Console.WriteLine(exception.StackTrace);
            }
            Console.WriteLine("------------------------------------------------");
            try
            {
                int x = 0;
                int y = 10 / x;
            }
            catch
            {
                Console.WriteLine("Вызвано исключение");
            }
            finally
            {
                Console.WriteLine("Обработка ошибок завершена");
            }
            Console.WriteLine("------------------------------------------------");
            int[] aa = null;
            Debug.Assert(aa != null, "Values array cannot be null");

            Console.ReadKey();
        }
示例#7
0
        static void Main(string[] args)
        {
            try
            {
                TransportAgency Agent  = new TransportAgency();
                Printer         Print  = new Printer();
                Train           poezd1 = new Train(123, 8578947, 89);
                poezd1.toString();
                Train poezd2 = new Train(678, 8745683, 100);
                Train poezd3 = new Train(987, 098009, 85);
                Train poezd4 = new Train(897, 8575, 80);
                Vagon vagon1 = new Vagon(123, 2354, 89, 6);
                vagon1.toString();
                Express express1 = new Express(124, 9465464, 89, 100);
                express1.toString();
                Car car1 = new Car(456, 34534, 90, "Volvo", 10);
                car1.toString();
                Car car2 = new Car(897, 65646, 80, "Opel", 5);
                car1.toString();
                Engine engine1 = new Engine(456, 2343, 45, "Volvo", 10, 100);
                engine1.toString();
                Console.WriteLine();


                Transport[] arr = new Transport[2];
                arr[0] = vagon1;
                arr[1] = car1;
                Print.IAmPrinting(arr[0]);
                Print.IAmPrinting(arr[1]);
                Console.WriteLine();

                Part party = new Part();
                party.part2();
                party.part1();
                Console.WriteLine();
                Console.WriteLine(car1 is Transport);
                Console.WriteLine(car1 is Int32);
                Transport obj1 = express1 as Transport;
                if (obj1 != null)
                {
                    Console.WriteLine("Преобразование удалось");
                }
                else
                {
                    throw new Errors("Это фиаско, братан");
                }


                int en = (int)Enum.e;
                Console.WriteLine("enum " + en);
                Console.WriteLine();


                Agent.Add(poezd1);
                Agent.Add(car1);
                Agent.Add(express1);
                Agent.Add(vagon1);
                Agent.Add(engine1);

                Agent.Stoimoct();
                Agent.FindSpeed();
                Console.WriteLine();



                Car[] ar = new Car[2];
                ar[0] = car1;
                ar[1] = car2;
                Array.Sort(ar);
                foreach (Car p in ar)
                {
                    p.toString();
                }

                int[] aa = null;
                Debug.Assert(aa != null, "Что-то не так");
                Structura struct1 = new Structura {
                };
                struct1.name = "new";
                struct1.size = 3;
                Console.WriteLine(struct1.size);

                CollectionType <double> i = new CollectionType <double>();
                i.array = new List <double>()
                {
                    1, 3, 5
                };
                Console.WriteLine("Массив 1:\n");
                i.View(i);
                Console.WriteLine("В массив1 добавим 5:\n");
                i.Add(i, 5);
                Console.WriteLine("Массив1:\n");
                i.View(i);
                Console.WriteLine("Из массива 1 удалим 1:\n");
                i.Del(i, 1);
                Console.WriteLine("Массив 1:\n");
                i.View(i);
                Console.WriteLine();
                Console.WriteLine();


                CollectionType <Train> k = new CollectionType <Train>();
                k.array = new List <Train>(4)
                {
                    poezd1, poezd2, poezd3
                };
                Console.WriteLine("Массив2:\n");
                k.View(k);
                Console.WriteLine("В массив2 добавим еще поезд:\n");
                k.Add(k, poezd4);
                Console.WriteLine("Массив2:\n");
                k.View(k);
                for (int l = 0; l < 4; l++)
                {
                    k[l].toString();
                }
                Console.WriteLine("Из массива 2 удалим поезд:\n");
                k.Del(k, poezd4);
                Console.WriteLine("Массив 2:\n");
                k.View(k);
                for (int l = 0; l < 4; l++)
                {
                    k[l].toString();
                }
                Console.WriteLine();
                Console.WriteLine();
            }
            catch (Error e)
            {
                Console.WriteLine("Используется Error");
            }

            catch (Errorin e)
            {
                Console.WriteLine("Используется Errorin");
            }
            catch (Errors e)
            {
                Console.WriteLine("Используется Errors");
            }
            catch (Exception e)
            {
                Console.WriteLine("Используется Exception");
            }
            finally
            {
                Console.WriteLine("The end");
                Console.ReadKey();
            }
        }
示例#8
0
        static void Main(string[] args)
        {
            #region task_5
            Engine engine = new Engine("diesel", 167, 7.1, 2.4);
            Car    car    = new Car(4, 1222, 3.5, 210, 2004, "Volvo v60", engine);
            car.Info();

            if (car is Transport)
            {
                Console.WriteLine("Объект car принадлежит классу Transport.\n");
            }
            else
            {
                Console.WriteLine("Объект car не принадлежит классу Transport.\n");
            }

            Human human = new Human("Grisha", "Bulgak", 2002);
            human.Info();
            Engine      engine1     = new Engine("diesel", 167, 7.1, 2.4);
            Transformer transformer = new Transformer(4, 1700, 3.6, 250, 2016, "Range Rover", engine1);
            transformer.Info();

            if (transformer is Transport)
            {
                Console.WriteLine("Объект transformer принадлежит классу Transport.\n");
            }
            else
            {
                Console.WriteLine("Объект transformer не принадлежит классу Transport.\n");
            }

            if (human is Driving)
            {
                Console.WriteLine("Объект human принадлежит классу Driving.\n");
            }
            else
            {
                Console.WriteLine("Объект human не принадлежит классу Driving.\n");
            }

            Transport car_copy = car as Transport;
            Console.WriteLine(car_copy.ToString());
            #endregion

            #region task_6
            Car         car1         = new Car(4, 1222, 3.5, 210, 2004, "Volvo v60", new Engine("petrol", 320, 8, 3.2));
            Transformer transformer1 = new Transformer(4, 1222, 3.1, 230, 2018, "Volvo v40", new Engine("petrol", 320, 8.6, 3.0));
            Printer     printer      = new Printer();
            ISmart      transformer3 = new Transformer(4, 1400, 3.4, 214, 2013, "Toyota Corolla", new Engine("petrol", 190, 7, 1.8));
            transformer3.Info();
            Transport[] transports = new Transport[] { car1, transformer1 };
            Console.WriteLine();
            foreach (var item in transports)
            {
                printer.IAmPrinting(item);
                Console.WriteLine();
            }
            #endregion

            Troop troop1 = new Troop(TroopType.Human, 200, 2002, "medium");
            Troop troop2 = new Troop(TroopType.Transformer, 300, 2014, "medium");
            Troop troop3 = new Troop(TroopType.Transformer, 1000, 2019, "maximal");
            Troop troop4 = new Troop(TroopType.Human, 100, 1999, "minimal");
            Army  army   = new Army(troop1, troop2, troop3, troop4);
            army.Print();
            army.DateFind();
            army.TransformerPowerFind();
            army.Count();
        }
示例#9
0
        static void Main(string[] args)
        {
            /**
             * Построим следующую иерархию.
             * Класс ДОКУМЕНТ сделаем абстрактным, который будет описывать
             * свойства присущие документам. Он будет родителем для классов
             * НАКЛАДНАЯ, КВИТАНЦИЯ т.к эти классы являются документами.
             * Класс ЧЕК является запечатанным классом, можем только использовать его.
             * В нем будет хранится общая стоимость услуг/товаров из классов НАКЛАДНАЯ КВИТАНЦИЯ
             *
             * Класс ДАТА, будет запечатанным классом, который нельзя наследовать,
             * будет хранить в себе время и дату, которое зададим для его объектов.
             * Также перегрузим для него все методы object. Для него создаим интерфейс
             * который будет определелять члены класса для класса ДАТА.
             *
             * Класс ОРГАНИЗАЦИЯ, сделаем абстрактным.
             * Будем наследовать его для каждого нового класса придуманной организации.
             *
             */

            /**
             * Можно воспользоваться полиморфизмом, и передавать потомков класса Organization
             * вторым параметром. Создадим две организации, МинскГорЭлектро и продуктовый магазин.
             */

            // Создадим тестовые объекты. Квитанции и накладной.
            Receipt minskGorElRec = new Receipt(new Date(5, 32, 15, 2020, "December"),
                                                new MinskEnergyEstablishment());

            // Заполним словарь услуга-стоимость
            minskGorElRec.ServicePricePair.Add("Электричество", 1230);
            minskGorElRec.ServicePricePair.Add("Отопление", 3434);
            minskGorElRec.ServicePricePair.Add("Газ", 124);
            minskGorElRec.ServicePricePair.Add("ЖКХ", 534);
            minskGorElRec.CalculateFinalPrice(); // Посчитаем общую стоимость услуг и занесем в чек

            ConsignmentNote minskGorElCN = new ConsignmentNote(new Date(5, 32, 15, 2020, "December"),
                                                               new MinskEnergyEstablishment());

            // Заполним словарь товар-стоимость
            minskGorElCN.GoodsPricePair.Add("Счетчик \"Заря\"", 1543.23);
            minskGorElCN.GoodsPricePair.Add("Счетчик \"M23\"", 2543.23);
            minskGorElCN.GoodsPricePair.Add("Счетчик \"Электрон\"", 543.23);
            minskGorElCN.CalculateFinalPrice();
            Console.WriteLine(new MinskEnergyEstablishment().GetFullInfo() + "\n");
            // Выведем для МинскГорЭлектро список накладной.
            foreach (var good in minskGorElCN.GoodsPricePair)
            {
                Console.WriteLine($"Наименование товара: {good.Key} | Цена: {good.Value}");
            }
            Console.WriteLine("\n\n");
            ///////////////////////////////////////////////////////////////////////////
            // Создадим тестовые объекты. Квитанции и накладной.
            Receipt freshMarketRec = new Receipt(new Date(5, 32, 15, 2020, "December"),
                                                 new FreshMarket());

            // Заполним словарь услуга-стоимость
            freshMarketRec.ServicePricePair.Add("Доставка продуктов", 34230);
            freshMarketRec.ServicePricePair.Add("Накладные расходы", 342334);
            freshMarketRec.ServicePricePair.Add("Логистика", 1234124);
            freshMarketRec.ServicePricePair.Add("Уборка", 53434);
            freshMarketRec.CalculateFinalPrice(); // Посчитаем общую стоимость услуг и занесем в чек

            ConsignmentNote freshMarketCN = new ConsignmentNote(new Date(5, 32, 15, 2020, "December"),
                                                                new FreshMarket());

            // Заполним словарь товар-стоимость
            freshMarketCN.GoodsPricePair.Add("Фрукты", 154334.23);
            freshMarketCN.GoodsPricePair.Add("Вода", 2543343.23);
            freshMarketCN.GoodsPricePair.Add("Овощи", 54433.23);
            freshMarketCN.CalculateFinalPrice();
            Console.WriteLine(new FreshMarket().GetFullInfo() + "\n");
            // Выведем для продуктового магазина список накладной.
            foreach (var good in freshMarketCN.GoodsPricePair)
            {
                Console.WriteLine($"Наименование товара: {good.Key} | Цена: {good.Value}");
            }
            Console.WriteLine("\n\n");

            // Создаем список из документов разных организаций.
            List <Document> documents = new List <Document>()
            {
                minskGorElRec,
                minskGorElCN,
                freshMarketRec,
                freshMarketCN
            };
            // Создаем объект принтер.
            Printer printer = new Printer();

            // Последовательно перебираем все объекты и вызываем их перегрузку tostring
            foreach (var doc in documents)
            {
                printer.IAmPrinting(doc);
            }
            Console.ReadKey();
        }
示例#10
0
        static void Main(string[] args)
        {
            var cake   = new Cake("Tiramisu", 5, 5, 1000, 1000, 20, 100, 5);
            var sweets = new Sweets("Toffee", 150, 3, 1500, 500, 10, 50);
            var flower = new Flower("Tulip", 1, 30, "purple", 5);
            var watch  = new Watch("Datejust", 12, 5495, "Rolex", 1, 200);

            Console.WriteLine(cake);
            cake.Add(10);
            Console.WriteLine(cake);
            Console.WriteLine(watch);
            Console.WriteLine();

            watch.Method1(); // Goods
            watch.Method2();

            Console.WriteLine();

            cake.Method1(); // Product
            cake.Method2();



            Console.WriteLine();

            Goods goods = cake as Goods;

            goods.Method1();
            goods.Method2();

            Console.WriteLine();

            IGoods igoods = cake as IGoods;

            igoods.Method1();
            // виртуальгный метод низя

            Console.WriteLine();

            object obj = (object)flower;

            Console.WriteLine("flower is " + (obj is Flower ? "Flower" : "not Flower"));
            Console.WriteLine("flower is " + (obj is Goods ? "Goods" : "not Goods"));
            Console.WriteLine("flower is " + (obj is Product ? "Product" : "not Product"));
            Console.WriteLine("flower is " + (obj is IGoods ? "IGoods" : "not IGoods"));

            Console.WriteLine();


            Console.WriteLine("flower is " + ((obj as Flower) != null ? "Flower" : "not Flower"));
            Console.WriteLine("flower is " + ((obj as Goods) != null ? "Goods" : "not Goods"));
            Console.WriteLine("flower is " + ((obj as Product) != null ? "Product" : "not Product"));
            Console.WriteLine("flower is " + (obj is IGoods ? "IGoods" : "not IGoods"));

            Console.WriteLine();

            object[] arr = { cake, sweets, flower, watch };
            foreach (object o in arr)
            {
                Printer.IAmPrinting(o as Goods);
            }

            Console.WriteLine("\n========================\n");
            // И тут внезапно 6 лаба

            Gift gift = new Gift();

            gift.Add(cake);
            gift.Add(flower);
            gift.Add(watch);
            gift.Add(sweets);

            Console.WriteLine(gift);

            Console.WriteLine(GiftController.GetMinMass(gift));
            Console.WriteLine(GiftController.GetSumPrice(gift));
            GiftController.SortName(gift);
            Console.WriteLine(gift);

            var gift2 = new Gift();

            string folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(folder);
            directoryInfo = System.IO.Directory.GetParent(directoryInfo.FullName);
            directoryInfo = System.IO.Directory.GetParent(directoryInfo.FullName);
            folder        = directoryInfo.FullName;
            Console.WriteLine(folder);

            GiftController.ToFile(gift, folder + "\\Gift.txt");
            GiftController.FromFile(out gift2, folder + "\\Gift.txt");
            Console.WriteLine(gift2);

            GiftController.ToJson(gift, folder + "\\Gift.json");
            //GiftController.FromJson(out gift2, "e:\\ООП\\Лабы\\Lab5\\Gift.json");


            Console.WriteLine("\n========================\n");
            // И тут внезапно 7 лаба

            // flower amount = 1;
            try
            {
                flower.Remove(2);
            }
            catch (NegativeAmountException ex)
            {
                Console.WriteLine(ex);
                gift.logger.Add(ex);
            }

            try
            {
                flower.Sell(1);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex);
                gift.logger.Add(ex);
            }

            try
            {
                flower.Add(-2);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex);
                gift.logger.Add(ex);
            }

            try
            {
                Console.WriteLine("\n=====\n\tBeginning of the Gift");
                var emptygift = new Gift();
                emptygift.print();
            }
            catch (EmptyListException ex)
            {
                Console.WriteLine(ex);
                gift.logger.Add(ex);
            }
            finally
            {
                Console.WriteLine("\tEnding of the Gift\n=====\n");
            }
            try
            {
                int b = 0;
                int a = 10 / b;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                gift.logger.Add(ex);
            }

            Console.WriteLine("\n=========\nLog\n=========\n");
            Console.WriteLine(gift.logger);

            gift.logger.ToFile(folder + "\\log.txt");

            // И тут внезапно 8 лаба
            Console.WriteLine();
            Console.WriteLine();

            var intList = new CList <int>();

            intList.Add(1);
            intList.Add(2);
            intList.Add(3);
            intList.Print();
            Console.WriteLine();

            var doubleList = new CList <double>();

            doubleList.Add(1.1);
            doubleList.Add(2);
            doubleList.Add(3.3);
            doubleList.Print();
            Console.WriteLine();

            var goodsList = new CList <Goods>();

            goodsList.Add(flower);
            goodsList.Add(watch);
            goodsList.Add(sweets);
            goodsList.Add(cake);
            goodsList.Print();
            Console.WriteLine();

            try // Самый неочевидный способ очистки листа invented
            {
                for (var i = 0; i < 100; i++)
                {
                    intList--;
                }
                //intList--;
                //intList--;
                //intList--;
            } catch (NegativeAmountException ex)
            {
                Console.WriteLine("List empty");
            }
            finally
            {
                intList.Add(1);
                intList.Add(1);
                intList.Add(1);
                intList.Add(1);
                intList.Add(1);
                intList.Print();
            }
            intList.ToFile(folder + "\\intlist.txt");
            intList.ToJson(folder + "\\intlist.json");

            intList.toXML(folder + "\\xmllist.xml");
        }
示例#11
0
        static void Main(string[] args)
        {
            Sea sea1 = new Sea("Baltic");
            Sea sea2 = new Sea("Nordic");

            Sea[] seas1  = { sea1, sea2 };
            Ocean ocean1 = new Ocean("Atlantic", seas1);

            Sea sea3 = new Sea("White");
            Sea sea4 = new Sea("Norwegian");

            Sea[] seas2  = { sea3, sea4 };
            Ocean ocean2 = new Ocean("Arctic", seas2);

            Ocean[] oceans = { ocean1, ocean2 };

            Water water = new Water(oceans, "");

            Country country1 = new Country("England");
            Country country2 = new Country("Germany");

            Country[] countrys1  = { country1, country2 };
            Continent continent1 = new Continent("Europe", countrys1);

            Country country3 = new Country("USA");
            Country country4 = new Country("Canada");

            Country[] countrys2  = { country3, country4 };
            Continent continent2 = new Continent("North America", countrys2);

            Continent[] continents = { continent1, continent2 };

            Island island1 = new Island("Sumatra");
            Island island2 = new Island("Schpicbergen");
            Island island3 = new Island("Corsika");

            Island[] islands = { island1, island2, island3 };

            Land land = new Land(continents, islands, "Earth");

            Planet Earth = new Planet(water, land);

            Realization real = new Realization();

            real.WriteAbstract();
            real.WriteInterfaceMethod();

            Interface1 i1 = new Planet();

            i1.WriteInterfaceMethod();
            Interface2 i2 = new Planet();

            i2.WriteInterfaceMethod();

            AbstractClass a1 = new Realization();

            a1.WriteInterfaceMethod();

            ((Interface1)Earth).WriteInterfaceMethod();
            ((Interface2)Earth).WriteInterfaceMethod();

            AbstractClass abstr1 = real as Realization;

            abstr1.WriteInterfaceMethod();
            Interface1 i11 = Earth as Planet;
            Interface2 i22 = Earth as Planet;

            i11.WriteInterfaceMethod();
            i22.WriteInterfaceMethod();

            Console.WriteLine(Printer.IAmPrinting(i1));
            Console.WriteLine(Printer.IAmPrinting(i11));
        }