C# 我已经创建了一个employee类和两个新的employee实例,但只有第一个employee info起作用
我已经搜索了你的网站,试图找出如何解决这个问题。我是c的新手,所以如果我问了一个新手问题,我道歉 我们刚开始上课,我觉得这不太麻烦。然而,在我们的第一个任务中,我创建了一个类别Employee,它计算出一个百分比,并计算出一个员工的加薪。在主程序中,我创建了两个新实例,e1和e2。我使用GetValue方法读取员工的数据。我的问题是,它对第一个员工非常有效,但不要求第二个员工提供输入。如何让程序读取和输出e1和e2的数据 我可以做一些循环或迭代来获得两个员工的输入吗 提前感谢,, 黛安 这是我的密码:C# 我已经创建了一个employee类和两个新的employee实例,但只有第一个employee info起作用,c#,C#,我已经搜索了你的网站,试图找出如何解决这个问题。我是c的新手,所以如果我问了一个新手问题,我道歉 我们刚开始上课,我觉得这不太麻烦。然而,在我们的第一个任务中,我创建了一个类别Employee,它计算出一个百分比,并计算出一个员工的加薪。在主程序中,我创建了两个新实例,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
当然,您只需要将信息收集部分包装成一个循环。这里有一个简单的例子。在下面的示例中,我还将employee对象添加到列表中,这样我们就不必维护对它们的单独引用
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);
}
在此场景中,创建员工是单独方法的候选方法 具体而言,此代码应调用两次:
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();
这可以重复/扩展,以容纳更多员工,在一个循环中,等等。您为两名员工提供了完全相同的值-您没有要求第二名员工提供新的或不同的输入