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

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

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FunWithGenericCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            UseGenericList();
        }
 
        static void UseGenericList()
        {
            Stack<Person> stackOfPeople = new Stack<Person>();
            stackOfPeople.Push(new Person { FirstName = "Homer", LastName = "Simpson", Age = 47 });
            stackOfPeople.Push(new Person { FirstName = "Marge", LastName = "Simpson", Age = 45 });
            stackOfPeople.Push(new Person { FirstName = "Bart", LastName = "Simpson", Age = 9 });
            stackOfPeople.Push(new Person { FirstName = "Lisa", LastName = "Simpson", Age = 8 });
 
            Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
            Console.WriteLine("Popped off {0}", stackOfPeople.Pop());
 
            Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
            Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
 
            Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
            Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
 
            try
            {
                Console.WriteLine($"\nnFirst person is: {stackOfPeople.Peek()}");
                Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
                Console.WriteLine($"First person is: {stackOfPeople.Peek()}");
                Console.WriteLine($"Popped off {stackOfPeople.Pop()}");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine($"\nError! {ex.Message}");
            }
 
            Console.Read();
        }
    }
 
    class Person
    {
        public int Age { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
Вывод : 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
Листинг программы
public override string ToString()
{
    return $"{Age}, {FirstName}, {LastName}";
}

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

15   голосов , оценка 3.867 из 5
Похожие ответы