首页 > 解决方案 > 如何从用户输入创建对象 - C#

问题描述

我是 OOP 的初学者,最近开始使用 C# 进行编码。(在 Visual Studio 2017 控制台应用程序中工作。)搜索教程后,我会在这里试试运气。

我正在尝试制作一个简单的程序,允许用户通过询问他们的输入来制作一个新的对象书(或多个)。我知道如何手动创建类的对象,但不知道如何对用户输入做同样的事情。这是我到目前为止的代码:

public class book
{
    //variables
    private string title;
    private string author;
    private string genre;
    private string series;

    //constructor
    public book(string _titel, string _author, string _genre, string _series)
    {
        this.titel = _titel;
        this.author = _author;
        this.genre = _genre;
        this.series = _series;
    }

    //method to ask user for input to create book
    public void createBook()
    {

    }

标签: c#user-input

解决方案


Console.WriteLine("Input Title: ");
var title = Console.ReadLine();
Console.WriteLine("Input Author: "):
var author = Console.ReadLine();
etc..
var book = new Book(title,author etc...)

您将输入作为变量获取,然后从这些变量构造您的对象。


推荐阅读