C# 如何使用用户输入将对象添加到现有对象列表

C# How can I add objects to existing list of objects with user input

我在列表 (BLibShelf) 中有来自“书”class 的这些对象,但想开始使用控制台输入将它们添加到此类列表中

namespace Library
{
    class Program
    {
        static void Main(string[] args)
        {
            Book book1 = new Book("book one", "Author one", 900, 35, 16);
            Book book2 = new Book("book two", "Author two", 240, 42, 8);
            Book book3 = new Book("book three", "Author three", 700, 23, 8);
         
            List<Book> BLibShelf = new List<Book>();
            BLibShelf.AddRange(new List<Book>() { book1, book2, book3, book4, book5, book6, book7,  book8 });

 Console.ReadLine();

        }
       
    }

这是我的书class

class Book
    {
        public string title;
        public string author;
        public int pages;
        public int Libcopies;
        public int BCopies;
                     
        public Book(string nTitle, string nAuthor, int nPages, int nLcopies, int nBcopies)
        {
            title = nTitle;
            author = nAuthor;
            pages = nPages;
            Libcopies = nLcopies;
            BCopies = nBcopies;
        }

        

我写了一个简单的demo,支持输入新书名和页码

您可以自己实现其他字段,希望对您有所帮助:)

    class Program
    {
        static void Main(string[] args)
        {
            Book book1 = new Book("book one", "Author one", 900, 35, 16);
            Book book2 = new Book("book two", "Author two", 240, 42, 8);
            Book book3 = new Book("book three", "Author three", 700, 23, 8);

            List<Book> BLibShelf = new List<Book>();
            BLibShelf.AddRange(new List<Book>() { book1, book2, book3 });

            Console.WriteLine("Total " + BLibShelf.Count + " books");

            Console.WriteLine("Please input the new book Title:");
            var title = Console.ReadLine();

            Console.WriteLine("Please input the new book Pages(integer):");
            var pages = int.Parse(Console.ReadLine());
            var newBook = new Book(title, string.Empty, pages, 0, 0);
            BLibShelf.Add(newBook);

            Console.WriteLine("Total " + BLibShelf.Count + " books");
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }