我已经搜索过您的网站,试图弄清楚如何解决这个问题。我是c#的新手,所以如果我问一个新手问题我会道歉。
我们刚刚开始上课,我觉得这并不太麻烦。但是,对于我们的第一个任务,我创建了一个类Employee,它占用一定比例并计算出员工的加薪。在主程序中,我创建了2个新实例,e1和e2。我使用GetValue方法读取员工的数据。我的问题是它对第一名员工很有用,但不要求第二名员工输入。如何让程序读取和输出e1和e2的数据?
我可以做一些循环或迭代来获取两个员工的输入吗?
提前致谢, 戴安
这是我的代码:
//identify the variables
string firstName, lastName, employeeID, department;
decimal salary;
firstName = GetValue("First Name");
lastName = GetValue("Last Name");
employeeID = GetValue("Employee ID");
department = GetValue("Employee Department");
salary = Convert.ToDecimal(GetValue("Salary"));
//create two employee objects
Employee e1 = new Employee(firstName, lastName, employeeID, salary, department);
Employee e2 = new Employee(firstName, lastName, employeeID, salary, department);
//get user input
//clear the screen
Console.Clear();
//Display the pay rise information
Console.WriteLine("Total increase in salary for employee 1 is {0}", e1);
Console.WriteLine("Total increase in salary for employee 2 is {0}", e2);
Console.ReadLine();
}//end of Main
static public string GetValue(string value)
{
Console.WriteLine("Please enter the {0} >>", value);
string input = Console.ReadLine();
return input;
}//end GetValue
答案 0 :(得分:1)
当然,您只需要将信息收集部分包装在一个循环中。这是一个简单的例子。在下面的示例中,我还将员工对象添加到列表中,因此我们不必对它们进行单独的单独引用。
var employees = new List<Employee>();
// Populate our list with two employees
for (int i = 0; i < 2; i++)
{
var firstName = GetValue("First Name");
var lastName = GetValue("Last Name");
var employeeID = GetValue("Employee ID");
var department = GetValue("Employee Department");
var salary = Convert.ToDecimal(GetValue("Salary"));
employees.Add(new Employee(firstName, lastName, employeeID, salary, department));
}
// Display the employee information:
var counter = 1;
foreach (var employee in employees)
{
Console.WriteLine("Total increase in salary for employee {0} is {1}",
counter++, employee);
}
答案 1 :(得分:0)
在此方案中,创建员工是单独方法的候选者。
具体来说,应该调用此代码两次:
string firstName, lastName, employeeID, department;
decimal salary;
firstName = GetValue("First Name");
lastName = GetValue("Last Name");
employeeID = GetValue("Employee ID");
department = GetValue("Employee Department");
salary = Convert.ToDecimal(GetValue("Salary"));
Employee e1 = new Employee(firstName, lastName, employeeID, salary, department);
您可以创建一个方法,例如:
static Employee ReadEmployeeFromInput()
{
//... all the code from the above snippet;
return e1;
}
然后,在您的主要方法中,阅读两名员工:
Employee e1 = ReadEmployeeFromInput();
Employee e2 = ReadEmployeeFromInput();
可以从那里重复/扩展,以便在一个循环中雇用更多员工等。