【发布时间】:2020-01-24 02:53:10
【问题描述】:
我正在尝试在 C# 中创建一个名为 customer 的类,其中包含 3 个变量:名称、初始存款和每月存款金额。
这是一个控制台程序,它接受用户输入这三个变量并不断要求更多用户,直到用户不输入任何内容并按下回车键。
然而,这条线
customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
给我错误。第一个 userInputName 带有下划线,表示 “不能在此范围内删除名为 'userInputName' 的本地或参数,因为该名称在封闭的本地范围中用于定义本地或参数”。第二个 'userInputName' 表示 “参数 1:无法从 'lab4.Program.customer' 转换为 'string'”。
我可以解决此问题的唯一方法是将第一个 'userInputName' 更改为类似 customer1 的名称,但如果我这样做,如果用户继续输入姓名,我将无法继续结交新客户。
理想情况下,我希望能够输入诸如 customer.Bob.initialDeposit 之类的内容,并让程序能够告诉我 Bob 的初始存款是什么,等等。
我怎样才能做到这一点,或者我做错了什么?
using System;
namespace lab4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many months will the customer keep the money in the account?");
string monthsString = Console.ReadLine();
int months = Int32.Parse(monthsString);
bool run = true;
while (run)
{
Console.WriteLine("Enter new customer name: ");
string userInputName = Console.ReadLine();
if (userInputName == "")
{
run = false;
}
else
{
Console.WriteLine("Enter initial deposit amount: ");
string stringInitDeposit = Console.ReadLine();
int userInputInitial = Int32.Parse(stringInitDeposit);
Console.WriteLine("Enter montly deposit amount: ");
string stringMonthDeposit = Console.ReadLine();
int userInputMonthly = Int32.Parse(stringMonthDeposit);
customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
}
}
}
public class customer
{
public string name;
public int initialDeposit;
public int monthlyDeposit;
public customer(string name, int initialDeposit, int monthlyDeposit)
{
this.name = name;
this.initialDeposit = initialDeposit;
this.monthlyDeposit = monthlyDeposit;
}
}
}
}
【问题讨论】:
-
“我可以解决这个问题的唯一方法是将第一个 'userInputName' 更改为 customer1 之类的东西” -- 不,一点也不。您还可以通过将第二个更改为
customer11或userInputName以外的任何其他内容来解决此问题。但是您的问题不可能提供一个好的答案,因为解决它的第三种方法是完全省略第二个userInputName变量。无论如何,您的代码永远不会对该变量执行任何操作,因此不清楚您实际期望在这里发生什么。请改进您的问题,以便清楚您真正需要什么。 -
我用代码写了我想要做的事情。 理想情况下,我希望能够输入诸如 customer.Bob.initialDeposit 之类的内容,并让程序能够告诉我 Bob 的初始存款是什么,等等。 我想让每个新客户的名字成为变量的名称,但从下面 ps2goat 的响应中,我明白我哪里出错了。