Вывод в консоль без множества операторов ветвления - C#
Формулировка задачи:
Добрый день, подскажите как можно реализовать вывод в консоль без множества операторов ветвления. Какие шаблоны проектирования лучше использовать,что бы избежать чрезмерного количества if. Каким образом можно убрать зависимость и повысить гибкость кода? Спасибо.
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- class Machine
- {
- private Dictionary<int, string> _cars;
- public Machine(Dictionary<int,string> Cars)
- {
- _cars = Cars;
- }
- public void Show()
- {
- foreach (KeyValuePair<int, string> CarItem in _cars)
- {
- if (CarItem.Key == 1)
- {
- Console.WriteLine("{0}, {1}, 100$", CarItem.Key, CarItem.Value);
- }
- if (CarItem.Key == 2)
- {
- Console.WriteLine("{0}, {1}, 300$", CarItem.Key, CarItem.Value);
- }
- if (CarItem.Key == 3)
- {
- Console.WriteLine("{0}, {1}, 500$", CarItem.Key, CarItem.Value);
- }
- if (CarItem.Key == 4)
- {
- Console.WriteLine("{0}, {1}, 900$", CarItem.Key, CarItem.Value);
- }
- if (CarItem.Key == 5)
- {
- Console.WriteLine("{0}, {1}, 1$", CarItem.Key, CarItem.Value);
- }
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Dictionary<int, string> CarDictionary = new Dictionary<int, string>();
- CarDictionary.Add(1,"Monocycl");
- CarDictionary.Add(2,"Bicycle");
- CarDictionary.Add(3,"Bike");
- CarDictionary.Add(4,"Car");
- CarDictionary.Add(5,"Lada Kalina");
- Machine Test = new Machine(CarDictionary);
- Test.Show();
- }
- }
- }
Решение задачи: «Вывод в консоль без множества операторов ветвления»
textual
Листинг программы
- public void Show()
- {
- int i = 0;
- foreach (Car car in _cars)
- {
- Console.WriteLine("{0}\t{1}\t{2}", ++i, car.Name, car.Price);
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д