Подскажите как вывести верхний элемент стека в виде строкового представления - C#

Узнай цену своей работы

Формулировка задачи:

Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace FunWithGenericCollection
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. UseGenericList();
  13. }
  14. static void UseGenericList()
  15. {
  16. Stack<Person> stackOfPeople = new Stack<Person>();
  17. stackOfPeople.Push(new Person { FirstName = "Homer", LastName = "Simpson", Age = 47 });
  18. stackOfPeople.Push(new Person { FirstName = "Marge", LastName = "Simpson", Age = 45 });
  19. stackOfPeople.Push(new Person { FirstName = "Bart", LastName = "Simpson", Age = 9 });
  20. stackOfPeople.Push(new Person { FirstName = "Lisa", LastName = "Simpson", Age = 8 });
  21. Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
  22. Console.WriteLine("Popped off {0}", stackOfPeople.Pop());
  23. Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
  24. Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
  25. Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
  26. Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
  27. try
  28. {
  29. Console.WriteLine($"\nnFirst person is: {stackOfPeople.Peek()}");
  30. Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
  31. Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
  32. Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
  33. }
  34. catch (InvalidOperationException ex)
  35. {
  36. Console.WriteLine($"\nError! {ex.Message}");
  37. }
  38. Console.Read();
  39. }
  40. }
  41. class Person
  42. {
  43. public int Age { get; set; }
  44. public string FirstName { get; set; }
  45. public string LastName { get; set; }
  46. }
  47. }
Вывод : First person is: FunWithGenericCollection.Person Popped off FunWithGenericCollection.Person First person is: FunWithGenericCollection.Person Popped off FunWithGenericCollection.Person First person is: FunWithGenericCollection.Person Popped off FunWithGenericCollection.Person nFirst person is: FunWithGenericCollection.Person Popped off FunWithGenericCollection.Person Error! Стек пуст.

Решение задачи: «Подскажите как вывести верхний элемент стека в виде строкового представления»

textual
Листинг программы
  1. public override string ToString()
  2. {
  3.     return $"{Age}, {FirstName}, {LastName}";
  4. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.867 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы