如何从用户输入创建对象-C#
我是OOP的初学者,最近开始用C#编写代码。(在Visual Studio 2017控制台应用程序中工作。) 在搜索教程之后,我将在这里试试运气 我正在尝试制作一个简单的程序,允许用户通过请求输入来制作一个新的对象书(或多个)。我知道如何手动创建类的对象,但不知道如何对用户输入执行相同的操作。这是我目前掌握的代码:如何从用户输入创建对象-C#,c#,user-input,C#,User Input,我是OOP的初学者,最近开始用C#编写代码。(在Visual Studio 2017控制台应用程序中工作。) 在搜索教程之后,我将在这里试试运气 我正在尝试制作一个简单的程序,允许用户通过请求输入来制作一个新的对象书(或多个)。我知道如何手动创建类的对象,但不知道如何对用户输入执行相同的操作。这是我目前掌握的代码: public class book { //variables private string title; private string author;
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()
{
}
将输入作为变量,然后从这些变量构造对象 createBook()不应在book类中。理论上,创建您的书是您的构造函数应该做的事情。您需要将createBook()放在它可以调用构造函数的某个地方,并使该书存在(并将void更改为book对象)
但如果你把它放在主要位置(或任何你想放的地方),你会想打电话
createBook(); // although you can't do much with it as it returns a void
并将您的函数定义为
void createBook(){
// get input for _titel, _author, _genre, _series
Book = book(_titel, _author, _genre, _series);
console.writeline("book created! such a shame all its a properties are private, because I'd really like to output the title or something.")
}
您的输入场景是什么?您正在使用控制台应用程序吗?Web app?由于您的
createBook
方法是类的一部分,因此在创建book
对象之前,无法调用createBook
。如果您想允许用户创建一本书,您应该在创建对象之前提示用户所有内容,然后使用用户提供的输入调用book
构造函数。那么到目前为止您可以做什么?你能要求用户输入并回复给他们吗?如果没有,可能是时候研究一下你书中的那一章了。应用程序会要求用户提供所有字符串,然后你创建对象并用这些字符串初始化它。在代码调用newbook()中创建book对象
那么您是否会创建另一个名为user的类,该类中有一个获取书籍详细信息的方法?例如:公共字符串getBookDetails(),它会要求用户输入titel、author等并返回这些信息?是的,这绝对是一种方法。
void createBook(){
// get input for _titel, _author, _genre, _series
Book = book(_titel, _author, _genre, _series);
console.writeline("book created! such a shame all its a properties are private, because I'd really like to output the title or something.")
}