试图制作一个书架式控制台应用程序,但列表有些麻烦. (C#初学者) [英] Trying to make a bookshelf console application but having some trouble with lists. (C# Beginner)

查看:53
本文介绍了试图制作一个书架式控制台应用程序,但列表有些麻烦. (C#初学者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个书架应用程序,但是在使用列表时遇到了麻烦.我希望在用户指定要添加多少本书之后,for循环有望以指定的数量重复该方法.

I am trying to make a bookshelf application but I am having trouble with using lists. What I am hoping for is after the user specifies how many books they would like to add, the for-loop should hopefully repeat the method in the specified amount.

第一次运行该方法后,添加的更多标题将添加到列表中.

After the first run through of the method, the more titles added will add onto the list.

    class Shelf
{
    public void Program()
    {
        Book book = new Book();

        int bookAmount;

        Console.WriteLine("How many books are you adding.");
        bookAmount = int.Parse(Console.ReadLine());

        for(int x = 0; x <= bookAmount; x++)
        {
            AddBook(book); 
        }
    }

    public void AddBook(Book book)
    {
        List<string> bookTitles = new List<string>(); 

        string bookTitle;

        Console.WriteLine("Enter title.");
        bookTitle = Console.ReadLine();
        bookTitles.Add(bookTitle);

        bookTitles = book.Title; // 'Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>'

    }
}

    class Book
{
    private string title;

    public string Title
    {
        get { return title; }
        set { title = value; }
    }

}

欢迎任何批评.先感谢您.

Any critique is welcome. Thank you in advance.

推荐答案

您要执行的操作如下:

public class Book
{
     public string ISBN { get; set; }
     public string Title {get; set; }
     public string Author {get; set; }
}

这本书将代表我们的数据模型.现在您将执行以下操作:

The book will represent our data model. Now you would do this:

List<Book> library = new List<Book>();
int quantity;
while(quantity < 7)
{
    library.Add("12345", "C#", "Someone");
}

代码在做什么,我们创建一个List<Book>,它将保存我们的数据模型.然后,您将有一个基于用户输入的值进行迭代的循环.然后,您只需调用库(列表)并在要求用户输入后添加即可.

What the code is doing, we create a List<Book> which will hold our data model. Then you would have a loop that iterates based on value the user inputs. Then you would simply call the library (List) and add after it ask the user for input.

很明显,我不是在尝试获取用户输入或验证,而是使用了如何使用List的示例.

Obviously I'm not attempting to get user input or validation, but is using the example of how to use a List.

这篇关于试图制作一个书架式控制台应用程序,但列表有些麻烦. (C#初学者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆